blob: 78cdd0dd4a388433f1e708284ad1c923ef1de6b2 [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>
Siarhei Vishniakoud010b012023-01-18 15:00:53 -080023#include <android-base/logging.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080024#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080025#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050026#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070027#include <binder/Binder.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080028#include <ftl/enum.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070029#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050030#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070031#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080032#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080033#include <input/PrintTools.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070034#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010035#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070036#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080037
Michael Wright44753b12020-07-08 13:48:11 +010038#include <cerrno>
39#include <cinttypes>
40#include <climits>
41#include <cstddef>
42#include <ctime>
43#include <queue>
44#include <sstream>
45
46#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000047#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070048#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010049
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#define INDENT " "
51#define INDENT2 " "
52#define INDENT3 " "
53#define INDENT4 " "
54
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080055using namespace android::ftl::flag_operators;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080056using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000057using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080058using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070059using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050060using android::gui::FocusRequest;
61using android::gui::TouchOcclusionMode;
62using android::gui::WindowInfo;
63using android::gui::WindowInfoHandle;
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) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800152 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700153 case AMOTION_EVENT_ACTION_DOWN:
154 case AMOTION_EVENT_ACTION_UP:
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800155 return pointerCount == 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700156 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700157 case AMOTION_EVENT_ACTION_HOVER_ENTER:
158 case AMOTION_EVENT_ACTION_HOVER_MOVE:
159 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800160 return pointerCount >= 1;
161 case AMOTION_EVENT_ACTION_CANCEL:
162 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700163 case AMOTION_EVENT_ACTION_SCROLL:
164 return true;
165 case AMOTION_EVENT_ACTION_POINTER_DOWN:
166 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800167 const int32_t index = MotionEvent::getActionIndex(action);
168 return index >= 0 && index < pointerCount && pointerCount > 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700169 }
170 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
171 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
172 return actionButton != 0;
173 default:
174 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 }
176}
177
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000178int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500179 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
180}
181
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000182bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
183 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700184 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 ALOGE("Motion event has invalid action code 0x%x", action);
186 return false;
187 }
188 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800189 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %zu.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700190 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 return false;
192 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800193 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800194 for (size_t i = 0; i < pointerCount; i++) {
195 int32_t id = pointerProperties[i].id;
196 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700197 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
198 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800199 return false;
200 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800201 if (pointerIdBits.test(id)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800202 ALOGE("Motion event has duplicate pointer id %d", id);
203 return false;
204 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800205 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800206 }
207 return true;
208}
209
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000210std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000212 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800213 }
214
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000215 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 bool first = true;
217 Region::const_iterator cur = region.begin();
218 Region::const_iterator const tail = region.end();
219 while (cur != tail) {
220 if (first) {
221 first = false;
222 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800223 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800224 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800225 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226 cur++;
227 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000228 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800229}
230
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000231std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500232 constexpr size_t maxEntries = 50; // max events to print
233 constexpr size_t skipBegin = maxEntries / 2;
234 const size_t skipEnd = queue.size() - maxEntries / 2;
235 // skip from maxEntries / 2 ... size() - maxEntries/2
236 // only print from 0 .. skipBegin and then from skipEnd .. size()
237
238 std::string dump;
239 for (size_t i = 0; i < queue.size(); i++) {
240 const DispatchEntry& entry = *queue[i];
241 if (i >= skipBegin && i < skipEnd) {
242 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
243 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
244 continue;
245 }
246 dump.append(INDENT4);
247 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800248 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
249 "ms",
250 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500251 ns2ms(currentTime - entry.eventEntry->eventTime));
252 if (entry.deliveryTime != 0) {
253 // This entry was delivered, so add information on how long we've been waiting
254 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
255 }
256 dump.append("\n");
257 }
258 return dump;
259}
260
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700261/**
262 * Find the entry in std::unordered_map by key, and return it.
263 * If the entry is not found, return a default constructed entry.
264 *
265 * Useful when the entries are vectors, since an empty vector will be returned
266 * if the entry is not found.
267 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
268 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700269template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000270V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700271 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700272 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800273}
274
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000275bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700276 if (first == second) {
277 return true;
278 }
279
280 if (first == nullptr || second == nullptr) {
281 return false;
282 }
283
284 return first->getToken() == second->getToken();
285}
286
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000287bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000288 if (first == nullptr || second == nullptr) {
289 return false;
290 }
291 return first->applicationInfo.token != nullptr &&
292 first->applicationInfo.token == second->applicationInfo.token;
293}
294
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800295template <typename T>
296size_t firstMarkedBit(T set) {
297 // TODO: replace with std::countr_zero from <bit> when that's available
298 LOG_ALWAYS_FATAL_IF(set.none());
299 size_t i = 0;
300 while (!set.test(i)) {
301 i++;
302 }
303 return i;
304}
305
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800306std::unique_ptr<DispatchEntry> createDispatchEntry(
307 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
308 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700309 if (inputTarget.useDefaultPointerTransform()) {
310 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700311 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700312 inputTarget.displayTransform,
313 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000314 }
315
316 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
317 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
318
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700319 std::vector<PointerCoords> pointerCoords;
320 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000321
322 // Use the first pointer information to normalize all other pointers. This could be any pointer
323 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700324 // uses the transform for the normalized pointer.
325 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800326 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700327 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000328
329 // Iterate through all pointers in the event to normalize against the first.
330 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
331 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
332 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700333 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000334
335 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700336 // First, apply the current pointer's transform to update the coordinates into
337 // window space.
338 pointerCoords[pointerIndex].transform(currTransform);
339 // Next, apply the inverse transform of the normalized coordinates so the
340 // current coordinates are transformed into the normalized coordinate space.
341 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000342 }
343
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700344 std::unique_ptr<MotionEntry> combinedMotionEntry =
345 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
346 motionEntry.deviceId, motionEntry.source,
347 motionEntry.displayId, motionEntry.policyFlags,
348 motionEntry.action, motionEntry.actionButton,
349 motionEntry.flags, motionEntry.metaState,
350 motionEntry.buttonState, motionEntry.classification,
351 motionEntry.edgeFlags, motionEntry.xPrecision,
352 motionEntry.yPrecision, motionEntry.xCursorPosition,
353 motionEntry.yCursorPosition, motionEntry.downTime,
354 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000355 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000356
357 if (motionEntry.injectionState) {
358 combinedMotionEntry->injectionState = motionEntry.injectionState;
359 combinedMotionEntry->injectionState->refCount += 1;
360 }
361
362 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700363 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700364 firstPointerTransform, inputTarget.displayTransform,
365 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000366 return dispatchEntry;
367}
368
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000369status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
370 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700371 std::unique_ptr<InputChannel> uniqueServerChannel;
372 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
373
374 serverChannel = std::move(uniqueServerChannel);
375 return result;
376}
377
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500378template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000379bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500380 if (lhs == nullptr && rhs == nullptr) {
381 return true;
382 }
383 if (lhs == nullptr || rhs == nullptr) {
384 return false;
385 }
386 return *lhs == *rhs;
387}
388
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000389KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000390 KeyEvent event;
391 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
392 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
393 entry.repeatCount, entry.downTime, entry.eventTime);
394 return event;
395}
396
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000397bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000398 // Do not keep track of gesture monitors. They receive every event and would disproportionately
399 // affect the statistics.
400 if (connection.monitor) {
401 return false;
402 }
403 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
404 if (!connection.responsive) {
405 return false;
406 }
407 return true;
408}
409
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000410bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000411 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
412 const int32_t& inputEventId = eventEntry.id;
413 if (inputEventId != dispatchEntry.resolvedEventId) {
414 // Event was transmuted
415 return false;
416 }
417 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
418 return false;
419 }
420 // Only track latency for events that originated from hardware
421 if (eventEntry.isSynthesized()) {
422 return false;
423 }
424 const EventEntry::Type& inputEventEntryType = eventEntry.type;
425 if (inputEventEntryType == EventEntry::Type::KEY) {
426 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
427 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
428 return false;
429 }
430 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
431 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
432 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
433 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
434 return false;
435 }
436 } else {
437 // Not a key or a motion
438 return false;
439 }
440 if (!shouldReportMetricsForConnection(connection)) {
441 return false;
442 }
443 return true;
444}
445
Prabir Pradhancef936d2021-07-21 16:17:52 +0000446/**
447 * Connection is responsive if it has no events in the waitQueue that are older than the
448 * current time.
449 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000450bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000451 const nsecs_t currentTime = now();
452 for (const DispatchEntry* entry : connection.waitQueue) {
453 if (entry->timeoutTime < currentTime) {
454 return false;
455 }
456 }
457 return true;
458}
459
Antonio Kantekf16f2832021-09-28 04:39:20 +0000460// Returns true if the event type passed as argument represents a user activity.
461bool isUserActivityEvent(const EventEntry& eventEntry) {
462 switch (eventEntry.type) {
463 case EventEntry::Type::FOCUS:
464 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
465 case EventEntry::Type::DRAG:
466 case EventEntry::Type::TOUCH_MODE_CHANGED:
467 case EventEntry::Type::SENSOR:
468 case EventEntry::Type::CONFIGURATION_CHANGED:
469 return false;
470 case EventEntry::Type::DEVICE_RESET:
471 case EventEntry::Type::KEY:
472 case EventEntry::Type::MOTION:
473 return true;
474 }
475}
476
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800477// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhand65552b2021-10-07 11:23:50 -0700478bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, int32_t x, int32_t y,
479 bool isStylus) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800480 const auto inputConfig = windowInfo.inputConfig;
481 if (windowInfo.displayId != displayId ||
482 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800483 return false;
484 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700485 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800486 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800487 return false;
488 }
Prabir Pradhan06349042022-02-04 09:19:17 -0800489 if (!windowInfo.touchableRegionContainsPoint(x, y)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800490 return false;
491 }
492 return true;
493}
494
Prabir Pradhand65552b2021-10-07 11:23:50 -0700495bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
496 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000497 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700498}
499
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800500// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000501// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
502// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
503// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800504// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000505bool canReceiveForegroundTouches(const WindowInfo& info) {
506 // A non-touchable window can still receive touch events (e.g. in the case of
507 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
508 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
509}
510
Antonio Kantek48710e42022-03-24 14:19:30 -0700511bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
512 if (windowHandle == nullptr) {
513 return false;
514 }
515 const WindowInfo* windowInfo = windowHandle->getInfo();
516 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
517 return true;
518 }
519 return false;
520}
521
Prabir Pradhan5735a322022-04-11 17:23:34 +0000522// Checks targeted injection using the window's owner's uid.
523// Returns an empty string if an entry can be sent to the given window, or an error message if the
524// entry is a targeted injection whose uid target doesn't match the window owner.
525std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
526 const EventEntry& entry) {
527 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
528 // The event was not injected, or the injected event does not target a window.
529 return {};
530 }
531 const int32_t uid = *entry.injectionState->targetUid;
532 if (window == nullptr) {
533 return StringPrintf("No valid window target for injection into uid %d.", uid);
534 }
535 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
536 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
537 "owned by uid %d.",
538 uid, window->getName().c_str(), window->getInfo()->ownerUid);
539 }
540 return {};
541}
542
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700543Point resolveTouchedPosition(const MotionEntry& entry) {
544 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
545 // Always dispatch mouse events to cursor position.
546 if (isFromMouse) {
547 return Point(static_cast<int32_t>(entry.xCursorPosition),
548 static_cast<int32_t>(entry.yCursorPosition));
549 }
550
551 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
552 return Point(static_cast<int32_t>(
553 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X)),
554 static_cast<int32_t>(
555 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)));
556}
557
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700558std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
559 if (eventEntry.type == EventEntry::Type::KEY) {
560 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
561 return keyEntry.downTime;
562 } else if (eventEntry.type == EventEntry::Type::MOTION) {
563 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
564 return motionEntry.downTime;
565 }
566 return std::nullopt;
567}
568
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000569/**
570 * Compare the old touch state to the new touch state, and generate the corresponding touched
571 * windows (== input targets).
572 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
573 * If the pointer just entered the new window, produce HOVER_ENTER.
574 * For pointers remaining in the window, produce HOVER_MOVE.
575 */
576std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
577 const TouchState& newTouchState,
578 const MotionEntry& entry) {
579 std::vector<TouchedWindow> out;
580 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
581 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
582 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
583 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
584 // Not a hover event - don't need to do anything
585 return out;
586 }
587
588 // We should consider all hovering pointers here. But for now, just use the first one
589 const int32_t pointerId = entry.pointerProperties[0].id;
590
591 std::set<sp<WindowInfoHandle>> oldWindows;
592 if (oldState != nullptr) {
593 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
594 }
595
596 std::set<sp<WindowInfoHandle>> newWindows =
597 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
598
599 // If the pointer is no longer in the new window set, send HOVER_EXIT.
600 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
601 if (newWindows.find(oldWindow) == newWindows.end()) {
602 TouchedWindow touchedWindow;
603 touchedWindow.windowHandle = oldWindow;
604 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800605 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000606 out.push_back(touchedWindow);
607 }
608 }
609
610 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
611 TouchedWindow touchedWindow;
612 touchedWindow.windowHandle = newWindow;
613 if (oldWindows.find(newWindow) == oldWindows.end()) {
614 // Any windows that have this pointer now, and didn't have it before, should get
615 // HOVER_ENTER
616 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
617 } else {
618 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
619 LOG_ALWAYS_FATAL_IF(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE);
620 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
621 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800622 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000623 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
624 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
625 }
626 out.push_back(touchedWindow);
627 }
628 return out;
629}
630
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800631template <typename T>
632std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
633 left.insert(left.end(), right.begin(), right.end());
634 return left;
635}
636
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000637} // namespace
638
Michael Wrightd02c5b62014-02-10 15:10:22 -0800639// --- InputDispatcher ---
640
Garfield Tan00f511d2019-06-12 16:55:40 -0700641InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800642 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
643
644InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
645 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700646 : mPolicy(policy),
647 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700648 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800649 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700650 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700651 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700652 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800653 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700654 mDispatchEnabled(false),
655 mDispatchFrozen(false),
656 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100657 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000658 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800659 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800660 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000661 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000662 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700663 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800664 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800665
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700666 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700667#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700668 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700669#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700670 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800671 policy->getDispatcherConfiguration(&mConfig);
672}
673
674InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000675 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800676
Prabir Pradhancef936d2021-07-21 16:17:52 +0000677 resetKeyRepeatLocked();
678 releasePendingEventLocked();
679 drainInboundQueueLocked();
680 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000682 while (!mConnectionsByToken.empty()) {
683 sp<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000684 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800685 }
686}
687
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700688status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700689 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700690 return ALREADY_EXISTS;
691 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700692 mThread = std::make_unique<InputThread>(
693 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
694 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700695}
696
697status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700698 if (mThread && mThread->isCallingThread()) {
699 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700700 return INVALID_OPERATION;
701 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700702 mThread.reset();
703 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700704}
705
Michael Wrightd02c5b62014-02-10 15:10:22 -0800706void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700707 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800709 std::scoped_lock _l(mLock);
710 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800711
712 // Run a dispatch loop if there are no pending commands.
713 // The dispatch loop might enqueue commands to run afterwards.
714 if (!haveCommandsLocked()) {
715 dispatchOnceInnerLocked(&nextWakeupTime);
716 }
717
718 // Run all pending commands if there are any.
719 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000720 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700721 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800722 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800723
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700724 // If we are still waiting for ack on some events,
725 // we might have to wake up earlier to check if an app is anr'ing.
726 const nsecs_t nextAnrCheck = processAnrsLocked();
727 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
728
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800729 // We are about to enter an infinitely long sleep, because we have no commands or
730 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700731 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800732 mDispatcherEnteredIdle.notify_all();
733 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800734 } // release lock
735
736 // Wait for callback or timeout or wake. (make sure we round up, not down)
737 nsecs_t currentTime = now();
738 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
739 mLooper->pollOnce(timeoutMillis);
740}
741
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700742/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500743 * Raise ANR if there is no focused window.
744 * Before the ANR is raised, do a final state check:
745 * 1. The currently focused application must be the same one we are waiting for.
746 * 2. Ensure we still don't have a focused window.
747 */
748void InputDispatcher::processNoFocusedWindowAnrLocked() {
749 // Check if the application that we are waiting for is still focused.
750 std::shared_ptr<InputApplicationHandle> focusedApplication =
751 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
752 if (focusedApplication == nullptr ||
753 focusedApplication->getApplicationToken() !=
754 mAwaitedFocusedApplication->getApplicationToken()) {
755 // Unexpected because we should have reset the ANR timer when focused application changed
756 ALOGE("Waited for a focused window, but focused application has already changed to %s",
757 focusedApplication->getName().c_str());
758 return; // The focused application has changed.
759 }
760
chaviw98318de2021-05-19 16:45:23 -0500761 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500762 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
763 if (focusedWindowHandle != nullptr) {
764 return; // We now have a focused window. No need for ANR.
765 }
766 onAnrLocked(mAwaitedFocusedApplication);
767}
768
769/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700770 * Check if any of the connections' wait queues have events that are too old.
771 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
772 * Return the time at which we should wake up next.
773 */
774nsecs_t InputDispatcher::processAnrsLocked() {
775 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700776 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700777 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
778 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
779 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500780 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700781 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500782 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700783 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700784 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500785 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700786 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
787 }
788 }
789
790 // Check if any connection ANRs are due
791 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
792 if (currentTime < nextAnrCheck) { // most likely scenario
793 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
794 }
795
796 // If we reached here, we have an unresponsive connection.
797 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
798 if (connection == nullptr) {
799 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
800 return nextAnrCheck;
801 }
802 connection->responsive = false;
803 // Stop waking up for this unresponsive connection
804 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000805 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700806 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700807}
808
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800809std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
810 const sp<Connection>& connection) {
811 if (connection->monitor) {
812 return mMonitorDispatchingTimeout;
813 }
814 const sp<WindowInfoHandle> window =
815 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700816 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500817 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700818 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500819 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700820}
821
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
823 nsecs_t currentTime = now();
824
Jeff Browndc5992e2014-04-11 01:27:26 -0700825 // Reset the key repeat timer whenever normal dispatch is suspended while the
826 // device is in a non-interactive state. This is to ensure that we abort a key
827 // repeat if the device is just coming out of sleep.
828 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800829 resetKeyRepeatLocked();
830 }
831
832 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
833 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100834 if (DEBUG_FOCUS) {
835 ALOGD("Dispatch frozen. Waiting some more.");
836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837 return;
838 }
839
840 // Optimize latency of app switches.
841 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
842 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
843 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
844 if (mAppSwitchDueTime < *nextWakeupTime) {
845 *nextWakeupTime = mAppSwitchDueTime;
846 }
847
848 // Ready to start a new event.
849 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700850 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700851 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800852 if (isAppSwitchDue) {
853 // The inbound queue is empty so the app switch key we were waiting
854 // for will never arrive. Stop waiting for it.
855 resetPendingAppSwitchLocked(false);
856 isAppSwitchDue = false;
857 }
858
859 // Synthesize a key repeat if appropriate.
860 if (mKeyRepeatState.lastKeyEntry) {
861 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
862 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
863 } else {
864 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
865 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
866 }
867 }
868 }
869
870 // Nothing to do if there is no pending event.
871 if (!mPendingEvent) {
872 return;
873 }
874 } else {
875 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700876 mPendingEvent = mInboundQueue.front();
877 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878 traceInboundQueueLengthLocked();
879 }
880
881 // Poke user activity for this event.
882 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700883 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800885 }
886
887 // Now we have an event to dispatch.
888 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700889 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700891 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700893 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700895 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 }
897
898 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700899 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900 }
901
902 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700903 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700904 const ConfigurationChangedEntry& typedEntry =
905 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700906 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700907 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700908 break;
909 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800910
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700911 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700912 const DeviceResetEntry& typedEntry =
913 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700914 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700915 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700916 break;
917 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800918
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100919 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700920 std::shared_ptr<FocusEntry> typedEntry =
921 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100922 dispatchFocusLocked(currentTime, typedEntry);
923 done = true;
924 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
925 break;
926 }
927
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700928 case EventEntry::Type::TOUCH_MODE_CHANGED: {
929 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
930 dispatchTouchModeChangeLocked(currentTime, typedEntry);
931 done = true;
932 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
933 break;
934 }
935
Prabir Pradhan99987712020-11-10 18:43:05 -0800936 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
937 const auto typedEntry =
938 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
939 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
940 done = true;
941 break;
942 }
943
arthurhungb89ccb02020-12-30 16:19:01 +0800944 case EventEntry::Type::DRAG: {
945 std::shared_ptr<DragEntry> typedEntry =
946 std::static_pointer_cast<DragEntry>(mPendingEvent);
947 dispatchDragLocked(currentTime, typedEntry);
948 done = true;
949 break;
950 }
951
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700952 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700953 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700954 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700955 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700956 resetPendingAppSwitchLocked(true);
957 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700958 } else if (dropReason == DropReason::NOT_DROPPED) {
959 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700960 }
961 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700962 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700963 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700964 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700965 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
966 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700967 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700968 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700969 break;
970 }
971
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700972 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700973 std::shared_ptr<MotionEntry> motionEntry =
974 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700975 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
976 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700978 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700979 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700980 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700981 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
982 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700983 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700984 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700985 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986 }
Chris Yef59a2f42020-10-16 12:55:26 -0700987
988 case EventEntry::Type::SENSOR: {
989 std::shared_ptr<SensorEntry> sensorEntry =
990 std::static_pointer_cast<SensorEntry>(mPendingEvent);
991 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
992 dropReason = DropReason::APP_SWITCH;
993 }
994 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
995 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
996 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
997 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
998 dropReason = DropReason::STALE;
999 }
1000 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1001 done = true;
1002 break;
1003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004 }
1005
1006 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001007 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001008 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001009 }
Michael Wright3a981722015-06-10 15:26:13 +01001010 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011
1012 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001013 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 }
1015}
1016
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001017bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1018 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1019}
1020
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001021/**
1022 * Return true if the events preceding this incoming motion event should be dropped
1023 * Return false otherwise (the default behaviour)
1024 */
1025bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001026 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001027 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001028
1029 // Optimize case where the current application is unresponsive and the user
1030 // decides to touch a window in a different application.
1031 // If the application takes too long to catch up then we drop all events preceding
1032 // the touch into the other window.
1033 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001034 const int32_t displayId = motionEntry.displayId;
1035 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001036 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001037
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001038 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001039 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001040 touchedWindowHandle->getApplicationToken() !=
1041 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001042 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001043 ALOGI("Pruning input queue because user touched a different application while waiting "
1044 "for %s",
1045 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001046 return true;
1047 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001048
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001049 // Alternatively, maybe there's a spy window that could handle this event.
1050 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1051 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1052 for (const auto& windowHandle : touchedSpies) {
1053 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001054 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001055 // This spy window could take more input. Drop all events preceding this
1056 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001057 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001058 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001059 mAwaitedFocusedApplication->getName().c_str());
1060 return true;
1061 }
1062 }
1063 }
1064
1065 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1066 // yet been processed by some connections, the dispatcher will wait for these motion
1067 // events to be processed before dispatching the key event. This is because these motion events
1068 // may cause a new window to be launched, which the user might expect to receive focus.
1069 // To prevent waiting forever for such events, just send the key to the currently focused window
1070 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1071 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1072 "just send the pending key event to the focused window.");
1073 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001074 }
1075 return false;
1076}
1077
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001078bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001079 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001080 mInboundQueue.push_back(std::move(newEntry));
1081 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082 traceInboundQueueLengthLocked();
1083
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001084 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001085 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001086 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1087 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001088 // Optimize app switch latency.
1089 // If the application takes too long to catch up then we drop all events preceding
1090 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001091 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001092 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001093 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001094 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001095 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001096 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001097 if (DEBUG_APP_SWITCH) {
1098 ALOGD("App switch is pending!");
1099 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001100 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001101 mAppSwitchSawKeyDown = false;
1102 needWake = true;
1103 }
1104 }
1105 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001106
1107 // If a new up event comes in, and the pending event with same key code has been asked
1108 // to try again later because of the policy. We have to reset the intercept key wake up
1109 // time for it may have been handled in the policy and could be dropped.
1110 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1111 mPendingEvent->type == EventEntry::Type::KEY) {
1112 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1113 if (pendingKey.keyCode == keyEntry.keyCode &&
1114 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001115 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1116 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001117 pendingKey.interceptKeyWakeupTime = 0;
1118 needWake = true;
1119 }
1120 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001121 break;
1122 }
1123
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001124 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001125 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1126 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001127 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1128 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001129 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001131 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001132 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001133 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001134 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1135 break;
1136 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001137 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001138 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001139 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001140 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001141 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1142 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001143 // nothing to do
1144 break;
1145 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146 }
1147
1148 return needWake;
1149}
1150
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001151void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001152 // Do not store sensor event in recent queue to avoid flooding the queue.
1153 if (entry->type != EventEntry::Type::SENSOR) {
1154 mRecentQueue.push_back(entry);
1155 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001156 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001157 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001158 }
1159}
1160
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001161std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
1162InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x, int32_t y, bool isStylus,
1163 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001165 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001166 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001167 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001168 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001169 continue;
1170 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001172 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001173 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001174 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001175 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001176
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001177 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1178 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001179 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001180 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 }
1182 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001183 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184}
1185
Prabir Pradhand65552b2021-10-07 11:23:50 -07001186std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1187 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001188 // Traverse windows from front to back and gather the touched spy windows.
1189 std::vector<sp<WindowInfoHandle>> spyWindows;
1190 const auto& windowHandles = getWindowHandlesLocked(displayId);
1191 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1192 const WindowInfo& info = *windowHandle->getInfo();
1193
Prabir Pradhand65552b2021-10-07 11:23:50 -07001194 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001195 continue;
1196 }
1197 if (!info.isSpy()) {
1198 // The first touched non-spy window was found, so return the spy windows touched so far.
1199 return spyWindows;
1200 }
1201 spyWindows.push_back(windowHandle);
1202 }
1203 return spyWindows;
1204}
1205
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001206void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207 const char* reason;
1208 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001209 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001210 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001211 ALOGD("Dropped event because policy consumed it.");
1212 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001213 reason = "inbound event was dropped because the policy consumed it";
1214 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001215 case DropReason::DISABLED:
1216 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001217 ALOGI("Dropped event because input dispatch is disabled.");
1218 }
1219 reason = "inbound event was dropped because input dispatch is disabled";
1220 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001221 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001222 ALOGI("Dropped event because of pending overdue app switch.");
1223 reason = "inbound event was dropped because of pending overdue app switch";
1224 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001225 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001226 ALOGI("Dropped event because the current application is not responding and the user "
1227 "has started interacting with a different application.");
1228 reason = "inbound event was dropped because the current application is not responding "
1229 "and the user has started interacting with a different application";
1230 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001231 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001232 ALOGI("Dropped event because it is stale.");
1233 reason = "inbound event was dropped because it is stale";
1234 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001235 case DropReason::NO_POINTER_CAPTURE:
1236 ALOGI("Dropped event because there is no window with Pointer Capture.");
1237 reason = "inbound event was dropped because there is no window with Pointer Capture";
1238 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001239 case DropReason::NOT_DROPPED: {
1240 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001241 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001242 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 }
1244
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001245 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001246 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001247 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001249 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001251 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001252 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1253 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001254 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001255 synthesizeCancelationEventsForAllConnectionsLocked(options);
1256 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001257 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1258 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001259 synthesizeCancelationEventsForAllConnectionsLocked(options);
1260 }
1261 break;
1262 }
Chris Yef59a2f42020-10-16 12:55:26 -07001263 case EventEntry::Type::SENSOR: {
1264 break;
1265 }
arthurhungb89ccb02020-12-30 16:19:01 +08001266 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1267 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001268 break;
1269 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001270 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001271 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001272 case EventEntry::Type::CONFIGURATION_CHANGED:
1273 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001274 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001275 break;
1276 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277 }
1278}
1279
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001280static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001281 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1282 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283}
1284
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001285bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1286 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1287 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1288 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001289}
1290
1291bool InputDispatcher::isAppSwitchPendingLocked() {
Colin Cross5b799302022-10-18 21:52:41 -07001292 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293}
1294
1295void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001296 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001297
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001298 if (DEBUG_APP_SWITCH) {
1299 if (handled) {
1300 ALOGD("App switch has arrived.");
1301 } else {
1302 ALOGD("App switch was abandoned.");
1303 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001305}
1306
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001308 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309}
1310
Prabir Pradhancef936d2021-07-21 16:17:52 +00001311bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001312 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313 return false;
1314 }
1315
1316 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001317 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001318 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001319 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1320 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001321 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 return true;
1323}
1324
Prabir Pradhancef936d2021-07-21 16:17:52 +00001325void InputDispatcher::postCommandLocked(Command&& command) {
1326 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001327}
1328
1329void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001330 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001331 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001332 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001333 releaseInboundEventLocked(entry);
1334 }
1335 traceInboundQueueLengthLocked();
1336}
1337
1338void InputDispatcher::releasePendingEventLocked() {
1339 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001341 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001342 }
1343}
1344
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001345void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001346 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001347 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001348 if (DEBUG_DISPATCH_CYCLE) {
1349 ALOGD("Injected inbound event was dropped.");
1350 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001351 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352 }
1353 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001354 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355 }
1356 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001357}
1358
1359void InputDispatcher::resetKeyRepeatLocked() {
1360 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001361 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 }
1363}
1364
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001365std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1366 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001367
Michael Wright2e732952014-09-24 13:26:59 -07001368 uint32_t policyFlags = entry->policyFlags &
1369 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001371 std::shared_ptr<KeyEntry> newEntry =
1372 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1373 entry->source, entry->displayId, policyFlags, entry->action,
1374 entry->flags, entry->keyCode, entry->scanCode,
1375 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001377 newEntry->syntheticRepeat = true;
1378 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001379 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001380 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381}
1382
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001383bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001384 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001385 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1386 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1387 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388
1389 // Reset key repeating in case a keyboard device was added or removed or something.
1390 resetKeyRepeatLocked();
1391
1392 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001393 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1394 scoped_unlock unlock(mLock);
1395 mPolicy->notifyConfigurationChanged(eventTime);
1396 };
1397 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001398 return true;
1399}
1400
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001401bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1402 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001403 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1404 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1405 entry.deviceId);
1406 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001407
liushenxiang42232912021-05-21 20:24:09 +08001408 // Reset key repeating in case a keyboard device was disabled or enabled.
1409 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1410 resetKeyRepeatLocked();
1411 }
1412
Michael Wrightfb04fd52022-11-24 22:31:11 +00001413 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001414 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415 synthesizeCancelationEventsForAllConnectionsLocked(options);
1416 return true;
1417}
1418
Vishnu Nairad321cd2020-08-20 16:40:21 -07001419void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001420 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001421 if (mPendingEvent != nullptr) {
1422 // Move the pending event to the front of the queue. This will give the chance
1423 // for the pending event to get dispatched to the newly focused window
1424 mInboundQueue.push_front(mPendingEvent);
1425 mPendingEvent = nullptr;
1426 }
1427
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001428 std::unique_ptr<FocusEntry> focusEntry =
1429 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1430 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001431
1432 // This event should go to the front of the queue, but behind all other focus events
1433 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001434 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001435 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001436 [](const std::shared_ptr<EventEntry>& event) {
1437 return event->type == EventEntry::Type::FOCUS;
1438 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001439
1440 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001441 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001442}
1443
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001444void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001445 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001446 if (channel == nullptr) {
1447 return; // Window has gone away
1448 }
1449 InputTarget target;
1450 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001451 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001452 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001453 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1454 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001455 std::string reason = std::string("reason=").append(entry->reason);
1456 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001457 dispatchEventLocked(currentTime, entry, {target});
1458}
1459
Prabir Pradhan99987712020-11-10 18:43:05 -08001460void InputDispatcher::dispatchPointerCaptureChangedLocked(
1461 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1462 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001463 dropReason = DropReason::NOT_DROPPED;
1464
Prabir Pradhan99987712020-11-10 18:43:05 -08001465 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001466 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001467
1468 if (entry->pointerCaptureRequest.enable) {
1469 // Enable Pointer Capture.
1470 if (haveWindowWithPointerCapture &&
1471 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001472 // This can happen if pointer capture is disabled and re-enabled before we notify the
1473 // app of the state change, so there is no need to notify the app.
1474 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1475 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001476 }
1477 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001478 // This can happen if a window requests capture and immediately releases capture.
1479 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001480 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001481 return;
1482 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001483 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1484 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1485 return;
1486 }
1487
Vishnu Nairc519ff72021-01-21 08:23:08 -08001488 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001489 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1490 mWindowTokenWithPointerCapture = token;
1491 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001492 // Disable Pointer Capture.
1493 // We do not check if the sequence number matches for requests to disable Pointer Capture
1494 // for two reasons:
1495 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1496 // to disable capture with the same sequence number: one generated by
1497 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1498 // Capture being disabled in InputReader.
1499 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1500 // actual Pointer Capture state that affects events being generated by input devices is
1501 // in InputReader.
1502 if (!haveWindowWithPointerCapture) {
1503 // Pointer capture was already forcefully disabled because of focus change.
1504 dropReason = DropReason::NOT_DROPPED;
1505 return;
1506 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001507 token = mWindowTokenWithPointerCapture;
1508 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001509 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001510 setPointerCaptureLocked(false);
1511 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001512 }
1513
1514 auto channel = getInputChannelLocked(token);
1515 if (channel == nullptr) {
1516 // Window has gone away, clean up Pointer Capture state.
1517 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001518 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001519 setPointerCaptureLocked(false);
1520 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001521 return;
1522 }
1523 InputTarget target;
1524 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001525 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001526 entry->dispatchInProgress = true;
1527 dispatchEventLocked(currentTime, entry, {target});
1528
1529 dropReason = DropReason::NOT_DROPPED;
1530}
1531
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001532void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1533 const std::shared_ptr<TouchModeEntry>& entry) {
1534 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001535 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001536 if (windowHandles.empty()) {
1537 return;
1538 }
1539 const std::vector<InputTarget> inputTargets =
1540 getInputTargetsFromWindowHandlesLocked(windowHandles);
1541 if (inputTargets.empty()) {
1542 return;
1543 }
1544 entry->dispatchInProgress = true;
1545 dispatchEventLocked(currentTime, entry, inputTargets);
1546}
1547
1548std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1549 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1550 std::vector<InputTarget> inputTargets;
1551 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001552 const sp<IBinder>& token = handle->getToken();
1553 if (token == nullptr) {
1554 continue;
1555 }
1556 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1557 if (channel == nullptr) {
1558 continue; // Window has gone away
1559 }
1560 InputTarget target;
1561 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001562 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001563 inputTargets.push_back(target);
1564 }
1565 return inputTargets;
1566}
1567
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001568bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001569 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001571 if (!entry->dispatchInProgress) {
1572 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1573 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1574 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1575 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001576 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577 // We have seen two identical key downs in a row which indicates that the device
1578 // driver is automatically generating key repeats itself. We take note of the
1579 // repeat here, but we disable our own next key repeat timer since it is clear that
1580 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001581 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1582 // Make sure we don't get key down from a different device. If a different
1583 // device Id has same key pressed down, the new device Id will replace the
1584 // current one to hold the key repeat with repeat count reset.
1585 // In the future when got a KEY_UP on the device id, drop it and do not
1586 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1588 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001589 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590 } else {
1591 // Not a repeat. Save key down state in case we do see a repeat later.
1592 resetKeyRepeatLocked();
1593 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1594 }
1595 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001596 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1597 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001598 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001599 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001600 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1601 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001602 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603 resetKeyRepeatLocked();
1604 }
1605
1606 if (entry->repeatCount == 1) {
1607 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1608 } else {
1609 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1610 }
1611
1612 entry->dispatchInProgress = true;
1613
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001614 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 }
1616
1617 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001618 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001619 if (currentTime < entry->interceptKeyWakeupTime) {
1620 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1621 *nextWakeupTime = entry->interceptKeyWakeupTime;
1622 }
1623 return false; // wait until next wakeup
1624 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001625 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626 entry->interceptKeyWakeupTime = 0;
1627 }
1628
1629 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001630 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001631 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001632 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001633 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001634
1635 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1636 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1637 };
1638 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001639 return false; // wait for the command to run
1640 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001641 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001643 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001644 if (*dropReason == DropReason::NOT_DROPPED) {
1645 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001646 }
1647 }
1648
1649 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001650 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001651 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001652 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1653 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001654 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 return true;
1656 }
1657
1658 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001659 InputEventInjectionResult injectionResult;
1660 sp<WindowInfoHandle> focusedWindow =
1661 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1662 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001663 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 return false;
1665 }
1666
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001667 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001668 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 return true;
1670 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001671 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1672
1673 std::vector<InputTarget> inputTargets;
1674 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001675 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001676 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001677
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001678 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001679 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680
1681 // Dispatch the key.
1682 dispatchEventLocked(currentTime, entry, inputTargets);
1683 return true;
1684}
1685
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001686void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001687 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1688 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1689 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1690 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1691 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1692 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1693 entry.metaState, entry.repeatCount, entry.downTime);
1694 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695}
1696
Prabir Pradhancef936d2021-07-21 16:17:52 +00001697void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1698 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001699 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001700 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1701 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1702 "source=0x%x, sensorType=%s",
1703 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001704 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001705 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001706 auto command = [this, entry]() REQUIRES(mLock) {
1707 scoped_unlock unlock(mLock);
1708
1709 if (entry->accuracyChanged) {
1710 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1711 }
1712 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1713 entry->hwTimestamp, entry->values);
1714 };
1715 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001716}
1717
1718bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001719 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1720 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001721 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001722 }
Chris Yef59a2f42020-10-16 12:55:26 -07001723 { // acquire lock
1724 std::scoped_lock _l(mLock);
1725
1726 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1727 std::shared_ptr<EventEntry> entry = *it;
1728 if (entry->type == EventEntry::Type::SENSOR) {
1729 it = mInboundQueue.erase(it);
1730 releaseInboundEventLocked(entry);
1731 }
1732 }
1733 }
1734 return true;
1735}
1736
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001737bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001738 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001739 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001741 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 entry->dispatchInProgress = true;
1743
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001744 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745 }
1746
1747 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001748 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001749 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001750 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1751 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752 return true;
1753 }
1754
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001755 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756
1757 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001758 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759
1760 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001761 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762 if (isPointerEvent) {
1763 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001764
1765 if (mDragState &&
1766 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1767 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1768 pilferPointersLocked(mDragState->dragWindow->getToken());
1769 }
1770
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001771 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001772 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001773 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001774 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1775 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776 } else {
1777 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001778 sp<WindowInfoHandle> focusedWindow =
1779 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1780 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1781 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1782 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001783 InputTarget::Flags::FOREGROUND |
1784 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001785 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001786 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001788 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 return false;
1790 }
1791
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001792 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001793 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001794 return true;
1795 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001796 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001797 CancelationOptions::Mode mode(
1798 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1799 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001800 CancelationOptions options(mode, "input event injection failed");
1801 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802 return true;
1803 }
1804
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001805 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001806 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001807
1808 // Dispatch the motion.
1809 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001810 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001811 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 synthesizeCancelationEventsForAllConnectionsLocked(options);
1813 }
1814 dispatchEventLocked(currentTime, entry, inputTargets);
1815 return true;
1816}
1817
chaviw98318de2021-05-19 16:45:23 -05001818void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001819 bool isExiting, const int32_t rawX,
1820 const int32_t rawY) {
1821 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001822 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001823 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1824 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001825
1826 enqueueInboundEventLocked(std::move(dragEntry));
1827}
1828
1829void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1830 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1831 if (channel == nullptr) {
1832 return; // Window has gone away
1833 }
1834 InputTarget target;
1835 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001836 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001837 entry->dispatchInProgress = true;
1838 dispatchEventLocked(currentTime, entry, {target});
1839}
1840
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001841void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001842 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001843 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001844 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001845 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001846 "metaState=0x%x, buttonState=0x%x,"
1847 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001848 prefix, entry.eventTime, entry.deviceId,
1849 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1850 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1851 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1852 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001854 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1855 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1856 "x=%f, y=%f, pressure=%f, size=%f, "
1857 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1858 "orientation=%f",
1859 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1860 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1861 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1862 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1863 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1864 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1865 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1866 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1867 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1868 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871}
1872
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001873void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1874 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001875 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001876 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001877 if (DEBUG_DISPATCH_CYCLE) {
1878 ALOGD("dispatchEventToCurrentInputTargets");
1879 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001880
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001881 updateInteractionTokensLocked(*eventEntry, inputTargets);
1882
Michael Wrightd02c5b62014-02-10 15:10:22 -08001883 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1884
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001885 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001887 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001888 sp<Connection> connection =
1889 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001890 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001891 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001893 if (DEBUG_FOCUS) {
1894 ALOGD("Dropping event delivery to target with channel '%s' because it "
1895 "is no longer registered with the input dispatcher.",
1896 inputTarget.inputChannel->getName().c_str());
1897 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898 }
1899 }
1900}
1901
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001902void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1903 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1904 // If the policy decides to close the app, we will get a channel removal event via
1905 // unregisterInputChannel, and will clean up the connection that way. We are already not
1906 // sending new pointers to the connection when it blocked, but focused events will continue to
1907 // pile up.
1908 ALOGW("Canceling events for %s because it is unresponsive",
1909 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001910 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001911 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001912 "application not responding");
1913 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914 }
1915}
1916
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001917void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001918 if (DEBUG_FOCUS) {
1919 ALOGD("Resetting ANR timeouts.");
1920 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921
1922 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001923 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001924 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925}
1926
Tiger Huang721e26f2018-07-24 22:26:19 +08001927/**
1928 * Get the display id that the given event should go to. If this event specifies a valid display id,
1929 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1930 * Focused display is the display that the user most recently interacted with.
1931 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001932int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001933 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001934 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001935 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001936 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1937 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001938 break;
1939 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001940 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001941 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1942 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001943 break;
1944 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001945 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001946 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001947 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001948 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001949 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001950 case EventEntry::Type::SENSOR:
1951 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001952 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001953 return ADISPLAY_ID_NONE;
1954 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001955 }
1956 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1957}
1958
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001959bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1960 const char* focusedWindowName) {
1961 if (mAnrTracker.empty()) {
1962 // already processed all events that we waited for
1963 mKeyIsWaitingForEventsTimeout = std::nullopt;
1964 return false;
1965 }
1966
1967 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1968 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001969 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001970 mKeyIsWaitingForEventsTimeout = currentTime +
1971 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1972 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001973 return true;
1974 }
1975
1976 // We still have pending events, and already started the timer
1977 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1978 return true; // Still waiting
1979 }
1980
1981 // Waited too long, and some connection still hasn't processed all motions
1982 // Just send the key to the focused window
1983 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1984 focusedWindowName);
1985 mKeyIsWaitingForEventsTimeout = std::nullopt;
1986 return false;
1987}
1988
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001989sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
1990 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
1991 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001992 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001993 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994
Tiger Huang721e26f2018-07-24 22:26:19 +08001995 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001996 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001997 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001998 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1999
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000 // If there is no currently focused window and no focused application
2001 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002002 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2003 ALOGI("Dropping %s event because there is no focused window or focused application in "
2004 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002005 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002006 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007 }
2008
Vishnu Nair062a8672021-09-03 16:07:44 -07002009 // Drop key events if requested by input feature
2010 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002011 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002012 }
2013
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002014 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2015 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2016 // start interacting with another application via touch (app switch). This code can be removed
2017 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2018 // an app is expected to have a focused window.
2019 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2020 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2021 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002022 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2023 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2024 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002025 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002026 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002027 ALOGW("Waiting because no window has focus but %s may eventually add a "
2028 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002029 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002030 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002031 outInjectionResult = InputEventInjectionResult::PENDING;
2032 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002033 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2034 // Already raised ANR. Drop the event
2035 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002036 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002037 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002038 } else {
2039 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002040 outInjectionResult = InputEventInjectionResult::PENDING;
2041 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002042 }
2043 }
2044
2045 // we have a valid, non-null focused window
2046 resetNoFocusedWindowTimeoutLocked();
2047
Prabir Pradhan5735a322022-04-11 17:23:34 +00002048 // Verify targeted injection.
2049 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2050 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002051 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2052 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053 }
2054
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002055 if (focusedWindowHandle->getInfo()->inputConfig.test(
2056 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002057 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002058 outInjectionResult = InputEventInjectionResult::PENDING;
2059 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002060 }
2061
2062 // If the event is a key event, then we must wait for all previous events to
2063 // complete before delivering it because previous events may have the
2064 // side-effect of transferring focus to a different window and we want to
2065 // ensure that the following keys are sent to the new window.
2066 //
2067 // Suppose the user touches a button in a window then immediately presses "A".
2068 // If the button causes a pop-up window to appear then we want to ensure that
2069 // the "A" key is delivered to the new pop-up window. This is because users
2070 // often anticipate pending UI changes when typing on a keyboard.
2071 // To obtain this behavior, we must serialize key events with respect to all
2072 // prior input events.
2073 if (entry.type == EventEntry::Type::KEY) {
2074 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2075 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002076 outInjectionResult = InputEventInjectionResult::PENDING;
2077 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002078 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079 }
2080
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002081 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2082 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083}
2084
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002085/**
2086 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2087 * that are currently unresponsive.
2088 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002089std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2090 const std::vector<Monitor>& monitors) const {
2091 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002092 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002093 [this](const Monitor& monitor) REQUIRES(mLock) {
2094 sp<Connection> connection =
2095 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002096 if (connection == nullptr) {
2097 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002098 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002099 return false;
2100 }
2101 if (!connection->responsive) {
2102 ALOGW("Unresponsive monitor %s will not get the new gesture",
2103 connection->inputChannel->getName().c_str());
2104 return false;
2105 }
2106 return true;
2107 });
2108 return responsiveMonitors;
2109}
2110
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002111/**
2112 * In general, touch should be always split between windows. Some exceptions:
2113 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2114 * from the same device, *and* the window that's receiving the current pointer does not support
2115 * split touch.
2116 * 2. Don't split mouse events
2117 */
2118bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2119 const MotionEntry& entry) const {
2120 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2121 // We should never split mouse events
2122 return false;
2123 }
2124 for (const TouchedWindow& touchedWindow : touchState.windows) {
2125 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2126 // Spy windows should not affect whether or not touch is split.
2127 continue;
2128 }
2129 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2130 continue;
2131 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002132 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2133 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2134 // Wallpaper window should not affect whether or not touch is split
2135 continue;
2136 }
2137
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002138 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2139 // being sent there. For now, use deviceId from touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002140 if (entry.deviceId == touchState.deviceId && touchedWindow.pointerIds.any()) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002141 return false;
2142 }
2143 }
2144 return true;
2145}
2146
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002147std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002148 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2149 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002150 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002151
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002152 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 // For security reasons, we defer updating the touch state until we are sure that
2154 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002155 const int32_t displayId = entry.displayId;
2156 const int32_t action = entry.action;
2157 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158
2159 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002160 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002162 // Copy current touch state into tempTouchState.
2163 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2164 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002165 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002166 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002167 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2168 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002169 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002170 }
2171
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002172 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002173 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002174 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002175
2176 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2177 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2178 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002179 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2180 // touchable windows.
2181 const bool wasDown = oldState != nullptr && oldState->isDown();
2182 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2183 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
2184 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002185 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002186
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002187 // If pointers are already down, let's finish the current gesture and ignore the new events
2188 // from another device. However, if the new event is a down event, let's cancel the current
2189 // touch and let the new one take over.
2190 if (switchedDevice && wasDown && !isDown) {
2191 LOG(INFO) << "Dropping event because a pointer for device " << oldState->deviceId
2192 << " is already down in display " << displayId << ": " << entry.getDescription();
2193 // TODO(b/211379801): test multiple simultaneous input streams.
2194 outInjectionResult = InputEventInjectionResult::FAILED;
2195 return {}; // wrong device
2196 }
2197
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002199 // If a new gesture is starting, clear the touch state completely.
2200 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002201 tempTouchState.deviceId = entry.deviceId;
2202 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002203 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002204 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002205 ALOGI("Dropping move event because a pointer for a different device is already active "
2206 "in display %" PRId32,
2207 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002208 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002209 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002210 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211 }
2212
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002213 if (isHoverAction) {
2214 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2215 // all of the existing hovering pointers and recompute.
2216 tempTouchState.clearHoveringPointers();
2217 }
2218
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2220 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002221 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002222 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002223 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2224 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002225 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002226 auto [newTouchedWindowHandle, outsideTargets] =
2227 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002228
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002229 if (isDown) {
2230 targets += outsideTargets;
2231 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002233 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002234 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2235 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002237 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002238 }
2239
Prabir Pradhan5735a322022-04-11 17:23:34 +00002240 // Verify targeted injection.
2241 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2242 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002243 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002244 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002245 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002246 }
2247
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002248 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002249 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002250 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2251 // New window supports splitting, but we should never split mouse events.
2252 isSplit = !isFromMouse;
2253 } else if (isSplit) {
2254 // New window does not support splitting but we have already split events.
2255 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002256 newTouchedWindowHandle = nullptr;
2257 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002258 } else {
2259 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002260 // be delivered to a new window which supports split touch. Pointers from a mouse device
2261 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002262 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002263 }
2264
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002265 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002266 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002267 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002268 // Process the foreground window first so that it is the first to receive the event.
2269 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002270 }
2271
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002272 if (newTouchedWindows.empty()) {
2273 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2274 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002275 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002276 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002277 }
2278
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002279 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002280 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002281 continue;
2282 }
2283
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002284 if (isHoverAction) {
2285 const int32_t pointerId = entry.pointerProperties[0].id;
2286 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2287 // Pointer left. Remove it
2288 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2289 } else {
2290 // The "windowHandle" is the target of this hovering pointer.
2291 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId,
2292 pointerId);
2293 }
2294 }
2295
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002296 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002297 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002298
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002299 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2300 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002301 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002302 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002303
2304 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002305 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002306 }
2307 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002308 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002309 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002310 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002311 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002312
2313 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002314 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002315 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002316 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002317 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002318
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002319 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2320 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2321
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002322 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2323 // still add a window to the touch state. We should avoid doing that, but some of the
2324 // later checks ("at least one foreground window") rely on this in order to dispatch
2325 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002326 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002327 isDownOrPointerDown
2328 ? std::make_optional(entry.eventTime)
2329 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002330
2331 // If this is the pointer going down and the touched window has a wallpaper
2332 // then also add the touched wallpaper windows so they are locked in for the duration
2333 // of the touch gesture.
2334 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2335 // engine only supports touch events. We would need to add a mechanism similar
2336 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002337 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002338 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2339 windowHandle->getInfo()->inputConfig.test(
2340 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2341 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2342 if (wallpaper != nullptr) {
2343 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2344 InputTarget::Flags::WINDOW_IS_OBSCURED |
2345 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2346 InputTarget::Flags::DISPATCH_AS_IS;
2347 if (isSplit) {
2348 wallpaperFlags |= InputTarget::Flags::SPLIT;
2349 }
2350 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2351 entry.eventTime);
2352 }
2353 }
2354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002356
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002357 // If a window is already pilfering some pointers, give it this new pointer as well and
2358 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2359 // which is a specific behaviour that we want.
2360 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2361 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002362 if (touchedWindow.pointerIds.test(pointerId) &&
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002363 touchedWindow.pilferedPointerIds.count() > 0) {
2364 // This window is already pilfering some pointers, and this new pointer is also
2365 // going to it. Therefore, take over this pointer and don't give it to anyone
2366 // else.
2367 touchedWindow.pilferedPointerIds.set(pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002368 }
2369 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002370
2371 // Restrict all pilfered pointers to the pilfering windows.
2372 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002373 } else {
2374 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2375
2376 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002377 if (!tempTouchState.isDown()) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002378 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2379 "dropped the pointer down event in display "
2380 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002381 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002382 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002383 }
2384
arthurhung6d4bed92021-03-17 11:59:33 +08002385 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002386
Michael Wrightd02c5b62014-02-10 15:10:22 -08002387 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002388 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002389 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002390 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002391 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002392 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002393 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002394 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002395
Prabir Pradhan5735a322022-04-11 17:23:34 +00002396 // Verify targeted injection.
2397 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2398 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002399 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002400 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002401 }
2402
Vishnu Nair062a8672021-09-03 16:07:44 -07002403 // Drop touch events if requested by input feature
2404 if (newTouchedWindowHandle != nullptr &&
2405 shouldDropInput(entry, newTouchedWindowHandle)) {
2406 newTouchedWindowHandle = nullptr;
2407 }
2408
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002409 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2410 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002411 if (DEBUG_FOCUS) {
2412 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2413 oldTouchedWindowHandle->getName().c_str(),
2414 newTouchedWindowHandle->getName().c_str(), displayId);
2415 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002416 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002417 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002418 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002419 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002420
2421 const TouchedWindow& touchedWindow =
2422 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2423 addWindowTargetLocked(oldTouchedWindowHandle,
2424 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
2425 touchedWindow.firstDownTimeInTarget, targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002426
2427 // Make a slippery entrance into the new window.
2428 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002429 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002430 }
2431
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002432 ftl::Flags<InputTarget::Flags> targetFlags =
2433 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002434 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002435 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002438 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002439 }
2440 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002441 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002442 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002443 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002444 }
2445
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002446 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2447 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002448
2449 // Check if the wallpaper window should deliver the corresponding event.
2450 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002451 tempTouchState, pointerId, targets);
2452 tempTouchState.removeTouchedPointerFromWindow(pointerId, oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002453 }
2454 }
Arthur Hung96483742022-11-15 03:30:48 +00002455
2456 // Update the pointerIds for non-splittable when it received pointer down.
2457 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2458 // If no split, we suppose all touched windows should receive pointer down.
2459 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2460 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2461 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2462 // Ignore drag window for it should just track one pointer.
2463 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2464 continue;
2465 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002466 touchedWindow.pointerIds.set(entry.pointerProperties[pointerIndex].id);
Arthur Hung96483742022-11-15 03:30:48 +00002467 }
2468 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469 }
2470
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002471 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002472 {
2473 std::vector<TouchedWindow> hoveringWindows =
2474 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2475 for (const TouchedWindow& touchedWindow : hoveringWindows) {
2476 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2477 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2478 targets);
2479 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002480 }
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002481 // Ensure that we have at least one foreground window or at least one window that cannot be a
2482 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2483 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2484 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002485 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2486 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002487 return !canReceiveForegroundTouches(
2488 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002489 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002490 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002491 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2492 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002493 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002494 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002495 }
2496
Prabir Pradhan5735a322022-04-11 17:23:34 +00002497 // Ensure that all touched windows are valid for injection.
2498 if (entry.injectionState != nullptr) {
2499 std::string errs;
2500 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002501 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002502 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2503 // dispatched to any uid, since the coords will be zeroed out later.
2504 continue;
2505 }
2506 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2507 if (err) errs += "\n - " + *err;
2508 }
2509 if (!errs.empty()) {
2510 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2511 "%d:%s",
2512 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002513 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002514 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002515 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002516 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002517
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002518 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2519 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002520 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002521 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002522 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002523 if (foregroundWindowHandle) {
2524 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002525 for (InputTarget& target : targets) {
2526 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2527 sp<WindowInfoHandle> targetWindow =
2528 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2529 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2530 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532 }
2533 }
2534 }
2535 }
2536
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002537 // Success! Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002538 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002539 if (touchedWindow.pointerIds.none() && !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002540 // Windows with hovering pointers are getting persisted inside TouchState.
2541 // Do not send this event to those windows.
2542 continue;
2543 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002544 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2545 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2546 targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002547 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002548
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002549 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002550 // Drop the outside or hover touch windows since we will not care about them
2551 // in the next iteration.
2552 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553
Michael Wrightd02c5b62014-02-10 15:10:22 -08002554 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002555 if (switchedDevice) {
2556 if (DEBUG_FOCUS) {
2557 ALOGD("Conflicting pointer actions: Switched to a different device.");
2558 }
2559 *outConflictingPointerActions = true;
2560 }
2561
2562 if (isHoverAction) {
2563 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002564 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002565 ALOGD_IF(DEBUG_FOCUS,
2566 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002567 *outConflictingPointerActions = true;
2568 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002569 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2570 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2571 tempTouchState.deviceId = entry.deviceId;
2572 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002573 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002574 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2575 // Pointer went up.
2576 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002577 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002578 // All pointers up or canceled.
2579 tempTouchState.reset();
2580 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2581 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002582 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2583 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002584 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002585 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002586 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2587 // One pointer went up.
2588 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2589 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002590
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002591 for (size_t i = 0; i < tempTouchState.windows.size();) {
2592 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002593 touchedWindow.pointerIds.reset(pointerId);
2594 if (touchedWindow.pointerIds.none()) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002595 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2596 continue;
2597 }
2598 i += 1;
2599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600 }
2601
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002602 // Save changes unless the action was scroll in which case the temporary touch
2603 // state was only valid for this one action.
2604 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002605 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002606 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002607 mTouchStatesByDisplay[displayId] = tempTouchState;
2608 } else {
2609 mTouchStatesByDisplay.erase(displayId);
2610 }
2611 }
2612
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002613 if (tempTouchState.windows.empty()) {
2614 mTouchStatesByDisplay.erase(displayId);
2615 }
2616
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002617 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002618}
2619
arthurhung6d4bed92021-03-17 11:59:33 +08002620void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002621 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2622 // have an explicit reason to support it.
2623 constexpr bool isStylus = false;
2624
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002625 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002626 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002627 if (dropWindow) {
2628 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002629 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002630 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002631 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002632 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002633 }
2634 mDragState.reset();
2635}
2636
2637void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002638 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002639 return;
2640 }
2641
arthurhung6d4bed92021-03-17 11:59:33 +08002642 if (!mDragState->isStartDrag) {
2643 mDragState->isStartDrag = true;
2644 mDragState->isStylusButtonDownAtStart =
2645 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2646 }
2647
Arthur Hung54745652022-04-20 07:17:41 +00002648 // Find the pointer index by id.
2649 int32_t pointerIndex = 0;
2650 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2651 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2652 if (pointerProperties.id == mDragState->pointerId) {
2653 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002654 }
Arthur Hung54745652022-04-20 07:17:41 +00002655 }
arthurhung6d4bed92021-03-17 11:59:33 +08002656
Arthur Hung54745652022-04-20 07:17:41 +00002657 if (uint32_t(pointerIndex) == entry.pointerCount) {
2658 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002659 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002660 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002661 return;
2662 }
2663
2664 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2665 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2666 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2667
2668 switch (maskedAction) {
2669 case AMOTION_EVENT_ACTION_MOVE: {
2670 // Handle the special case : stylus button no longer pressed.
2671 bool isStylusButtonDown =
2672 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2673 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2674 finishDragAndDrop(entry.displayId, x, y);
2675 return;
2676 }
2677
2678 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2679 // until we have an explicit reason to support it.
2680 constexpr bool isStylus = false;
2681
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002682 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002683 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002684 // enqueue drag exit if needed.
2685 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2686 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2687 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002688 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002689 y);
2690 }
2691 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2692 }
2693 // enqueue drag location if needed.
2694 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002695 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002696 }
2697 break;
2698 }
2699
2700 case AMOTION_EVENT_ACTION_POINTER_UP:
2701 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2702 break;
2703 }
2704 // The drag pointer is up.
2705 [[fallthrough]];
2706 case AMOTION_EVENT_ACTION_UP:
2707 finishDragAndDrop(entry.displayId, x, y);
2708 break;
2709 case AMOTION_EVENT_ACTION_CANCEL: {
2710 ALOGD("Receiving cancel when drag and drop.");
2711 sendDropWindowCommandLocked(nullptr, 0, 0);
2712 mDragState.reset();
2713 break;
2714 }
arthurhungb89ccb02020-12-30 16:19:01 +08002715 }
2716}
2717
chaviw98318de2021-05-19 16:45:23 -05002718void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002719 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002720 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002721 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002722 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002723 std::vector<InputTarget>::iterator it =
2724 std::find_if(inputTargets.begin(), inputTargets.end(),
2725 [&windowHandle](const InputTarget& inputTarget) {
2726 return inputTarget.inputChannel->getConnectionToken() ==
2727 windowHandle->getToken();
2728 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002729
chaviw98318de2021-05-19 16:45:23 -05002730 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002731
2732 if (it == inputTargets.end()) {
2733 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002734 std::shared_ptr<InputChannel> inputChannel =
2735 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002736 if (inputChannel == nullptr) {
2737 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2738 return;
2739 }
2740 inputTarget.inputChannel = inputChannel;
2741 inputTarget.flags = targetFlags;
2742 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002743 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002744 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2745 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002746 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002747 } else {
Siarhei Vishniakoua06bb552023-02-07 09:38:56 -08002748 // DisplayInfo not found for this window on display windowInfo->displayId.
2749 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002750 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002751 inputTargets.push_back(inputTarget);
2752 it = inputTargets.end() - 1;
2753 }
2754
2755 ALOG_ASSERT(it->flags == targetFlags);
2756 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2757
chaviw1ff3d1e2020-07-01 15:53:47 -07002758 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759}
2760
Michael Wright3dd60e22019-03-27 22:06:44 +00002761void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002762 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002763 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2764 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002765
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002766 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2767 InputTarget target;
2768 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002769 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002770 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2771 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002772 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2773 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002774 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002775 target.setDefaultPointerTransform(target.displayTransform);
2776 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777 }
2778}
2779
Robert Carrc9bf1d32020-04-13 17:21:08 -07002780/**
2781 * Indicate whether one window handle should be considered as obscuring
2782 * another window handle. We only check a few preconditions. Actually
2783 * checking the bounds is left to the caller.
2784 */
chaviw98318de2021-05-19 16:45:23 -05002785static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2786 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002787 // Compare by token so cloned layers aren't counted
2788 if (haveSameToken(windowHandle, otherHandle)) {
2789 return false;
2790 }
2791 auto info = windowHandle->getInfo();
2792 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002793 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002794 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002795 } else if (otherInfo->alpha == 0 &&
2796 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002797 // Those act as if they were invisible, so we don't need to flag them.
2798 // We do want to potentially flag touchable windows even if they have 0
2799 // opacity, since they can consume touches and alter the effects of the
2800 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002801 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002802 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2803 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002804 } else if (info->ownerUid == otherInfo->ownerUid) {
2805 // If ownerUid is the same we don't generate occlusion events as there
2806 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002807 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002808 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002809 return false;
2810 } else if (otherInfo->displayId != info->displayId) {
2811 return false;
2812 }
2813 return true;
2814}
2815
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002816/**
2817 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2818 * untrusted, one should check:
2819 *
2820 * 1. If result.hasBlockingOcclusion is true.
2821 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2822 * BLOCK_UNTRUSTED.
2823 *
2824 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2825 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2826 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2827 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2828 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2829 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2830 *
2831 * If neither of those is true, then it means the touch can be allowed.
2832 */
2833InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002834 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2835 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002836 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002837 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002838 TouchOcclusionInfo info;
2839 info.hasBlockingOcclusion = false;
2840 info.obscuringOpacity = 0;
2841 info.obscuringUid = -1;
2842 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002843 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002844 if (windowHandle == otherHandle) {
2845 break; // All future windows are below us. Exit early.
2846 }
chaviw98318de2021-05-19 16:45:23 -05002847 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002848 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2849 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002850 if (DEBUG_TOUCH_OCCLUSION) {
2851 info.debugInfo.push_back(
2852 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2853 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002854 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2855 // we perform the checks below to see if the touch can be propagated or not based on the
2856 // window's touch occlusion mode
2857 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2858 info.hasBlockingOcclusion = true;
2859 info.obscuringUid = otherInfo->ownerUid;
2860 info.obscuringPackage = otherInfo->packageName;
2861 break;
2862 }
2863 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2864 uint32_t uid = otherInfo->ownerUid;
2865 float opacity =
2866 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2867 // Given windows A and B:
2868 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2869 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2870 opacityByUid[uid] = opacity;
2871 if (opacity > info.obscuringOpacity) {
2872 info.obscuringOpacity = opacity;
2873 info.obscuringUid = uid;
2874 info.obscuringPackage = otherInfo->packageName;
2875 }
2876 }
2877 }
2878 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002879 if (DEBUG_TOUCH_OCCLUSION) {
2880 info.debugInfo.push_back(
2881 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2882 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002883 return info;
2884}
2885
chaviw98318de2021-05-19 16:45:23 -05002886std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002887 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002888 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2889 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2890 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2891 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002892 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2893 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2894 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2895 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2896 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002897 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002898 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002899}
2900
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002901bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2902 if (occlusionInfo.hasBlockingOcclusion) {
2903 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2904 occlusionInfo.obscuringUid);
2905 return false;
2906 }
2907 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2908 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2909 "%.2f, maximum allowed = %.2f)",
2910 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2911 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2912 return false;
2913 }
2914 return true;
2915}
2916
chaviw98318de2021-05-19 16:45:23 -05002917bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002918 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002920 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2921 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002922 if (windowHandle == otherHandle) {
2923 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002924 }
chaviw98318de2021-05-19 16:45:23 -05002925 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002926 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002927 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928 return true;
2929 }
2930 }
2931 return false;
2932}
2933
chaviw98318de2021-05-19 16:45:23 -05002934bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002935 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002936 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2937 const WindowInfo* windowInfo = windowHandle->getInfo();
2938 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002939 if (windowHandle == otherHandle) {
2940 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002941 }
chaviw98318de2021-05-19 16:45:23 -05002942 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002943 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002944 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002945 return true;
2946 }
2947 }
2948 return false;
2949}
2950
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002951std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002952 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002953 if (applicationHandle != nullptr) {
2954 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002955 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002956 } else {
2957 return applicationHandle->getName();
2958 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002959 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002960 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002961 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002962 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002963 }
2964}
2965
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002966void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002967 if (!isUserActivityEvent(eventEntry)) {
2968 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002969 return;
2970 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002971 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002972 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002973 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002974 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002975 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002976 if (DEBUG_DISPATCH_CYCLE) {
2977 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2978 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002979 return;
2980 }
2981 }
2982
2983 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002984 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002985 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002986 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2987 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002988 return;
2989 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002990
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002991 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002992 eventType = USER_ACTIVITY_EVENT_TOUCH;
2993 }
2994 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002995 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002996 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002997 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2998 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002999 return;
3000 }
3001 eventType = USER_ACTIVITY_EVENT_BUTTON;
3002 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003003 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003004 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003005 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003006 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003007 break;
3008 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003009 }
3010
Prabir Pradhancef936d2021-07-21 16:17:52 +00003011 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3012 REQUIRES(mLock) {
3013 scoped_unlock unlock(mLock);
3014 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
3015 };
3016 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017}
3018
3019void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003020 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003021 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003022 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003023 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003024 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003025 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003026 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003027 ATRACE_NAME(message.c_str());
3028 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003029 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003030 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003031 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003032 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003033 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003034 inputTarget.getPointerInfoString().c_str());
3035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003036
3037 // Skip this event if the connection status is not normal.
3038 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003039 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003040 if (DEBUG_DISPATCH_CYCLE) {
3041 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003042 connection->getInputChannelName().c_str(),
3043 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003044 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003045 return;
3046 }
3047
3048 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003049 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003050 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003051 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003052 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003053
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003054 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003055 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003056 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3057 logDispatchStateLocked();
3058 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3059 "target on connection "
3060 << connection->getInputChannelName() << " for "
3061 << originalMotionEntry.getDescription();
3062 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003063 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003064 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3065 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066 if (!splitMotionEntry) {
3067 return; // split event was dropped
3068 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003069 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3070 std::string reason = std::string("reason=pointer cancel on split window");
3071 android_log_event_list(LOGTAG_INPUT_CANCEL)
3072 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3073 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003074 if (DEBUG_FOCUS) {
3075 ALOGD("channel '%s' ~ Split motion event.",
3076 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003077 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003078 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003079 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3080 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003081 return;
3082 }
3083 }
3084
3085 // Not splitting. Enqueue dispatch entries for the event as is.
3086 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3087}
3088
3089void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003090 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003091 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003092 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003093 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003094 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003095 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003096 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003097 ATRACE_NAME(message.c_str());
3098 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003099 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3100 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003101
hongzuo liu95785e22022-09-06 02:51:35 +00003102 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103
3104 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003105 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003106 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003107 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003108 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003109 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003110 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003111 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003112 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003113 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003114 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003115 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003116 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117
3118 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003119 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003120 startDispatchCycleLocked(currentTime, connection);
3121 }
3122}
3123
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003124void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003125 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003126 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003127 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003128 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003129 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3130 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003131 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003132 ATRACE_NAME(message.c_str());
3133 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003134 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3135 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003136 return;
3137 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003138
3139 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3140 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003141
3142 // This is a new event.
3143 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003144 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003145 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003146
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003147 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3148 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003149 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003151 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003152 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003153 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003154 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003155 dispatchEntry->resolvedAction = keyEntry.action;
3156 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003158 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3159 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003160 if (DEBUG_DISPATCH_CYCLE) {
3161 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3162 "event",
3163 connection->getInputChannelName().c_str());
3164 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003165 return; // skip the inconsistent event
3166 }
3167 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003170 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003171 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003172 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3173 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3174 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3175 static_cast<int32_t>(IdGenerator::Source::OTHER);
3176 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003177 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003178 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003179 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003180 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003181 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003182 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003183 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003184 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003185 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003186 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3187 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003188 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003189 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003190 }
3191 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003192 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3193 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003194 if (DEBUG_DISPATCH_CYCLE) {
3195 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3196 "enter event",
3197 connection->getInputChannelName().c_str());
3198 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003199 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3200 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003201 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3202 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003204 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003205 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3206 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3207 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003208 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003209 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3210 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003211 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003212 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3213 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003215 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3216 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003217 if (DEBUG_DISPATCH_CYCLE) {
3218 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3219 "event",
3220 connection->getInputChannelName().c_str());
3221 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003222 return; // skip the inconsistent event
3223 }
3224
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003225 dispatchEntry->resolvedEventId =
3226 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3227 ? mIdGenerator.nextId()
3228 : motionEntry.id;
3229 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3230 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3231 ") to MotionEvent(id=0x%" PRIx32 ").",
3232 motionEntry.id, dispatchEntry->resolvedEventId);
3233 ATRACE_NAME(message.c_str());
3234 }
3235
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003236 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3237 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3238 // Skip reporting pointer down outside focus to the policy.
3239 break;
3240 }
3241
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003242 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003243 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003244
3245 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003247 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003248 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003249 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3250 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003251 break;
3252 }
Chris Yef59a2f42020-10-16 12:55:26 -07003253 case EventEntry::Type::SENSOR: {
3254 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3255 break;
3256 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003257 case EventEntry::Type::CONFIGURATION_CHANGED:
3258 case EventEntry::Type::DEVICE_RESET: {
3259 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003260 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003261 break;
3262 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003263 }
3264
3265 // Remember that we are waiting for this dispatch to complete.
3266 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003267 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003268 }
3269
3270 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003271 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003272 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003273}
3274
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003275/**
3276 * This function is purely for debugging. It helps us understand where the user interaction
3277 * was taking place. For example, if user is touching launcher, we will see a log that user
3278 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3279 * We will see both launcher and wallpaper in that list.
3280 * Once the interaction with a particular set of connections starts, no new logs will be printed
3281 * until the set of interacted connections changes.
3282 *
3283 * The following items are skipped, to reduce the logspam:
3284 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3285 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3286 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3287 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3288 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003289 */
3290void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3291 const std::vector<InputTarget>& targets) {
3292 // Skip ACTION_UP events, and all events other than keys and motions
3293 if (entry.type == EventEntry::Type::KEY) {
3294 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3295 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3296 return;
3297 }
3298 } else if (entry.type == EventEntry::Type::MOTION) {
3299 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3300 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3301 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3302 return;
3303 }
3304 } else {
3305 return; // Not a key or a motion
3306 }
3307
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003308 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003309 std::vector<sp<Connection>> newConnections;
3310 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003311 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003312 continue; // Skip windows that receive ACTION_OUTSIDE
3313 }
3314
3315 sp<IBinder> token = target.inputChannel->getConnectionToken();
3316 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003317 if (connection == nullptr) {
3318 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003319 }
3320 newConnectionTokens.insert(std::move(token));
3321 newConnections.emplace_back(connection);
3322 }
3323 if (newConnectionTokens == mInteractionConnectionTokens) {
3324 return; // no change
3325 }
3326 mInteractionConnectionTokens = newConnectionTokens;
3327
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003328 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003329 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003330 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003331 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003332 std::string message = "Interaction with: " + targetList;
3333 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003334 message += "<none>";
3335 }
3336 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3337}
3338
chaviwfd6d3512019-03-25 13:23:49 -07003339void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003340 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003341 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003342 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3343 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003344 return;
3345 }
3346
Vishnu Nairc519ff72021-01-21 08:23:08 -08003347 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003348 if (focusedToken == token) {
3349 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003350 return;
3351 }
3352
Prabir Pradhancef936d2021-07-21 16:17:52 +00003353 auto command = [this, token]() REQUIRES(mLock) {
3354 scoped_unlock unlock(mLock);
3355 mPolicy->onPointerDownOutsideFocus(token);
3356 };
3357 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003358}
3359
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003360status_t InputDispatcher::publishMotionEvent(Connection& connection,
3361 DispatchEntry& dispatchEntry) const {
3362 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3363 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3364
3365 PointerCoords scaledCoords[MAX_POINTERS];
3366 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3367
3368 // Set the X and Y offset and X and Y scale depending on the input source.
3369 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003370 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003371 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3372 if (globalScaleFactor != 1.0f) {
3373 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3374 scaledCoords[i] = motionEntry.pointerCoords[i];
3375 // Don't apply window scale here since we don't want scale to affect raw
3376 // coordinates. The scale will be sent back to the client and applied
3377 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003378 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003379 }
3380 usingCoords = scaledCoords;
3381 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003382 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003383 // We don't want the dispatch target to know the coordinates
3384 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3385 scaledCoords[i].clear();
3386 }
3387 usingCoords = scaledCoords;
3388 }
3389
3390 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3391
3392 // Publish the motion event.
3393 return connection.inputPublisher
3394 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3395 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3396 std::move(hmac), dispatchEntry.resolvedAction,
3397 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3398 motionEntry.edgeFlags, motionEntry.metaState,
3399 motionEntry.buttonState, motionEntry.classification,
3400 dispatchEntry.transform, motionEntry.xPrecision,
3401 motionEntry.yPrecision, motionEntry.xCursorPosition,
3402 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3403 motionEntry.downTime, motionEntry.eventTime,
3404 motionEntry.pointerCount, motionEntry.pointerProperties,
3405 usingCoords);
3406}
3407
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003409 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003410 if (ATRACE_ENABLED()) {
3411 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003412 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003413 ATRACE_NAME(message.c_str());
3414 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003415 if (DEBUG_DISPATCH_CYCLE) {
3416 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3417 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003419 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003420 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003422 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003423 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424
3425 // Publish the event.
3426 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003427 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3428 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003429 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003430 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3431 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003432 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3433 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3434 << connection->getInputChannelName();
3435 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003437 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003438 status = connection->inputPublisher
3439 .publishKeyEvent(dispatchEntry->seq,
3440 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3441 keyEntry.source, keyEntry.displayId,
3442 std::move(hmac), dispatchEntry->resolvedAction,
3443 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3444 keyEntry.scanCode, keyEntry.metaState,
3445 keyEntry.repeatCount, keyEntry.downTime,
3446 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003447 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448 }
3449
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003450 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003451 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3452 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3453 << connection->getInputChannelName();
3454 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003455 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003456 break;
3457 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003458
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003459 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003460 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003461 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003462 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003463 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003464 break;
3465 }
3466
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003467 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3468 const TouchModeEntry& touchModeEntry =
3469 static_cast<const TouchModeEntry&>(eventEntry);
3470 status = connection->inputPublisher
3471 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3472 touchModeEntry.inTouchMode);
3473
3474 break;
3475 }
3476
Prabir Pradhan99987712020-11-10 18:43:05 -08003477 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3478 const auto& captureEntry =
3479 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3480 status = connection->inputPublisher
3481 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003482 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003483 break;
3484 }
3485
arthurhungb89ccb02020-12-30 16:19:01 +08003486 case EventEntry::Type::DRAG: {
3487 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3488 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3489 dragEntry.id, dragEntry.x,
3490 dragEntry.y,
3491 dragEntry.isExiting);
3492 break;
3493 }
3494
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003495 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003496 case EventEntry::Type::DEVICE_RESET:
3497 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003498 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003499 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003500 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502 }
3503
3504 // Check the result.
3505 if (status) {
3506 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003507 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003509 "This is unexpected because the wait queue is empty, so the pipe "
3510 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003511 "event to it, status=%s(%d)",
3512 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3513 status);
Harry Cutts33476232023-01-30 19:57:29 +00003514 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003515 } else {
3516 // Pipe is full and we are waiting for the app to finish process some events
3517 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003518 if (DEBUG_DISPATCH_CYCLE) {
3519 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3520 "waiting for the application to catch up",
3521 connection->getInputChannelName().c_str());
3522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523 }
3524 } else {
3525 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003526 "status=%s(%d)",
3527 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3528 status);
Harry Cutts33476232023-01-30 19:57:29 +00003529 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003530 }
3531 return;
3532 }
3533
3534 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003535 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3536 connection->outboundQueue.end(),
3537 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003538 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003539 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003540 if (connection->responsive) {
3541 mAnrTracker.insert(dispatchEntry->timeoutTime,
3542 connection->inputChannel->getConnectionToken());
3543 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003544 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545 }
3546}
3547
chaviw09c8d2d2020-08-24 15:48:26 -07003548std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3549 size_t size;
3550 switch (event.type) {
3551 case VerifiedInputEvent::Type::KEY: {
3552 size = sizeof(VerifiedKeyEvent);
3553 break;
3554 }
3555 case VerifiedInputEvent::Type::MOTION: {
3556 size = sizeof(VerifiedMotionEvent);
3557 break;
3558 }
3559 }
3560 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3561 return mHmacKeyManager.sign(start, size);
3562}
3563
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003564const std::array<uint8_t, 32> InputDispatcher::getSignature(
3565 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003566 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3567 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003568 // Only sign events up and down events as the purely move events
3569 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003570 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003571 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003572
3573 VerifiedMotionEvent verifiedEvent =
3574 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3575 verifiedEvent.actionMasked = actionMasked;
3576 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3577 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003578}
3579
3580const std::array<uint8_t, 32> InputDispatcher::getSignature(
3581 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3582 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3583 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3584 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003585 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003586}
3587
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003589 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003590 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003591 if (DEBUG_DISPATCH_CYCLE) {
3592 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3593 connection->getInputChannelName().c_str(), seq, toString(handled));
3594 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003596 if (connection->status == Connection::Status::BROKEN ||
3597 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598 return;
3599 }
3600
3601 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003602 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3603 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3604 };
3605 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606}
3607
3608void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003609 const sp<Connection>& connection,
3610 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003611 if (DEBUG_DISPATCH_CYCLE) {
3612 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3613 connection->getInputChannelName().c_str(), toString(notify));
3614 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615
3616 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003617 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003618 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003619 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003620 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621
3622 // The connection appears to be unrecoverably broken.
3623 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003624 if (connection->status == Connection::Status::NORMAL) {
3625 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626
3627 if (notify) {
3628 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003629 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3630 connection->getInputChannelName().c_str());
3631
3632 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003633 scoped_unlock unlock(mLock);
3634 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3635 };
3636 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637 }
3638 }
3639}
3640
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003641void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3642 while (!queue.empty()) {
3643 DispatchEntry* dispatchEntry = queue.front();
3644 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003645 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646 }
3647}
3648
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003649void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003650 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003651 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003652 }
3653 delete dispatchEntry;
3654}
3655
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003656int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3657 std::scoped_lock _l(mLock);
3658 sp<Connection> connection = getConnectionLocked(connectionToken);
3659 if (connection == nullptr) {
3660 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3661 connectionToken.get(), events);
3662 return 0; // remove the callback
3663 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003665 bool notify;
3666 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3667 if (!(events & ALOOPER_EVENT_INPUT)) {
3668 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3669 "events=0x%x",
3670 connection->getInputChannelName().c_str(), events);
3671 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003672 }
3673
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003674 nsecs_t currentTime = now();
3675 bool gotOne = false;
3676 status_t status = OK;
3677 for (;;) {
3678 Result<InputPublisher::ConsumerResponse> result =
3679 connection->inputPublisher.receiveConsumerResponse();
3680 if (!result.ok()) {
3681 status = result.error().code();
3682 break;
3683 }
3684
3685 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3686 const InputPublisher::Finished& finish =
3687 std::get<InputPublisher::Finished>(*result);
3688 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3689 finish.consumeTime);
3690 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003691 if (shouldReportMetricsForConnection(*connection)) {
3692 const InputPublisher::Timeline& timeline =
3693 std::get<InputPublisher::Timeline>(*result);
3694 mLatencyTracker
3695 .trackGraphicsLatency(timeline.inputEventId,
3696 connection->inputChannel->getConnectionToken(),
3697 std::move(timeline.graphicsTimeline));
3698 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003699 }
3700 gotOne = true;
3701 }
3702 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003703 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003704 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003705 return 1;
3706 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003707 }
3708
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003709 notify = status != DEAD_OBJECT || !connection->monitor;
3710 if (notify) {
3711 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3712 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3713 status);
3714 }
3715 } else {
3716 // Monitor channels are never explicitly unregistered.
3717 // We do it automatically when the remote endpoint is closed so don't warn about them.
3718 const bool stillHaveWindowHandle =
3719 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3720 notify = !connection->monitor && stillHaveWindowHandle;
3721 if (notify) {
3722 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3723 connection->getInputChannelName().c_str(), events);
3724 }
3725 }
3726
3727 // Remove the channel.
3728 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3729 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730}
3731
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003732void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003734 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003735 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736 }
3737}
3738
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003739void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003740 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003741 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003742 for (const Monitor& monitor : monitors) {
3743 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003744 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003745 }
3746}
3747
Michael Wrightd02c5b62014-02-10 15:10:22 -08003748void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003749 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003750 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003751 if (connection == nullptr) {
3752 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003754
3755 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756}
3757
3758void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3759 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003760 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003761 return;
3762 }
3763
3764 nsecs_t currentTime = now();
3765
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003766 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003767 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003768
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003769 if (cancelationEvents.empty()) {
3770 return;
3771 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003772 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3773 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003774 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003775 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003776 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003777 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003778
Arthur Hungb3307ee2021-10-14 10:57:37 +00003779 std::string reason = std::string("reason=").append(options.reason);
3780 android_log_event_list(LOGTAG_INPUT_CANCEL)
3781 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3782
Svet Ganov5d3bc372020-01-26 23:11:07 -08003783 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003784 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003785 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3786 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003787 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003788 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003789 target.globalScaleFactor = windowInfo->globalScaleFactor;
3790 }
3791 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003792 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003793
hongzuo liu95785e22022-09-06 02:51:35 +00003794 const bool wasEmpty = connection->outboundQueue.empty();
3795
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003796 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003797 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003798 switch (cancelationEventEntry->type) {
3799 case EventEntry::Type::KEY: {
3800 logOutboundKeyDetails("cancel - ",
3801 static_cast<const KeyEntry&>(*cancelationEventEntry));
3802 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003804 case EventEntry::Type::MOTION: {
3805 logOutboundMotionDetails("cancel - ",
3806 static_cast<const MotionEntry&>(*cancelationEventEntry));
3807 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003808 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003809 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003810 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003811 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3812 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003813 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003814 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003815 break;
3816 }
3817 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003818 case EventEntry::Type::DEVICE_RESET:
3819 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003820 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003821 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003822 break;
3823 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824 }
3825
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003826 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003827 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003829
hongzuo liu95785e22022-09-06 02:51:35 +00003830 // If the outbound queue was previously empty, start the dispatch cycle going.
3831 if (wasEmpty && !connection->outboundQueue.empty()) {
3832 startDispatchCycleLocked(currentTime, connection);
3833 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834}
3835
Svet Ganov5d3bc372020-01-26 23:11:07 -08003836void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Arthur Hungc539dbb2022-12-08 07:45:36 +00003837 const nsecs_t downTime, const sp<Connection>& connection,
3838 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003839 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003840 return;
3841 }
3842
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003843 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003844 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003845
3846 if (downEvents.empty()) {
3847 return;
3848 }
3849
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003850 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003851 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3852 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003853 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003854
3855 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003856 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003857 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3858 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003859 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003860 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003861 target.globalScaleFactor = windowInfo->globalScaleFactor;
3862 }
3863 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00003864 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003865
hongzuo liu95785e22022-09-06 02:51:35 +00003866 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003867 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003868 switch (downEventEntry->type) {
3869 case EventEntry::Type::MOTION: {
3870 logOutboundMotionDetails("down - ",
3871 static_cast<const MotionEntry&>(*downEventEntry));
3872 break;
3873 }
3874
3875 case EventEntry::Type::KEY:
3876 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003877 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003878 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003879 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003880 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003881 case EventEntry::Type::SENSOR:
3882 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003883 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003884 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003885 break;
3886 }
3887 }
3888
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003889 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003890 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003891 }
3892
hongzuo liu95785e22022-09-06 02:51:35 +00003893 // If the outbound queue was previously empty, start the dispatch cycle going.
3894 if (wasEmpty && !connection->outboundQueue.empty()) {
3895 startDispatchCycleLocked(downTime, connection);
3896 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003897}
3898
Arthur Hungc539dbb2022-12-08 07:45:36 +00003899void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
3900 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
3901 if (windowHandle != nullptr) {
3902 sp<Connection> wallpaperConnection = getConnectionLocked(windowHandle->getToken());
3903 if (wallpaperConnection != nullptr) {
3904 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
3905 }
3906 }
3907}
3908
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003909std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003910 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
3911 nsecs_t splitDownTime) {
3912 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003913
3914 uint32_t splitPointerIndexMap[MAX_POINTERS];
3915 PointerProperties splitPointerProperties[MAX_POINTERS];
3916 PointerCoords splitPointerCoords[MAX_POINTERS];
3917
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003918 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919 uint32_t splitPointerCount = 0;
3920
3921 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003922 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003924 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003926 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3928 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3929 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003930 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931 splitPointerCount += 1;
3932 }
3933 }
3934
3935 if (splitPointerCount != pointerIds.count()) {
3936 // This is bad. We are missing some of the pointers that we expected to deliver.
3937 // Most likely this indicates that we received an ACTION_MOVE events that has
3938 // different pointer ids than we expected based on the previous ACTION_DOWN
3939 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3940 // in this way.
3941 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003942 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003943 "a broken sequence of pointer ids from the input device: %s",
3944 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07003945 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003946 }
3947
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003948 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003950 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3951 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3953 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003954 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003956 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 if (pointerIds.count() == 1) {
3958 // The first/last pointer went down/up.
3959 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003960 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003961 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3962 ? AMOTION_EVENT_ACTION_CANCEL
3963 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964 } else {
3965 // A secondary pointer went down/up.
3966 uint32_t splitPointerIndex = 0;
3967 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3968 splitPointerIndex += 1;
3969 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003970 action = maskedAction |
3971 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972 }
3973 } else {
3974 // An unrelated pointer changed.
3975 action = AMOTION_EVENT_ACTION_MOVE;
3976 }
3977 }
3978
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003979 if (action == AMOTION_EVENT_ACTION_DOWN) {
3980 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3981 "Split motion event has mismatching downTime and eventTime for "
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08003982 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
3983 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003984 }
3985
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003986 int32_t newId = mIdGenerator.nextId();
3987 if (ATRACE_ENABLED()) {
3988 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3989 ") to MotionEvent(id=0x%" PRIx32 ").",
3990 originalMotionEntry.id, newId);
3991 ATRACE_NAME(message.c_str());
3992 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003993 std::unique_ptr<MotionEntry> splitMotionEntry =
3994 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3995 originalMotionEntry.deviceId, originalMotionEntry.source,
3996 originalMotionEntry.displayId,
3997 originalMotionEntry.policyFlags, action,
3998 originalMotionEntry.actionButton,
3999 originalMotionEntry.flags, originalMotionEntry.metaState,
4000 originalMotionEntry.buttonState,
4001 originalMotionEntry.classification,
4002 originalMotionEntry.edgeFlags,
4003 originalMotionEntry.xPrecision,
4004 originalMotionEntry.yPrecision,
4005 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004006 originalMotionEntry.yCursorPosition, splitDownTime,
4007 splitPointerCount, splitPointerProperties,
4008 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004010 if (originalMotionEntry.injectionState) {
4011 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012 splitMotionEntry->injectionState->refCount += 1;
4013 }
4014
4015 return splitMotionEntry;
4016}
4017
4018void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004019 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004020 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
4021 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004022
Antonio Kantekf16f2832021-09-28 04:39:20 +00004023 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004024 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004025 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004026
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004027 std::unique_ptr<ConfigurationChangedEntry> newEntry =
4028 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
4029 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004030 } // release lock
4031
4032 if (needWake) {
4033 mLooper->wake();
4034 }
4035}
4036
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004037/**
4038 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004039 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4040 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4041 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4042 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4043 * potentially handle the back key presses.
4044 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4045 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004046 */
4047void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004048 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004049 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4050 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004051 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004052 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004053 }
4054 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004055 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004056 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004057 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004058 keyCode = newKeyCode;
4059 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4060 }
4061 } else if (action == AKEY_EVENT_ACTION_UP) {
4062 // In order to maintain a consistent stream of up and down events, check to see if the key
4063 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4064 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004065 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004066 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004067 auto replacementIt = mReplacedKeys.find(replacement);
4068 if (replacementIt != mReplacedKeys.end()) {
4069 keyCode = replacementIt->second;
4070 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004071 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4072 }
4073 }
4074}
4075
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004077 ALOGD_IF(debugInboundEventDetails(),
4078 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4079 ", deviceId=%d, source=%s, displayId=%" PRId32
4080 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4081 "downTime=%" PRId64,
4082 args->id, args->eventTime, args->deviceId,
4083 inputEventSourceToString(args->source).c_str(), args->displayId, args->policyFlags,
4084 KeyEvent::actionToString(args->action), args->flags, KeyEvent::getLabel(args->keyCode),
4085 args->scanCode, args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086 if (!validateKeyEvent(args->action)) {
4087 return;
4088 }
4089
4090 uint32_t policyFlags = args->policyFlags;
4091 int32_t flags = args->flags;
4092 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004093 // InputDispatcher tracks and generates key repeats on behalf of
4094 // whatever notifies it, so repeatCount should always be set to 0
4095 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004096 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4097 policyFlags |= POLICY_FLAG_VIRTUAL;
4098 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4099 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100 if (policyFlags & POLICY_FLAG_FUNCTION) {
4101 metaState |= AMETA_FUNCTION_ON;
4102 }
4103
4104 policyFlags |= POLICY_FLAG_TRUSTED;
4105
Michael Wright78f24442014-08-06 15:55:28 -07004106 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004107 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004108
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004110 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08004111 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
4112 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113
Michael Wright2b3c3302018-03-02 17:19:13 +00004114 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004115 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004116 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4117 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004118 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004119 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120
Antonio Kantekf16f2832021-09-28 04:39:20 +00004121 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122 { // acquire lock
4123 mLock.lock();
4124
4125 if (shouldSendKeyToInputFilterLocked(args)) {
4126 mLock.unlock();
4127
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004128 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4130 return; // event was consumed by the filter
4131 }
4132
4133 mLock.lock();
4134 }
4135
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004136 std::unique_ptr<KeyEntry> newEntry =
4137 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4138 args->displayId, policyFlags, args->action, flags,
4139 keyCode, args->scanCode, metaState, repeatCount,
4140 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004142 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004143 mLock.unlock();
4144 } // release lock
4145
4146 if (needWake) {
4147 mLooper->wake();
4148 }
4149}
4150
4151bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4152 return mInputFilterEnabled;
4153}
4154
4155void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004156 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004157 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004158 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004159 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004160 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4161 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhan96282b02023-02-24 22:36:17 +00004162 args->id, args->eventTime, args->deviceId,
4163 inputEventSourceToString(args->source).c_str(), args->displayId, args->policyFlags,
4164 MotionEvent::actionToString(args->action).c_str(), args->actionButton, args->flags,
4165 args->metaState, args->buttonState, args->edgeFlags, args->xPrecision,
4166 args->yPrecision, args->xCursorPosition, args->yCursorPosition, args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004167 for (uint32_t i = 0; i < args->pointerCount; i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004168 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4169 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
4170 i, args->pointerProperties[i].id,
4171 motionToolTypeToString(args->pointerProperties[i].toolType),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004172 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4173 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4174 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4175 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4176 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4177 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4178 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4179 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4180 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4181 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182 }
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004183
4184 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4185 args->pointerProperties)) {
4186 LOG(ERROR) << "Invalid event: " << args->dump();
4187 return;
4188 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189
4190 uint32_t policyFlags = args->policyFlags;
4191 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004192
4193 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004194 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004195 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4196 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004197 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004198 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199
Antonio Kantekf16f2832021-09-28 04:39:20 +00004200 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201 { // acquire lock
4202 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004203 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4204 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4205 // complete the processing of the current stroke.
4206 const auto touchStateIt = mTouchStatesByDisplay.find(args->displayId);
4207 if (touchStateIt != mTouchStatesByDisplay.end()) {
4208 const TouchState& touchState = touchStateIt->second;
4209 if (touchState.deviceId == args->deviceId && touchState.isDown()) {
4210 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4211 }
4212 }
4213 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214
4215 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004216 ui::Transform displayTransform;
4217 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4218 displayTransform = it->second.transform;
4219 }
4220
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221 mLock.unlock();
4222
4223 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004224 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4225 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004226 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004227 displayTransform, args->xPrecision, args->yPrecision,
4228 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004229 args->downTime, args->eventTime, args->pointerCount,
4230 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231
4232 policyFlags |= POLICY_FLAG_FILTERED;
4233 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4234 return; // event was consumed by the filter
4235 }
4236
4237 mLock.lock();
4238 }
4239
4240 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004241 std::unique_ptr<MotionEntry> newEntry =
4242 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4243 args->source, args->displayId, policyFlags,
4244 args->action, args->actionButton, args->flags,
4245 args->metaState, args->buttonState,
4246 args->classification, args->edgeFlags,
4247 args->xPrecision, args->yPrecision,
4248 args->xCursorPosition, args->yCursorPosition,
4249 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004250 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004252 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4253 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4254 !mInputFilterEnabled) {
4255 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4256 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4257 }
4258
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004259 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 mLock.unlock();
4261 } // release lock
4262
4263 if (needWake) {
4264 mLooper->wake();
4265 }
4266}
4267
Chris Yef59a2f42020-10-16 12:55:26 -07004268void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004269 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004270 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4271 " sensorType=%s",
4272 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004273 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004274 }
Chris Yef59a2f42020-10-16 12:55:26 -07004275
Antonio Kantekf16f2832021-09-28 04:39:20 +00004276 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004277 { // acquire lock
4278 mLock.lock();
4279
4280 // Just enqueue a new sensor event.
4281 std::unique_ptr<SensorEntry> newEntry =
4282 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
Harry Cutts33476232023-01-30 19:57:29 +00004283 args->source, /* policyFlags=*/0, args->hwTimestamp,
Chris Yef59a2f42020-10-16 12:55:26 -07004284 args->sensorType, args->accuracy,
4285 args->accuracyChanged, args->values);
4286
4287 needWake = enqueueInboundEventLocked(std::move(newEntry));
4288 mLock.unlock();
4289 } // release lock
4290
4291 if (needWake) {
4292 mLooper->wake();
4293 }
4294}
4295
Chris Yefb552902021-02-03 17:18:37 -08004296void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004297 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004298 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4299 args->deviceId, args->isOn);
4300 }
Chris Yefb552902021-02-03 17:18:37 -08004301 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4302}
4303
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004305 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306}
4307
4308void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004309 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004310 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4311 "switchMask=0x%08x",
4312 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4313 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314
4315 uint32_t policyFlags = args->policyFlags;
4316 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004317 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318}
4319
4320void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004321 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004322 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4323 args->deviceId);
4324 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325
Antonio Kantekf16f2832021-09-28 04:39:20 +00004326 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004328 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004330 std::unique_ptr<DeviceResetEntry> newEntry =
4331 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4332 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333 } // release lock
4334
4335 if (needWake) {
4336 mLooper->wake();
4337 }
4338}
4339
Prabir Pradhan7e186182020-11-10 13:56:45 -08004340void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004341 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004342 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004343 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004344 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004345
Antonio Kantekf16f2832021-09-28 04:39:20 +00004346 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004347 { // acquire lock
4348 std::scoped_lock _l(mLock);
4349 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004350 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004351 needWake = enqueueInboundEventLocked(std::move(entry));
4352 } // release lock
4353
4354 if (needWake) {
4355 mLooper->wake();
4356 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004357}
4358
Prabir Pradhan5735a322022-04-11 17:23:34 +00004359InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4360 std::optional<int32_t> targetUid,
4361 InputEventInjectionSync syncMode,
4362 std::chrono::milliseconds timeout,
4363 uint32_t policyFlags) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004364 if (debugInboundEventDetails()) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004365 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4366 "policyFlags=0x%08x",
4367 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4368 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004369 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004370 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371
Prabir Pradhan5735a322022-04-11 17:23:34 +00004372 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004374 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004375 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4376 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4377 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4378 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4379 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004380 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004381 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004382 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004383 }
4384
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004385 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004387 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004388 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4389 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004390 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004391 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004394 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004395 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4396 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4397 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004398 int32_t keyCode = incomingKey.getKeyCode();
4399 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004400 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004401 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004402 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004403 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004404 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4405 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4406 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004407
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004408 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4409 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004410 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004411
4412 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4413 android::base::Timer t;
4414 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4415 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4416 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4417 std::to_string(t.duration().count()).c_str());
4418 }
4419 }
4420
4421 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004422 std::unique_ptr<KeyEntry> injectedEntry =
4423 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004424 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004425 incomingKey.getDisplayId(), policyFlags, action,
4426 flags, keyCode, incomingKey.getScanCode(), metaState,
4427 incomingKey.getRepeatCount(),
4428 incomingKey.getDownTime());
4429 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004430 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004431 }
4432
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004433 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004434 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004435 const int32_t action = motionEvent.getAction();
4436 const bool isPointerEvent =
4437 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4438 // If a pointer event has no displayId specified, inject it to the default display.
4439 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4440 ? ADISPLAY_ID_DEFAULT
4441 : event->getDisplayId();
4442 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004443 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004444 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004445 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004446 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004447 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004448 }
4449
4450 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004451 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004452 android::base::Timer t;
4453 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4454 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4455 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4456 std::to_string(t.duration().count()).c_str());
4457 }
4458 }
4459
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004460 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4461 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4462 }
4463
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004464 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004465 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4466 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004467 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004468 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4469 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004470 displayId, policyFlags, action, actionButton,
4471 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004472 motionEvent.getButtonState(),
4473 motionEvent.getClassification(),
4474 motionEvent.getEdgeFlags(),
4475 motionEvent.getXPrecision(),
4476 motionEvent.getYPrecision(),
4477 motionEvent.getRawXCursorPosition(),
4478 motionEvent.getRawYCursorPosition(),
4479 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004480 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004481 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004482 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004483 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004484 sampleEventTimes += 1;
4485 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004486 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004487 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4488 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004489 displayId, policyFlags, action, actionButton,
4490 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004491 motionEvent.getButtonState(),
4492 motionEvent.getClassification(),
4493 motionEvent.getEdgeFlags(),
4494 motionEvent.getXPrecision(),
4495 motionEvent.getYPrecision(),
4496 motionEvent.getRawXCursorPosition(),
4497 motionEvent.getRawYCursorPosition(),
4498 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004499 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004500 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004501 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4502 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004503 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004504 }
4505 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004506 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004507
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004508 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004509 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004510 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004511 }
4512
Prabir Pradhan5735a322022-04-11 17:23:34 +00004513 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004514 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004515 injectionState->injectionIsAsync = true;
4516 }
4517
4518 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004519 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004520
4521 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004522 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004523 if (DEBUG_INJECTION) {
4524 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4525 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004526 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004527 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004528 }
4529
4530 mLock.unlock();
4531
4532 if (needWake) {
4533 mLooper->wake();
4534 }
4535
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004536 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004537 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004538 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004539
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004540 if (syncMode == InputEventInjectionSync::NONE) {
4541 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004542 } else {
4543 for (;;) {
4544 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004545 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546 break;
4547 }
4548
4549 nsecs_t remainingTimeout = endTime - now();
4550 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004551 if (DEBUG_INJECTION) {
4552 ALOGD("injectInputEvent - Timed out waiting for injection result "
4553 "to become available.");
4554 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004555 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004556 break;
4557 }
4558
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004559 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004560 }
4561
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004562 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4563 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004564 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004565 if (DEBUG_INJECTION) {
4566 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4567 injectionState->pendingForegroundDispatches);
4568 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004569 nsecs_t remainingTimeout = endTime - now();
4570 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004571 if (DEBUG_INJECTION) {
4572 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4573 "dispatches to finish.");
4574 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004575 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004576 break;
4577 }
4578
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004579 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004580 }
4581 }
4582 }
4583
4584 injectionState->release();
4585 } // release lock
4586
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004587 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004588 LOG(DEBUG) << "injectInputEvent - Finished with result "
4589 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004591
4592 return injectionResult;
4593}
4594
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004595std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004596 std::array<uint8_t, 32> calculatedHmac;
4597 std::unique_ptr<VerifiedInputEvent> result;
4598 switch (event.getType()) {
4599 case AINPUT_EVENT_TYPE_KEY: {
4600 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4601 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4602 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004603 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004604 break;
4605 }
4606 case AINPUT_EVENT_TYPE_MOTION: {
4607 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4608 VerifiedMotionEvent verifiedMotionEvent =
4609 verifiedMotionEventFromMotionEvent(motionEvent);
4610 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004611 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004612 break;
4613 }
4614 default: {
4615 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4616 return nullptr;
4617 }
4618 }
4619 if (calculatedHmac == INVALID_HMAC) {
4620 return nullptr;
4621 }
4622 if (calculatedHmac != event.getHmac()) {
4623 return nullptr;
4624 }
4625 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004626}
4627
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004628void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004629 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004630 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004631 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004632 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004633 LOG(DEBUG) << "Setting input event injection result to "
4634 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004635 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004636
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004637 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004638 // Log the outcome since the injector did not wait for the injection result.
4639 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004640 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004641 ALOGV("Asynchronous input event injection succeeded.");
4642 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004643 case InputEventInjectionResult::TARGET_MISMATCH:
4644 ALOGV("Asynchronous input event injection target mismatch.");
4645 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004646 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004647 ALOGW("Asynchronous input event injection failed.");
4648 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004649 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004650 ALOGW("Asynchronous input event injection timed out.");
4651 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004652 case InputEventInjectionResult::PENDING:
4653 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4654 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004655 }
4656 }
4657
4658 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004659 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004660 }
4661}
4662
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004663void InputDispatcher::transformMotionEntryForInjectionLocked(
4664 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004665 // Input injection works in the logical display coordinate space, but the input pipeline works
4666 // display space, so we need to transform the injected events accordingly.
4667 const auto it = mDisplayInfos.find(entry.displayId);
4668 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004669 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004670
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004671 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4672 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4673 const vec2 cursor =
4674 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4675 {entry.xCursorPosition, entry.yCursorPosition});
4676 entry.xCursorPosition = cursor.x;
4677 entry.yCursorPosition = cursor.y;
4678 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004679 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004680 entry.pointerCoords[i] =
4681 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4682 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004683 }
4684}
4685
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004686void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4687 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004688 if (injectionState) {
4689 injectionState->pendingForegroundDispatches += 1;
4690 }
4691}
4692
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004693void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4694 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004695 if (injectionState) {
4696 injectionState->pendingForegroundDispatches -= 1;
4697
4698 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004699 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004700 }
4701 }
4702}
4703
chaviw98318de2021-05-19 16:45:23 -05004704const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004705 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004706 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004707 auto it = mWindowHandlesByDisplay.find(displayId);
4708 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004709}
4710
chaviw98318de2021-05-19 16:45:23 -05004711sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004712 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004713 if (windowHandleToken == nullptr) {
4714 return nullptr;
4715 }
4716
Arthur Hungb92218b2018-08-14 12:00:21 +08004717 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004718 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4719 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004720 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004721 return windowHandle;
4722 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723 }
4724 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004725 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726}
4727
chaviw98318de2021-05-19 16:45:23 -05004728sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4729 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004730 if (windowHandleToken == nullptr) {
4731 return nullptr;
4732 }
4733
chaviw98318de2021-05-19 16:45:23 -05004734 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004735 if (windowHandle->getToken() == windowHandleToken) {
4736 return windowHandle;
4737 }
4738 }
4739 return nullptr;
4740}
4741
chaviw98318de2021-05-19 16:45:23 -05004742sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4743 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004744 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004745 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4746 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004747 if (handle->getId() == windowHandle->getId() &&
4748 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004749 if (windowHandle->getInfo()->displayId != it.first) {
4750 ALOGE("Found window %s in display %" PRId32
4751 ", but it should belong to display %" PRId32,
4752 windowHandle->getName().c_str(), it.first,
4753 windowHandle->getInfo()->displayId);
4754 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004755 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004756 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004757 }
4758 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004759 return nullptr;
4760}
4761
chaviw98318de2021-05-19 16:45:23 -05004762sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004763 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4764 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004765}
4766
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004767bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4768 const MotionEntry& motionEntry) const {
4769 const WindowInfo& info = *window->getInfo();
4770
4771 // Skip spy window targets that are not valid for targeted injection.
4772 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004773 return false;
4774 }
4775
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004776 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4777 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4778 return false;
4779 }
4780
4781 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4782 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4783 window->getName().c_str());
4784 return false;
4785 }
4786
4787 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004788 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004789 ALOGW("Not sending touch to %s because there's no corresponding connection",
4790 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004791 return false;
4792 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004793
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004794 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004795 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004796 return false;
4797 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004798
4799 // Drop events that can't be trusted due to occlusion
4800 const auto [x, y] = resolveTouchedPosition(motionEntry);
4801 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4802 if (!isTouchTrustedLocked(occlusionInfo)) {
4803 if (DEBUG_TOUCH_OCCLUSION) {
4804 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4805 for (const auto& log : occlusionInfo.debugInfo) {
4806 ALOGD("%s", log.c_str());
4807 }
4808 }
4809 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4810 occlusionInfo.obscuringUid);
4811 return false;
4812 }
4813
4814 // Drop touch events if requested by input feature
4815 if (shouldDropInput(motionEntry, window)) {
4816 return false;
4817 }
4818
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004819 return true;
4820}
4821
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004822std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4823 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004824 auto connectionIt = mConnectionsByToken.find(token);
4825 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004826 return nullptr;
4827 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004828 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004829}
4830
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004831void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004832 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4833 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004834 // Remove all handles on a display if there are no windows left.
4835 mWindowHandlesByDisplay.erase(displayId);
4836 return;
4837 }
4838
4839 // Since we compare the pointer of input window handles across window updates, we need
4840 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004841 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4842 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4843 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004844 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004845 }
4846
chaviw98318de2021-05-19 16:45:23 -05004847 std::vector<sp<WindowInfoHandle>> newHandles;
4848 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004849 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004850 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004851 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004852 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004853 const bool canReceiveInput =
4854 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4855 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004856 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004857 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004858 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004859 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004860 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004861 }
4862
4863 if (info->displayId != displayId) {
4864 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4865 handle->getName().c_str(), displayId, info->displayId);
4866 continue;
4867 }
4868
Robert Carredd13602020-04-13 17:24:34 -07004869 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4870 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004871 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004872 oldHandle->updateFrom(handle);
4873 newHandles.push_back(oldHandle);
4874 } else {
4875 newHandles.push_back(handle);
4876 }
4877 }
4878
4879 // Insert or replace
4880 mWindowHandlesByDisplay[displayId] = newHandles;
4881}
4882
Arthur Hung72d8dc32020-03-28 00:48:39 +00004883void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004884 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004885 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004886 { // acquire lock
4887 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004888 for (const auto& [displayId, handles] : handlesPerDisplay) {
4889 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004890 }
4891 }
4892 // Wake up poll loop since it may need to make new input dispatching choices.
4893 mLooper->wake();
4894}
4895
Arthur Hungb92218b2018-08-14 12:00:21 +08004896/**
4897 * Called from InputManagerService, update window handle list by displayId that can receive input.
4898 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4899 * If set an empty list, remove all handles from the specific display.
4900 * For focused handle, check if need to change and send a cancel event to previous one.
4901 * For removed handle, check if need to send a cancel event if already in touch.
4902 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004903void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004904 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004905 if (DEBUG_FOCUS) {
4906 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004907 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004908 windowList += iwh->getName() + " ";
4909 }
4910 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4911 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912
Prabir Pradhand65552b2021-10-07 11:23:50 -07004913 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004914 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004915 const WindowInfo& info = *window->getInfo();
4916
4917 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004918 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004919 if (noInputWindow && window->getToken() != nullptr) {
4920 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4921 window->getName().c_str());
4922 window->releaseChannel();
4923 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004924
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004925 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004926 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4927 !info.inputConfig.test(
4928 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004929 "%s has feature SPY, but is not a trusted overlay.",
4930 window->getName().c_str());
4931
Prabir Pradhand65552b2021-10-07 11:23:50 -07004932 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004933 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4934 !info.inputConfig.test(
4935 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004936 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4937 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004938 }
4939
Arthur Hung72d8dc32020-03-28 00:48:39 +00004940 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004941 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004942
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004943 // Save the old windows' orientation by ID before it gets updated.
4944 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004945 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004946 oldWindowOrientations.emplace(handle->getId(),
4947 handle->getInfo()->transform.getOrientation());
4948 }
4949
chaviw98318de2021-05-19 16:45:23 -05004950 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004951
chaviw98318de2021-05-19 16:45:23 -05004952 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004953
Vishnu Nairc519ff72021-01-21 08:23:08 -08004954 std::optional<FocusResolver::FocusChanges> changes =
4955 mFocusResolver.setInputWindows(displayId, windowHandles);
4956 if (changes) {
4957 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004958 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004960 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4961 mTouchStatesByDisplay.find(displayId);
4962 if (stateIt != mTouchStatesByDisplay.end()) {
4963 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004964 for (size_t i = 0; i < state.windows.size();) {
4965 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004966 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004967 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004968 ALOGD("Touched window was removed: %s in display %" PRId32,
4969 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004970 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004971 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004972 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4973 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004974 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00004975 "touched window was removed");
4976 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004977 // Since we are about to drop the touch, cancel the events for the wallpaper as
4978 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004979 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004980 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4981 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004982 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004983 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004984 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004985 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004986 state.windows.erase(state.windows.begin() + i);
4987 } else {
4988 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004989 }
4990 }
arthurhungb89ccb02020-12-30 16:19:01 +08004991
arthurhung6d4bed92021-03-17 11:59:33 +08004992 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004993 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004994 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004995 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004996 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004997 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4998 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004999 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005000 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005001 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005002
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005003 // Determine if the orientation of any of the input windows have changed, and cancel all
5004 // pointer events if necessary.
5005 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
5006 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
5007 if (newWindowHandle != nullptr &&
5008 newWindowHandle->getInfo()->transform.getOrientation() !=
5009 oldWindowOrientations[oldWindowHandle->getId()]) {
5010 std::shared_ptr<InputChannel> inputChannel =
5011 getInputChannelLocked(newWindowHandle->getToken());
5012 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005013 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005014 "touched window's orientation changed");
5015 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005016 }
5017 }
5018 }
5019
Arthur Hung72d8dc32020-03-28 00:48:39 +00005020 // Release information for windows that are no longer present.
5021 // This ensures that unused input channels are released promptly.
5022 // Otherwise, they might stick around until the window handle is destroyed
5023 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005024 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005025 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005026 if (DEBUG_FOCUS) {
5027 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005028 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005029 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005030 }
chaviw291d88a2019-02-14 10:33:58 -08005031 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005032}
5033
5034void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005035 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005036 if (DEBUG_FOCUS) {
5037 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5038 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5039 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005040 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005041 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005042 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005043 } // release lock
5044
5045 // Wake up poll loop since it may need to make new input dispatching choices.
5046 mLooper->wake();
5047}
5048
Vishnu Nair599f1412021-06-21 10:39:58 -07005049void InputDispatcher::setFocusedApplicationLocked(
5050 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5051 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5052 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5053
5054 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5055 return; // This application is already focused. No need to wake up or change anything.
5056 }
5057
5058 // Set the new application handle.
5059 if (inputApplicationHandle != nullptr) {
5060 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5061 } else {
5062 mFocusedApplicationHandlesByDisplay.erase(displayId);
5063 }
5064
5065 // No matter what the old focused application was, stop waiting on it because it is
5066 // no longer focused.
5067 resetNoFocusedWindowTimeoutLocked();
5068}
5069
Tiger Huang721e26f2018-07-24 22:26:19 +08005070/**
5071 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5072 * the display not specified.
5073 *
5074 * We track any unreleased events for each window. If a window loses the ability to receive the
5075 * released event, we will send a cancel event to it. So when the focused display is changed, we
5076 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5077 * display. The display-specified events won't be affected.
5078 */
5079void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005080 if (DEBUG_FOCUS) {
5081 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5082 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005083 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005084 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005085
5086 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005087 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005088 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005089 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005090 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005091 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005092 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005093 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005094 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005095 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005096 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005097 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5098 }
5099 }
5100 mFocusedDisplayId = displayId;
5101
Chris Ye3c2d6f52020-08-09 10:39:48 -07005102 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005103 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005104 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005105
Vishnu Nairad321cd2020-08-20 16:40:21 -07005106 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005107 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005108 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005109 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005110 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005111 }
5112 }
5113 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005114 } // release lock
5115
5116 // Wake up poll loop since it may need to make new input dispatching choices.
5117 mLooper->wake();
5118}
5119
Michael Wrightd02c5b62014-02-10 15:10:22 -08005120void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005121 if (DEBUG_FOCUS) {
5122 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5123 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124
5125 bool changed;
5126 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005127 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005128
5129 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5130 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005131 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005132 }
5133
5134 if (mDispatchEnabled && !enabled) {
5135 resetAndDropEverythingLocked("dispatcher is being disabled");
5136 }
5137
5138 mDispatchEnabled = enabled;
5139 mDispatchFrozen = frozen;
5140 changed = true;
5141 } else {
5142 changed = false;
5143 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005144 } // release lock
5145
5146 if (changed) {
5147 // Wake up poll loop since it may need to make new input dispatching choices.
5148 mLooper->wake();
5149 }
5150}
5151
5152void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005153 if (DEBUG_FOCUS) {
5154 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5155 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005156
5157 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005158 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159
5160 if (mInputFilterEnabled == enabled) {
5161 return;
5162 }
5163
5164 mInputFilterEnabled = enabled;
5165 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5166 } // release lock
5167
5168 // Wake up poll loop since there might be work to do to drop everything.
5169 mLooper->wake();
5170}
5171
Antonio Kanteka042c022022-07-06 16:51:07 -07005172bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5173 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005174 bool needWake = false;
5175 {
5176 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005177 ALOGD_IF(DEBUG_TOUCH_MODE,
5178 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5179 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5180 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5181 mTouchModePerDisplay.count(displayId) == 0
5182 ? "not set"
5183 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5184
Antonio Kantek15beb512022-06-13 22:35:41 +00005185 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5186 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005187 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005188 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005189 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005190 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5191 !recentWindowsAreOwnedByLocked(pid, uid)) {
5192 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5193 "window nor none of the previously interacted window",
5194 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005195 return false;
5196 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005197 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005198 mTouchModePerDisplay[displayId] = inTouchMode;
5199 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5200 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005201 needWake = enqueueInboundEventLocked(std::move(entry));
5202 } // release lock
5203
5204 if (needWake) {
5205 mLooper->wake();
5206 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005207 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005208}
5209
Antonio Kantek48710e42022-03-24 14:19:30 -07005210bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5211 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5212 if (focusedToken == nullptr) {
5213 return false;
5214 }
5215 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5216 return isWindowOwnedBy(windowHandle, pid, uid);
5217}
5218
5219bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5220 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5221 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5222 const sp<WindowInfoHandle> windowHandle =
5223 getWindowHandleLocked(connectionToken);
5224 return isWindowOwnedBy(windowHandle, pid, uid);
5225 }) != mInteractionConnectionTokens.end();
5226}
5227
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005228void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5229 if (opacity < 0 || opacity > 1) {
5230 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5231 return;
5232 }
5233
5234 std::scoped_lock lock(mLock);
5235 mMaximumObscuringOpacityForTouch = opacity;
5236}
5237
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005238std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5239InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005240 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5241 for (TouchedWindow& w : state.windows) {
5242 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005243 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005244 }
5245 }
5246 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005247 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005248}
5249
arthurhungb89ccb02020-12-30 16:19:01 +08005250bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5251 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005252 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005253 if (DEBUG_FOCUS) {
5254 ALOGD("Trivial transfer to same window.");
5255 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005256 return true;
5257 }
5258
Michael Wrightd02c5b62014-02-10 15:10:22 -08005259 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005260 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005261
Arthur Hungabbb9d82021-09-01 14:52:30 +00005262 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005263 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005264 if (state == nullptr || touchedWindow == nullptr) {
5265 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266 return false;
5267 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005268
Arthur Hungabbb9d82021-09-01 14:52:30 +00005269 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5270 if (toWindowHandle == nullptr) {
5271 ALOGW("Cannot transfer focus because to window not found.");
5272 return false;
5273 }
5274
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005275 if (DEBUG_FOCUS) {
5276 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005277 touchedWindow->windowHandle->getName().c_str(),
5278 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005279 }
5280
Arthur Hungabbb9d82021-09-01 14:52:30 +00005281 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005282 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005283 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005284 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005285 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005286
Arthur Hungabbb9d82021-09-01 14:52:30 +00005287 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005288 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005289 ftl::Flags<InputTarget::Flags> newTargetFlags =
5290 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005291 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005292 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005293 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005294 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005295
Arthur Hungabbb9d82021-09-01 14:52:30 +00005296 // Store the dragging window.
5297 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005298 if (pointerIds.count() != 1) {
5299 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5300 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005301 return false;
5302 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005303 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005304 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005305 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005306 }
5307
Arthur Hungabbb9d82021-09-01 14:52:30 +00005308 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005309 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5310 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005311 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005312 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005313 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005314 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005315 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005316 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005317 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5318 newTargetFlags);
5319
5320 // Check if the wallpaper window should deliver the corresponding event.
5321 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5322 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005324 } // release lock
5325
5326 // Wake up poll loop since it may need to make new input dispatching choices.
5327 mLooper->wake();
5328 return true;
5329}
5330
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005331/**
5332 * Get the touched foreground window on the given display.
5333 * Return null if there are no windows touched on that display, or if more than one foreground
5334 * window is being touched.
5335 */
5336sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5337 auto stateIt = mTouchStatesByDisplay.find(displayId);
5338 if (stateIt == mTouchStatesByDisplay.end()) {
5339 ALOGI("No touch state on display %" PRId32, displayId);
5340 return nullptr;
5341 }
5342
5343 const TouchState& state = stateIt->second;
5344 sp<WindowInfoHandle> touchedForegroundWindow;
5345 // If multiple foreground windows are touched, return nullptr
5346 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005347 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005348 if (touchedForegroundWindow != nullptr) {
5349 ALOGI("Two or more foreground windows: %s and %s",
5350 touchedForegroundWindow->getName().c_str(),
5351 window.windowHandle->getName().c_str());
5352 return nullptr;
5353 }
5354 touchedForegroundWindow = window.windowHandle;
5355 }
5356 }
5357 return touchedForegroundWindow;
5358}
5359
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005360// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005361bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005362 sp<IBinder> fromToken;
5363 { // acquire lock
5364 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005365 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005366 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005367 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5368 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005369 return false;
5370 }
5371
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005372 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5373 if (from == nullptr) {
5374 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5375 return false;
5376 }
5377
5378 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005379 } // release lock
5380
5381 return transferTouchFocus(fromToken, destChannelToken);
5382}
5383
Michael Wrightd02c5b62014-02-10 15:10:22 -08005384void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005385 if (DEBUG_FOCUS) {
5386 ALOGD("Resetting and dropping all events (%s).", reason);
5387 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005388
Michael Wrightfb04fd52022-11-24 22:31:11 +00005389 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005390 synthesizeCancelationEventsForAllConnectionsLocked(options);
5391
5392 resetKeyRepeatLocked();
5393 releasePendingEventLocked();
5394 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005395 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005396
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005397 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005398 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005399 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005400}
5401
5402void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005403 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005404 dumpDispatchStateLocked(dump);
5405
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005406 std::istringstream stream(dump);
5407 std::string line;
5408
5409 while (std::getline(stream, line, '\n')) {
5410 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005411 }
5412}
5413
Prabir Pradhan99987712020-11-10 18:43:05 -08005414std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5415 std::string dump;
5416
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005417 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5418 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005419
5420 std::string windowName = "None";
5421 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005422 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005423 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5424 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5425 : "token has capture without window";
5426 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005427 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005428
5429 return dump;
5430}
5431
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005432void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005433 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5434 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5435 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005436 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005437
Tiger Huang721e26f2018-07-24 22:26:19 +08005438 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5439 dump += StringPrintf(INDENT "FocusedApplications:\n");
5440 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5441 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005442 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005443 const std::chrono::duration timeout =
5444 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005445 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005446 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005447 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005448 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005449 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005450 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005451 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005452
Vishnu Nairc519ff72021-01-21 08:23:08 -08005453 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005454 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005455
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005456 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005457 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005458 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005459 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5460 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005461 }
5462 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005463 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005464 }
5465
arthurhung6d4bed92021-03-17 11:59:33 +08005466 if (mDragState) {
5467 dump += StringPrintf(INDENT "DragState:\n");
5468 mDragState->dump(dump, INDENT2);
5469 }
5470
Arthur Hungb92218b2018-08-14 12:00:21 +08005471 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005472 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5473 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5474 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5475 const auto& displayInfo = it->second;
5476 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5477 displayInfo.logicalHeight);
5478 displayInfo.transform.dump(dump, "transform", INDENT4);
5479 } else {
5480 dump += INDENT2 "No DisplayInfo found!\n";
5481 }
5482
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005483 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005484 dump += INDENT2 "Windows:\n";
5485 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005486 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5487 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005489 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005490 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005491 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005492 "applicationInfo.name=%s, "
5493 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005494 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005495 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005496 windowInfo->displayId,
5497 windowInfo->inputConfig.string().c_str(),
5498 windowInfo->alpha, windowInfo->frameLeft,
5499 windowInfo->frameTop, windowInfo->frameRight,
5500 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005501 windowInfo->applicationInfo.name.c_str(),
5502 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005503 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005504 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005505 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005506 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005507 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005508 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005509 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005510 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005511 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005512 }
5513 } else {
5514 dump += INDENT2 "Windows: <none>\n";
5515 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005516 }
5517 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005518 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005519 }
5520
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005521 if (!mGlobalMonitorsByDisplay.empty()) {
5522 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5523 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005524 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005525 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005526 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005527 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005528 }
5529
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005530 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005531
5532 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005533 if (!mRecentQueue.empty()) {
5534 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005535 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005536 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005537 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005538 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005539 }
5540 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005541 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005542 }
5543
5544 // Dump event currently being dispatched.
5545 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005546 dump += INDENT "PendingEvent:\n";
5547 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005548 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005549 dump += StringPrintf(", age=%" PRId64 "ms\n",
5550 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005551 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005552 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005553 }
5554
5555 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005556 if (!mInboundQueue.empty()) {
5557 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005558 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005559 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005560 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005561 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562 }
5563 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005564 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005565 }
5566
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005567 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005568 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005569 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005570 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005571 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005572 }
5573 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005574 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005575 }
5576
Prabir Pradhancef936d2021-07-21 16:17:52 +00005577 if (!mCommandQueue.empty()) {
5578 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5579 } else {
5580 dump += INDENT "CommandQueue: <empty>\n";
5581 }
5582
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005583 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005584 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005585 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005586 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005587 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005588 connection->inputChannel->getFd().get(),
5589 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005590 connection->getWindowName().c_str(),
5591 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005592 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005593
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005594 if (!connection->outboundQueue.empty()) {
5595 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5596 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005597 dump += dumpQueue(connection->outboundQueue, currentTime);
5598
Michael Wrightd02c5b62014-02-10 15:10:22 -08005599 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005600 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005601 }
5602
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005603 if (!connection->waitQueue.empty()) {
5604 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5605 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005606 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005608 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005609 }
5610 }
5611 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005612 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005613 }
5614
5615 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005616 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5617 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005618 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005619 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005620 }
5621
Antonio Kantek15beb512022-06-13 22:35:41 +00005622 if (!mTouchModePerDisplay.empty()) {
5623 dump += INDENT "TouchModePerDisplay:\n";
5624 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5625 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5626 std::to_string(touchMode).c_str());
5627 }
5628 } else {
5629 dump += INDENT "TouchModePerDisplay: <none>\n";
5630 }
5631
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005632 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005633 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5634 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5635 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005636 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005637 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005638}
5639
Michael Wright3dd60e22019-03-27 22:06:44 +00005640void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5641 const size_t numMonitors = monitors.size();
5642 for (size_t i = 0; i < numMonitors; i++) {
5643 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005644 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005645 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5646 dump += "\n";
5647 }
5648}
5649
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005650class LooperEventCallback : public LooperCallback {
5651public:
5652 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5653 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5654
5655private:
5656 std::function<int(int events)> mCallback;
5657};
5658
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005659Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005660 if (DEBUG_CHANNEL_CREATION) {
5661 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5662 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005663
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005664 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005665 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005666 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005667
5668 if (result) {
5669 return base::Error(result) << "Failed to open input channel pair with name " << name;
5670 }
5671
Michael Wrightd02c5b62014-02-10 15:10:22 -08005672 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005673 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005674 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005675 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005676 sp<Connection> connection =
Harry Cutts33476232023-01-30 19:57:29 +00005677 sp<Connection>::make(std::move(serverChannel), /*monitor=*/false, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005678
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005679 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5680 ALOGE("Created a new connection, but the token %p is already known", token.get());
5681 }
5682 mConnectionsByToken.emplace(token, connection);
5683
5684 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5685 this, std::placeholders::_1, token);
5686
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005687 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5688 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005689 } // release lock
5690
5691 // Wake the looper because some connections have changed.
5692 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005693 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005694}
5695
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005696Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005697 const std::string& name,
5698 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005699 std::shared_ptr<InputChannel> serverChannel;
5700 std::unique_ptr<InputChannel> clientChannel;
5701 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5702 if (result) {
5703 return base::Error(result) << "Failed to open input channel pair with name " << name;
5704 }
5705
Michael Wright3dd60e22019-03-27 22:06:44 +00005706 { // acquire lock
5707 std::scoped_lock _l(mLock);
5708
5709 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005710 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5711 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005712 }
5713
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005714 sp<Connection> connection =
Harry Cutts33476232023-01-30 19:57:29 +00005715 sp<Connection>::make(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005716 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005717 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005718
5719 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5720 ALOGE("Created a new connection, but the token %p is already known", token.get());
5721 }
5722 mConnectionsByToken.emplace(token, connection);
5723 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5724 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005725
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005726 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005727
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005728 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5729 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005730 }
Garfield Tan15601662020-09-22 15:32:38 -07005731
Michael Wright3dd60e22019-03-27 22:06:44 +00005732 // Wake the looper because some connections have changed.
5733 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005734 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005735}
5736
Garfield Tan15601662020-09-22 15:32:38 -07005737status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005738 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005739 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005740
Harry Cutts33476232023-01-30 19:57:29 +00005741 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005742 if (status) {
5743 return status;
5744 }
5745 } // release lock
5746
5747 // Wake the poll loop because removing the connection may have changed the current
5748 // synchronization state.
5749 mLooper->wake();
5750 return OK;
5751}
5752
Garfield Tan15601662020-09-22 15:32:38 -07005753status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5754 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005755 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005756 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005757 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005758 return BAD_VALUE;
5759 }
5760
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005761 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005762
Michael Wrightd02c5b62014-02-10 15:10:22 -08005763 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005764 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005765 }
5766
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005767 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005768
5769 nsecs_t currentTime = now();
5770 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5771
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005772 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005773 return OK;
5774}
5775
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005776void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005777 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5778 auto& [displayId, monitors] = *it;
5779 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5780 return monitor.inputChannel->getConnectionToken() == connectionToken;
5781 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005782
Michael Wright3dd60e22019-03-27 22:06:44 +00005783 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005784 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005785 } else {
5786 ++it;
5787 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005788 }
5789}
5790
Michael Wright3dd60e22019-03-27 22:06:44 +00005791status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005792 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005793 return pilferPointersLocked(token);
5794}
Michael Wright3dd60e22019-03-27 22:06:44 +00005795
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005796status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005797 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5798 if (!requestingChannel) {
5799 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5800 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005801 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005802
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005803 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005804 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.none()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005805 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5806 " Ignoring.");
5807 return BAD_VALUE;
5808 }
5809
5810 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005811 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005812 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005813 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005814 "input channel stole pointer stream");
5815 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005816 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005817 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005818 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005819 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005820 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005821 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005822 if (channel != nullptr && channel->getConnectionToken() != token) {
5823 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5824 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5825 canceledWindows += channel->getName();
5826 }
5827 }
5828 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5829 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5830 canceledWindows.c_str());
5831
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005832 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005833 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005834 window.pilferedPointerIds |= window.pointerIds;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005835
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005836 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005837 return OK;
5838}
5839
Prabir Pradhan99987712020-11-10 18:43:05 -08005840void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5841 { // acquire lock
5842 std::scoped_lock _l(mLock);
5843 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005844 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005845 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5846 windowHandle != nullptr ? windowHandle->getName().c_str()
5847 : "token without window");
5848 }
5849
Vishnu Nairc519ff72021-01-21 08:23:08 -08005850 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005851 if (focusedToken != windowToken) {
5852 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5853 enabled ? "enable" : "disable");
5854 return;
5855 }
5856
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005857 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005858 ALOGW("Ignoring request to %s Pointer Capture: "
5859 "window has %s requested pointer capture.",
5860 enabled ? "enable" : "disable", enabled ? "already" : "not");
5861 return;
5862 }
5863
Christine Franksb768bb42021-11-29 12:11:31 -08005864 if (enabled) {
5865 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5866 mIneligibleDisplaysForPointerCapture.end(),
5867 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5868 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5869 return;
5870 }
5871 }
5872
Prabir Pradhan99987712020-11-10 18:43:05 -08005873 setPointerCaptureLocked(enabled);
5874 } // release lock
5875
5876 // Wake the thread to process command entries.
5877 mLooper->wake();
5878}
5879
Christine Franksb768bb42021-11-29 12:11:31 -08005880void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5881 { // acquire lock
5882 std::scoped_lock _l(mLock);
5883 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5884 if (!isEligible) {
5885 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5886 }
5887 } // release lock
5888}
5889
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005890std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5891 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005892 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005893 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005894 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005895 }
5896 }
5897 }
5898 return std::nullopt;
5899}
5900
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005901sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005902 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005903 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005904 }
5905
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005906 for (const auto& [token, connection] : mConnectionsByToken) {
5907 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005908 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005909 }
5910 }
Robert Carr4e670e52018-08-15 13:26:12 -07005911
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005912 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005913}
5914
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005915std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5916 sp<Connection> connection = getConnectionLocked(connectionToken);
5917 if (connection == nullptr) {
5918 return "<nullptr>";
5919 }
5920 return connection->getInputChannelName();
5921}
5922
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005923void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005924 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005925 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005926}
5927
Prabir Pradhancef936d2021-07-21 16:17:52 +00005928void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5929 const sp<Connection>& connection, uint32_t seq,
5930 bool handled, nsecs_t consumeTime) {
5931 // Handle post-event policy actions.
5932 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5933 if (dispatchEntryIt == connection->waitQueue.end()) {
5934 return;
5935 }
5936 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5937 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5938 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5939 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5940 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5941 }
5942 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5943 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5944 connection->inputChannel->getConnectionToken(),
5945 dispatchEntry->deliveryTime, consumeTime, finishTime);
5946 }
5947
5948 bool restartEvent;
5949 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5950 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5951 restartEvent =
5952 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5953 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5954 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5955 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5956 handled);
5957 } else {
5958 restartEvent = false;
5959 }
5960
5961 // Dequeue the event and start the next cycle.
5962 // Because the lock might have been released, it is possible that the
5963 // contents of the wait queue to have been drained, so we need to double-check
5964 // a few things.
5965 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5966 if (dispatchEntryIt != connection->waitQueue.end()) {
5967 dispatchEntry = *dispatchEntryIt;
5968 connection->waitQueue.erase(dispatchEntryIt);
5969 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5970 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5971 if (!connection->responsive) {
5972 connection->responsive = isConnectionResponsive(*connection);
5973 if (connection->responsive) {
5974 // The connection was unresponsive, and now it's responsive.
5975 processConnectionResponsiveLocked(*connection);
5976 }
5977 }
5978 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005979 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005980 connection->outboundQueue.push_front(dispatchEntry);
5981 traceOutboundQueueLength(*connection);
5982 } else {
5983 releaseDispatchEntry(dispatchEntry);
5984 }
5985 }
5986
5987 // Start the next dispatch cycle for this connection.
5988 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005989}
5990
Prabir Pradhancef936d2021-07-21 16:17:52 +00005991void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5992 const sp<IBinder>& newToken) {
5993 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5994 scoped_unlock unlock(mLock);
5995 mPolicy->notifyFocusChanged(oldToken, newToken);
5996 };
5997 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005998}
5999
Prabir Pradhancef936d2021-07-21 16:17:52 +00006000void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6001 auto command = [this, token, x, y]() REQUIRES(mLock) {
6002 scoped_unlock unlock(mLock);
6003 mPolicy->notifyDropWindow(token, x, y);
6004 };
6005 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006006}
6007
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006008void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
6009 if (connection == nullptr) {
6010 LOG_ALWAYS_FATAL("Caller must check for nullness");
6011 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006012 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6013 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006014 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006015 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006016 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006017 return;
6018 }
6019 /**
6020 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6021 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6022 * has changed. This could cause newer entries to time out before the already dispatched
6023 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6024 * processes the events linearly. So providing information about the oldest entry seems to be
6025 * most useful.
6026 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006027 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006028 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6029 std::string reason =
6030 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006031 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006032 ns2ms(currentWait),
6033 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006034 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006035 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006036
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006037 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6038
6039 // Stop waking up for events on this connection, it is already unresponsive
6040 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006041}
6042
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006043void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6044 std::string reason =
6045 StringPrintf("%s does not have a focused window", application->getName().c_str());
6046 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006047
Prabir Pradhancef936d2021-07-21 16:17:52 +00006048 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
6049 scoped_unlock unlock(mLock);
6050 mPolicy->notifyNoFocusedWindowAnr(application);
6051 };
6052 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006053}
6054
chaviw98318de2021-05-19 16:45:23 -05006055void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006056 const std::string& reason) {
6057 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6058 updateLastAnrStateLocked(windowLabel, reason);
6059}
6060
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006061void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6062 const std::string& reason) {
6063 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006064 updateLastAnrStateLocked(windowLabel, reason);
6065}
6066
6067void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6068 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006069 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006070 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006071 struct tm tm;
6072 localtime_r(&t, &tm);
6073 char timestr[64];
6074 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006075 mLastAnrState.clear();
6076 mLastAnrState += INDENT "ANR:\n";
6077 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006078 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6079 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006080 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006081}
6082
Prabir Pradhancef936d2021-07-21 16:17:52 +00006083void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6084 KeyEntry& entry) {
6085 const KeyEvent event = createKeyEvent(entry);
6086 nsecs_t delay = 0;
6087 { // release lock
6088 scoped_unlock unlock(mLock);
6089 android::base::Timer t;
6090 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
6091 entry.policyFlags);
6092 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6093 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6094 std::to_string(t.duration().count()).c_str());
6095 }
6096 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006097
6098 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006099 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006100 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006101 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006102 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006103 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006104 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006105 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006106}
6107
Prabir Pradhancef936d2021-07-21 16:17:52 +00006108void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006109 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006110 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006111 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006112 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006113 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006114 };
6115 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006116}
6117
Prabir Pradhanedd96402022-02-15 01:46:16 -08006118void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6119 std::optional<int32_t> pid) {
6120 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006121 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006122 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006123 };
6124 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006125}
6126
6127/**
6128 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6129 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6130 * command entry to the command queue.
6131 */
6132void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6133 std::string reason) {
6134 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006135 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006136 if (connection.monitor) {
6137 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6138 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006139 pid = findMonitorPidByTokenLocked(connectionToken);
6140 } else {
6141 // The connection is a window
6142 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6143 reason.c_str());
6144 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6145 if (handle != nullptr) {
6146 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006147 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006148 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006149 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006150}
6151
6152/**
6153 * Tell the policy that a connection has become responsive so that it can stop ANR.
6154 */
6155void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6156 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006157 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006158 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006159 pid = findMonitorPidByTokenLocked(connectionToken);
6160 } else {
6161 // The connection is a window
6162 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6163 if (handle != nullptr) {
6164 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006165 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006166 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006167 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006168}
6169
Prabir Pradhancef936d2021-07-21 16:17:52 +00006170bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006171 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006172 KeyEntry& keyEntry, bool handled) {
6173 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006174 if (!handled) {
6175 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006176 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006177 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006178 return false;
6179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006180
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006181 // Get the fallback key state.
6182 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006183 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006184 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006185 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006186 connection->inputState.removeFallbackKey(originalKeyCode);
6187 }
6188
6189 if (handled || !dispatchEntry->hasForegroundTarget()) {
6190 // If the application handles the original key for which we previously
6191 // generated a fallback or if the window is not a foreground window,
6192 // then cancel the associated fallback key, if any.
6193 if (fallbackKeyCode != -1) {
6194 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006195 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6196 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6197 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6198 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6199 keyEntry.policyFlags);
6200 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006201 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006202 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006203
6204 mLock.unlock();
6205
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006206 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006207 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006208
6209 mLock.lock();
6210
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006211 // Cancel the fallback key.
6212 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006213 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006214 "application handled the original non-fallback key "
6215 "or is no longer a foreground target, "
6216 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006217 options.keyCode = fallbackKeyCode;
6218 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006219 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006220 connection->inputState.removeFallbackKey(originalKeyCode);
6221 }
6222 } else {
6223 // If the application did not handle a non-fallback key, first check
6224 // that we are in a good state to perform unhandled key event processing
6225 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006226 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006227 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006228 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6229 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6230 "since this is not an initial down. "
6231 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6232 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6233 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006234 return false;
6235 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006236
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006237 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006238 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6239 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6240 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6241 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6242 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006243 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006244
6245 mLock.unlock();
6246
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006247 bool fallback =
6248 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006249 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006250
6251 mLock.lock();
6252
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006253 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006254 connection->inputState.removeFallbackKey(originalKeyCode);
6255 return false;
6256 }
6257
6258 // Latch the fallback keycode for this key on an initial down.
6259 // The fallback keycode cannot change at any other point in the lifecycle.
6260 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006261 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006262 fallbackKeyCode = event.getKeyCode();
6263 } else {
6264 fallbackKeyCode = AKEYCODE_UNKNOWN;
6265 }
6266 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6267 }
6268
6269 ALOG_ASSERT(fallbackKeyCode != -1);
6270
6271 // Cancel the fallback key if the policy decides not to send it anymore.
6272 // We will continue to dispatch the key to the policy but we will no
6273 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006274 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6275 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006276 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6277 if (fallback) {
6278 ALOGD("Unhandled key event: Policy requested to send key %d"
6279 "as a fallback for %d, but on the DOWN it had requested "
6280 "to send %d instead. Fallback canceled.",
6281 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6282 } else {
6283 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6284 "but on the DOWN it had requested to send %d. "
6285 "Fallback canceled.",
6286 originalKeyCode, fallbackKeyCode);
6287 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006288 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006289
Michael Wrightfb04fd52022-11-24 22:31:11 +00006290 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006291 "canceling fallback, policy no longer desires it");
6292 options.keyCode = fallbackKeyCode;
6293 synthesizeCancelationEventsForConnectionLocked(connection, options);
6294
6295 fallback = false;
6296 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006297 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006298 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006299 }
6300 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006301
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006302 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6303 {
6304 std::string msg;
6305 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6306 connection->inputState.getFallbackKeys();
6307 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6308 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6309 }
6310 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6311 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006312 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006313 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006314
6315 if (fallback) {
6316 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006317 keyEntry.eventTime = event.getEventTime();
6318 keyEntry.deviceId = event.getDeviceId();
6319 keyEntry.source = event.getSource();
6320 keyEntry.displayId = event.getDisplayId();
6321 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6322 keyEntry.keyCode = fallbackKeyCode;
6323 keyEntry.scanCode = event.getScanCode();
6324 keyEntry.metaState = event.getMetaState();
6325 keyEntry.repeatCount = event.getRepeatCount();
6326 keyEntry.downTime = event.getDownTime();
6327 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006328
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006329 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6330 ALOGD("Unhandled key event: Dispatching fallback key. "
6331 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6332 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6333 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006334 return true; // restart the event
6335 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006336 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6337 ALOGD("Unhandled key event: No fallback key.");
6338 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006339
6340 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006341 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006342 }
6343 }
6344 return false;
6345}
6346
Prabir Pradhancef936d2021-07-21 16:17:52 +00006347bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006348 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006349 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006350 return false;
6351}
6352
Michael Wrightd02c5b62014-02-10 15:10:22 -08006353void InputDispatcher::traceInboundQueueLengthLocked() {
6354 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006355 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006356 }
6357}
6358
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006359void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006360 if (ATRACE_ENABLED()) {
6361 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006362 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6363 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006364 }
6365}
6366
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006367void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006368 if (ATRACE_ENABLED()) {
6369 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006370 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6371 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006372 }
6373}
6374
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006375void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006376 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006377
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006378 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006379 dumpDispatchStateLocked(dump);
6380
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006381 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006382 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006383 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006384 }
6385}
6386
6387void InputDispatcher::monitor() {
6388 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006389 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006390 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006391 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006392}
6393
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006394/**
6395 * Wake up the dispatcher and wait until it processes all events and commands.
6396 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6397 * this method can be safely called from any thread, as long as you've ensured that
6398 * the work you are interested in completing has already been queued.
6399 */
6400bool InputDispatcher::waitForIdle() {
6401 /**
6402 * Timeout should represent the longest possible time that a device might spend processing
6403 * events and commands.
6404 */
6405 constexpr std::chrono::duration TIMEOUT = 100ms;
6406 std::unique_lock lock(mLock);
6407 mLooper->wake();
6408 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6409 return result == std::cv_status::no_timeout;
6410}
6411
Vishnu Naire798b472020-07-23 13:52:21 -07006412/**
6413 * Sets focus to the window identified by the token. This must be called
6414 * after updating any input window handles.
6415 *
6416 * Params:
6417 * request.token - input channel token used to identify the window that should gain focus.
6418 * request.focusedToken - the token that the caller expects currently to be focused. If the
6419 * specified token does not match the currently focused window, this request will be dropped.
6420 * If the specified focused token matches the currently focused window, the call will succeed.
6421 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6422 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6423 * when requesting the focus change. This determines which request gets
6424 * precedence if there is a focus change request from another source such as pointer down.
6425 */
Vishnu Nair958da932020-08-21 17:12:37 -07006426void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6427 { // acquire lock
6428 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006429 std::optional<FocusResolver::FocusChanges> changes =
6430 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6431 if (changes) {
6432 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006433 }
6434 } // release lock
6435 // Wake up poll loop since it may need to make new input dispatching choices.
6436 mLooper->wake();
6437}
6438
Vishnu Nairc519ff72021-01-21 08:23:08 -08006439void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6440 if (changes.oldFocus) {
6441 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006442 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006443 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006444 "focus left window");
6445 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006446 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006447 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006448 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006449 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006450 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006451 }
6452
Prabir Pradhan99987712020-11-10 18:43:05 -08006453 // If a window has pointer capture, then it must have focus. We need to ensure that this
6454 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6455 // If the window loses focus before it loses pointer capture, then the window can be in a state
6456 // where it has pointer capture but not focus, violating the contract. Therefore we must
6457 // dispatch the pointer capture event before the focus event. Since focus events are added to
6458 // the front of the queue (above), we add the pointer capture event to the front of the queue
6459 // after the focus events are added. This ensures the pointer capture event ends up at the
6460 // front.
6461 disablePointerCaptureForcedLocked();
6462
Vishnu Nairc519ff72021-01-21 08:23:08 -08006463 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006464 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006465 }
6466}
Vishnu Nair958da932020-08-21 17:12:37 -07006467
Prabir Pradhan99987712020-11-10 18:43:05 -08006468void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006469 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006470 return;
6471 }
6472
6473 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6474
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006475 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006476 setPointerCaptureLocked(false);
6477 }
6478
6479 if (!mWindowTokenWithPointerCapture) {
6480 // No need to send capture changes because no window has capture.
6481 return;
6482 }
6483
6484 if (mPendingEvent != nullptr) {
6485 // Move the pending event to the front of the queue. This will give the chance
6486 // for the pending event to be dropped if it is a captured event.
6487 mInboundQueue.push_front(mPendingEvent);
6488 mPendingEvent = nullptr;
6489 }
6490
6491 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006492 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006493 mInboundQueue.push_front(std::move(entry));
6494}
6495
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006496void InputDispatcher::setPointerCaptureLocked(bool enable) {
6497 mCurrentPointerCaptureRequest.enable = enable;
6498 mCurrentPointerCaptureRequest.seq++;
6499 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006500 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006501 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006502 };
6503 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006504}
6505
Vishnu Nair599f1412021-06-21 10:39:58 -07006506void InputDispatcher::displayRemoved(int32_t displayId) {
6507 { // acquire lock
6508 std::scoped_lock _l(mLock);
6509 // Set an empty list to remove all handles from the specific display.
6510 setInputWindowsLocked(/* window handles */ {}, displayId);
6511 setFocusedApplicationLocked(displayId, nullptr);
6512 // Call focus resolver to clean up stale requests. This must be called after input windows
6513 // have been removed for the removed display.
6514 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006515 // Reset pointer capture eligibility, regardless of previous state.
6516 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006517 // Remove the associated touch mode state.
6518 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006519 } // release lock
6520
6521 // Wake up poll loop since it may need to make new input dispatching choices.
6522 mLooper->wake();
6523}
6524
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006525void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6526 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006527 // The listener sends the windows as a flattened array. Separate the windows by display for
6528 // more convenient parsing.
6529 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006530 for (const auto& info : windowInfos) {
6531 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006532 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006533 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006534
6535 { // acquire lock
6536 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006537
6538 // Ensure that we have an entry created for all existing displays so that if a displayId has
6539 // no windows, we can tell that the windows were removed from the display.
6540 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6541 handlesPerDisplay[displayId];
6542 }
6543
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006544 mDisplayInfos.clear();
6545 for (const auto& displayInfo : displayInfos) {
6546 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6547 }
6548
6549 for (const auto& [displayId, handles] : handlesPerDisplay) {
6550 setInputWindowsLocked(handles, displayId);
6551 }
6552 }
6553 // Wake up poll loop since it may need to make new input dispatching choices.
6554 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006555}
6556
Vishnu Nair062a8672021-09-03 16:07:44 -07006557bool InputDispatcher::shouldDropInput(
6558 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006559 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6560 (windowHandle->getInfo()->inputConfig.test(
6561 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006562 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006563 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6564 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006565 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006566 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006567 windowHandle->getInfo()->displayId);
6568 return true;
6569 }
6570 return false;
6571}
6572
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006573void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6574 const std::vector<gui::WindowInfo>& windowInfos,
6575 const std::vector<DisplayInfo>& displayInfos) {
6576 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6577}
6578
Arthur Hungdfd528e2021-12-08 13:23:04 +00006579void InputDispatcher::cancelCurrentTouch() {
6580 {
6581 std::scoped_lock _l(mLock);
6582 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006583 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006584 "cancel current touch");
6585 synthesizeCancelationEventsForAllConnectionsLocked(options);
6586
6587 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006588 }
6589 // Wake up poll loop since there might be work to do.
6590 mLooper->wake();
6591}
6592
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006593void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6594 std::scoped_lock _l(mLock);
6595 mMonitorDispatchingTimeout = timeout;
6596}
6597
Arthur Hungc539dbb2022-12-08 07:45:36 +00006598void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6599 const sp<WindowInfoHandle>& oldWindowHandle,
6600 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006601 TouchState& state, int32_t pointerId,
6602 std::vector<InputTarget>& targets) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006603 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6604 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006605 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6606 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6607 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6608 newWindowHandle->getInfo()->inputConfig.test(
6609 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6610 const sp<WindowInfoHandle> oldWallpaper =
6611 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6612 const sp<WindowInfoHandle> newWallpaper =
6613 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6614 if (oldWallpaper == newWallpaper) {
6615 return;
6616 }
6617
6618 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006619 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6620 addWindowTargetLocked(oldWallpaper,
6621 oldTouchedWindow.targetFlags |
6622 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6623 pointerIds, oldTouchedWindow.firstDownTimeInTarget, targets);
6624 state.removeTouchedPointerFromWindow(pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006625 }
6626
6627 if (newWallpaper != nullptr) {
6628 state.addOrUpdateWindow(newWallpaper,
6629 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6630 InputTarget::Flags::WINDOW_IS_OBSCURED |
6631 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6632 pointerIds);
6633 }
6634}
6635
6636void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6637 ftl::Flags<InputTarget::Flags> newTargetFlags,
6638 const sp<WindowInfoHandle> fromWindowHandle,
6639 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006640 TouchState& state,
6641 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006642 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6643 fromWindowHandle->getInfo()->inputConfig.test(
6644 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6645 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6646 toWindowHandle->getInfo()->inputConfig.test(
6647 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6648
6649 const sp<WindowInfoHandle> oldWallpaper =
6650 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6651 const sp<WindowInfoHandle> newWallpaper =
6652 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6653 if (oldWallpaper == newWallpaper) {
6654 return;
6655 }
6656
6657 if (oldWallpaper != nullptr) {
6658 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6659 "transferring touch focus to another window");
6660 state.removeWindowByToken(oldWallpaper->getToken());
6661 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6662 }
6663
6664 if (newWallpaper != nullptr) {
6665 nsecs_t downTimeInTarget = now();
6666 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6667 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6668 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6669 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6670 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
6671 sp<Connection> wallpaperConnection = getConnectionLocked(newWallpaper->getToken());
6672 if (wallpaperConnection != nullptr) {
6673 sp<Connection> toConnection = getConnectionLocked(toWindowHandle->getToken());
6674 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6675 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6676 wallpaperFlags);
6677 }
6678 }
6679}
6680
6681sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6682 const sp<WindowInfoHandle>& windowHandle) const {
6683 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6684 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6685 bool foundWindow = false;
6686 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6687 if (!foundWindow && otherHandle != windowHandle) {
6688 continue;
6689 }
6690 if (windowHandle == otherHandle) {
6691 foundWindow = true;
6692 continue;
6693 }
6694
6695 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6696 return otherHandle;
6697 }
6698 }
6699 return nullptr;
6700}
6701
Garfield Tane84e6f92019-08-29 17:28:41 -07006702} // namespace android::inputdispatcher