blob: bd8ae4a5aa97588ab39b2fe89e0a9cb23c8b12e6 [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 Pradhan82e081e2022-12-06 09:50:09 +0000478bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhand65552b2021-10-07 11:23:50 -0700479 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
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000543std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700544 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
545 // Always dispatch mouse events to cursor position.
546 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000547 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700548 }
549
550 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000551 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
552 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700553}
554
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700555std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
556 if (eventEntry.type == EventEntry::Type::KEY) {
557 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
558 return keyEntry.downTime;
559 } else if (eventEntry.type == EventEntry::Type::MOTION) {
560 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
561 return motionEntry.downTime;
562 }
563 return std::nullopt;
564}
565
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000566/**
567 * Compare the old touch state to the new touch state, and generate the corresponding touched
568 * windows (== input targets).
569 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
570 * If the pointer just entered the new window, produce HOVER_ENTER.
571 * For pointers remaining in the window, produce HOVER_MOVE.
572 */
573std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
574 const TouchState& newTouchState,
575 const MotionEntry& entry) {
576 std::vector<TouchedWindow> out;
577 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
578 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
579 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
580 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
581 // Not a hover event - don't need to do anything
582 return out;
583 }
584
585 // We should consider all hovering pointers here. But for now, just use the first one
586 const int32_t pointerId = entry.pointerProperties[0].id;
587
588 std::set<sp<WindowInfoHandle>> oldWindows;
589 if (oldState != nullptr) {
590 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
591 }
592
593 std::set<sp<WindowInfoHandle>> newWindows =
594 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
595
596 // If the pointer is no longer in the new window set, send HOVER_EXIT.
597 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
598 if (newWindows.find(oldWindow) == newWindows.end()) {
599 TouchedWindow touchedWindow;
600 touchedWindow.windowHandle = oldWindow;
601 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800602 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000603 out.push_back(touchedWindow);
604 }
605 }
606
607 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
608 TouchedWindow touchedWindow;
609 touchedWindow.windowHandle = newWindow;
610 if (oldWindows.find(newWindow) == oldWindows.end()) {
611 // Any windows that have this pointer now, and didn't have it before, should get
612 // HOVER_ENTER
613 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
614 } else {
615 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
616 LOG_ALWAYS_FATAL_IF(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE);
617 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
618 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800619 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000620 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
621 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
622 }
623 out.push_back(touchedWindow);
624 }
625 return out;
626}
627
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800628template <typename T>
629std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
630 left.insert(left.end(), right.begin(), right.end());
631 return left;
632}
633
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000634} // namespace
635
Michael Wrightd02c5b62014-02-10 15:10:22 -0800636// --- InputDispatcher ---
637
Garfield Tan00f511d2019-06-12 16:55:40 -0700638InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800639 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
640
641InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
642 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700643 : mPolicy(policy),
644 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700645 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800646 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700647 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700648 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700649 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800650 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700651 mDispatchEnabled(false),
652 mDispatchFrozen(false),
653 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100654 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000655 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800656 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800657 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000658 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000659 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700660 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800661 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800662
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700663 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700664#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700665 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700666#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700667 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668 policy->getDispatcherConfiguration(&mConfig);
669}
670
671InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000672 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800673
Prabir Pradhancef936d2021-07-21 16:17:52 +0000674 resetKeyRepeatLocked();
675 releasePendingEventLocked();
676 drainInboundQueueLocked();
677 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800678
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000679 while (!mConnectionsByToken.empty()) {
680 sp<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000681 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800682 }
683}
684
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700685status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700686 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700687 return ALREADY_EXISTS;
688 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700689 mThread = std::make_unique<InputThread>(
690 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
691 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700692}
693
694status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700695 if (mThread && mThread->isCallingThread()) {
696 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700697 return INVALID_OPERATION;
698 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700699 mThread.reset();
700 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700701}
702
Michael Wrightd02c5b62014-02-10 15:10:22 -0800703void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700704 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800705 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800706 std::scoped_lock _l(mLock);
707 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800708
709 // Run a dispatch loop if there are no pending commands.
710 // The dispatch loop might enqueue commands to run afterwards.
711 if (!haveCommandsLocked()) {
712 dispatchOnceInnerLocked(&nextWakeupTime);
713 }
714
715 // Run all pending commands if there are any.
716 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000717 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700718 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800719 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800720
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700721 // If we are still waiting for ack on some events,
722 // we might have to wake up earlier to check if an app is anr'ing.
723 const nsecs_t nextAnrCheck = processAnrsLocked();
724 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
725
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800726 // We are about to enter an infinitely long sleep, because we have no commands or
727 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700728 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800729 mDispatcherEnteredIdle.notify_all();
730 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800731 } // release lock
732
733 // Wait for callback or timeout or wake. (make sure we round up, not down)
734 nsecs_t currentTime = now();
735 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
736 mLooper->pollOnce(timeoutMillis);
737}
738
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700739/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500740 * Raise ANR if there is no focused window.
741 * Before the ANR is raised, do a final state check:
742 * 1. The currently focused application must be the same one we are waiting for.
743 * 2. Ensure we still don't have a focused window.
744 */
745void InputDispatcher::processNoFocusedWindowAnrLocked() {
746 // Check if the application that we are waiting for is still focused.
747 std::shared_ptr<InputApplicationHandle> focusedApplication =
748 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
749 if (focusedApplication == nullptr ||
750 focusedApplication->getApplicationToken() !=
751 mAwaitedFocusedApplication->getApplicationToken()) {
752 // Unexpected because we should have reset the ANR timer when focused application changed
753 ALOGE("Waited for a focused window, but focused application has already changed to %s",
754 focusedApplication->getName().c_str());
755 return; // The focused application has changed.
756 }
757
chaviw98318de2021-05-19 16:45:23 -0500758 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500759 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
760 if (focusedWindowHandle != nullptr) {
761 return; // We now have a focused window. No need for ANR.
762 }
763 onAnrLocked(mAwaitedFocusedApplication);
764}
765
766/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700767 * Check if any of the connections' wait queues have events that are too old.
768 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
769 * Return the time at which we should wake up next.
770 */
771nsecs_t InputDispatcher::processAnrsLocked() {
772 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700773 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700774 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
775 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
776 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500777 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700778 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500779 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700780 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700781 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500782 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700783 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
784 }
785 }
786
787 // Check if any connection ANRs are due
788 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
789 if (currentTime < nextAnrCheck) { // most likely scenario
790 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
791 }
792
793 // If we reached here, we have an unresponsive connection.
794 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
795 if (connection == nullptr) {
796 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
797 return nextAnrCheck;
798 }
799 connection->responsive = false;
800 // Stop waking up for this unresponsive connection
801 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000802 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700803 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700804}
805
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800806std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
807 const sp<Connection>& connection) {
808 if (connection->monitor) {
809 return mMonitorDispatchingTimeout;
810 }
811 const sp<WindowInfoHandle> window =
812 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700813 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500814 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700815 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500816 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700817}
818
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
820 nsecs_t currentTime = now();
821
Jeff Browndc5992e2014-04-11 01:27:26 -0700822 // Reset the key repeat timer whenever normal dispatch is suspended while the
823 // device is in a non-interactive state. This is to ensure that we abort a key
824 // repeat if the device is just coming out of sleep.
825 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800826 resetKeyRepeatLocked();
827 }
828
829 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
830 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100831 if (DEBUG_FOCUS) {
832 ALOGD("Dispatch frozen. Waiting some more.");
833 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800834 return;
835 }
836
837 // Optimize latency of app switches.
838 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
839 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
840 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
841 if (mAppSwitchDueTime < *nextWakeupTime) {
842 *nextWakeupTime = mAppSwitchDueTime;
843 }
844
845 // Ready to start a new event.
846 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700847 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700848 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849 if (isAppSwitchDue) {
850 // The inbound queue is empty so the app switch key we were waiting
851 // for will never arrive. Stop waiting for it.
852 resetPendingAppSwitchLocked(false);
853 isAppSwitchDue = false;
854 }
855
856 // Synthesize a key repeat if appropriate.
857 if (mKeyRepeatState.lastKeyEntry) {
858 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
859 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
860 } else {
861 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
862 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
863 }
864 }
865 }
866
867 // Nothing to do if there is no pending event.
868 if (!mPendingEvent) {
869 return;
870 }
871 } else {
872 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700873 mPendingEvent = mInboundQueue.front();
874 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 traceInboundQueueLengthLocked();
876 }
877
878 // Poke user activity for this event.
879 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700880 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882 }
883
884 // Now we have an event to dispatch.
885 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700886 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700888 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700890 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700892 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893 }
894
895 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700896 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 }
898
899 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700900 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700901 const ConfigurationChangedEntry& typedEntry =
902 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700903 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700904 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700905 break;
906 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700908 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700909 const DeviceResetEntry& typedEntry =
910 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700911 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700912 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700913 break;
914 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800915
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100916 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700917 std::shared_ptr<FocusEntry> typedEntry =
918 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100919 dispatchFocusLocked(currentTime, typedEntry);
920 done = true;
921 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
922 break;
923 }
924
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700925 case EventEntry::Type::TOUCH_MODE_CHANGED: {
926 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
927 dispatchTouchModeChangeLocked(currentTime, typedEntry);
928 done = true;
929 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
930 break;
931 }
932
Prabir Pradhan99987712020-11-10 18:43:05 -0800933 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
934 const auto typedEntry =
935 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
936 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
937 done = true;
938 break;
939 }
940
arthurhungb89ccb02020-12-30 16:19:01 +0800941 case EventEntry::Type::DRAG: {
942 std::shared_ptr<DragEntry> typedEntry =
943 std::static_pointer_cast<DragEntry>(mPendingEvent);
944 dispatchDragLocked(currentTime, typedEntry);
945 done = true;
946 break;
947 }
948
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700949 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700950 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700951 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700952 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700953 resetPendingAppSwitchLocked(true);
954 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700955 } else if (dropReason == DropReason::NOT_DROPPED) {
956 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700957 }
958 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700959 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700960 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700961 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700962 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
963 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700964 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700965 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700966 break;
967 }
968
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700969 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700970 std::shared_ptr<MotionEntry> motionEntry =
971 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700972 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
973 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700975 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700976 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700977 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700978 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
979 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700980 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700981 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700982 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983 }
Chris Yef59a2f42020-10-16 12:55:26 -0700984
985 case EventEntry::Type::SENSOR: {
986 std::shared_ptr<SensorEntry> sensorEntry =
987 std::static_pointer_cast<SensorEntry>(mPendingEvent);
988 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
989 dropReason = DropReason::APP_SWITCH;
990 }
991 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
992 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
993 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
994 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
995 dropReason = DropReason::STALE;
996 }
997 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
998 done = true;
999 break;
1000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 }
1002
1003 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001004 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001005 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 }
Michael Wright3a981722015-06-10 15:26:13 +01001007 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008
1009 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001010 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011 }
1012}
1013
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001014bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1015 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1016}
1017
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001018/**
1019 * Return true if the events preceding this incoming motion event should be dropped
1020 * Return false otherwise (the default behaviour)
1021 */
1022bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001023 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001024 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001025
1026 // Optimize case where the current application is unresponsive and the user
1027 // decides to touch a window in a different application.
1028 // If the application takes too long to catch up then we drop all events preceding
1029 // the touch into the other window.
1030 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001031 const int32_t displayId = motionEntry.displayId;
1032 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001033 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001034
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001035 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001036 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001037 touchedWindowHandle->getApplicationToken() !=
1038 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001039 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001040 ALOGI("Pruning input queue because user touched a different application while waiting "
1041 "for %s",
1042 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001043 return true;
1044 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001045
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001046 // Alternatively, maybe there's a spy window that could handle this event.
1047 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1048 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1049 for (const auto& windowHandle : touchedSpies) {
1050 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001051 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001052 // This spy window could take more input. Drop all events preceding this
1053 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001054 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001055 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001056 mAwaitedFocusedApplication->getName().c_str());
1057 return true;
1058 }
1059 }
1060 }
1061
1062 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1063 // yet been processed by some connections, the dispatcher will wait for these motion
1064 // events to be processed before dispatching the key event. This is because these motion events
1065 // may cause a new window to be launched, which the user might expect to receive focus.
1066 // To prevent waiting forever for such events, just send the key to the currently focused window
1067 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1068 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1069 "just send the pending key event to the focused window.");
1070 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001071 }
1072 return false;
1073}
1074
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001075bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001076 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001077 mInboundQueue.push_back(std::move(newEntry));
1078 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079 traceInboundQueueLengthLocked();
1080
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001081 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001082 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001083 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1084 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001085 // Optimize app switch latency.
1086 // If the application takes too long to catch up then we drop all events preceding
1087 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001088 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001089 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001090 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001091 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001092 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001093 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001094 if (DEBUG_APP_SWITCH) {
1095 ALOGD("App switch is pending!");
1096 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001097 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001098 mAppSwitchSawKeyDown = false;
1099 needWake = true;
1100 }
1101 }
1102 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001103
1104 // If a new up event comes in, and the pending event with same key code has been asked
1105 // to try again later because of the policy. We have to reset the intercept key wake up
1106 // time for it may have been handled in the policy and could be dropped.
1107 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1108 mPendingEvent->type == EventEntry::Type::KEY) {
1109 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1110 if (pendingKey.keyCode == keyEntry.keyCode &&
1111 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001112 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1113 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001114 pendingKey.interceptKeyWakeupTime = 0;
1115 needWake = true;
1116 }
1117 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001118 break;
1119 }
1120
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001121 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001122 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1123 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001124 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1125 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001126 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001128 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001129 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001130 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001131 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1132 break;
1133 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001134 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001135 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001136 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001137 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001138 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1139 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001140 // nothing to do
1141 break;
1142 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001143 }
1144
1145 return needWake;
1146}
1147
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001148void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001149 // Do not store sensor event in recent queue to avoid flooding the queue.
1150 if (entry->type != EventEntry::Type::SENSOR) {
1151 mRecentQueue.push_back(entry);
1152 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001153 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001154 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155 }
1156}
1157
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001158std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001159InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001160 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001162 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001163 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001164 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001165 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001166 continue;
1167 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001169 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001170 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001171 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001172 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001173
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001174 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1175 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001176 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001177 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178 }
1179 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001180 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181}
1182
Prabir Pradhand65552b2021-10-07 11:23:50 -07001183std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001184 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001185 // Traverse windows from front to back and gather the touched spy windows.
1186 std::vector<sp<WindowInfoHandle>> spyWindows;
1187 const auto& windowHandles = getWindowHandlesLocked(displayId);
1188 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1189 const WindowInfo& info = *windowHandle->getInfo();
1190
Prabir Pradhand65552b2021-10-07 11:23:50 -07001191 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001192 continue;
1193 }
1194 if (!info.isSpy()) {
1195 // The first touched non-spy window was found, so return the spy windows touched so far.
1196 return spyWindows;
1197 }
1198 spyWindows.push_back(windowHandle);
1199 }
1200 return spyWindows;
1201}
1202
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001203void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 const char* reason;
1205 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001206 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001207 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001208 ALOGD("Dropped event because policy consumed it.");
1209 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001210 reason = "inbound event was dropped because the policy consumed it";
1211 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001212 case DropReason::DISABLED:
1213 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001214 ALOGI("Dropped event because input dispatch is disabled.");
1215 }
1216 reason = "inbound event was dropped because input dispatch is disabled";
1217 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001218 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001219 ALOGI("Dropped event because of pending overdue app switch.");
1220 reason = "inbound event was dropped because of pending overdue app switch";
1221 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001222 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001223 ALOGI("Dropped event because the current application is not responding and the user "
1224 "has started interacting with a different application.");
1225 reason = "inbound event was dropped because the current application is not responding "
1226 "and the user has started interacting with a different application";
1227 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001228 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001229 ALOGI("Dropped event because it is stale.");
1230 reason = "inbound event was dropped because it is stale";
1231 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001232 case DropReason::NO_POINTER_CAPTURE:
1233 ALOGI("Dropped event because there is no window with Pointer Capture.");
1234 reason = "inbound event was dropped because there is no window with Pointer Capture";
1235 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001236 case DropReason::NOT_DROPPED: {
1237 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001238 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001239 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 }
1241
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001242 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001243 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001244 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001246 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001248 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001249 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1250 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001251 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001252 synthesizeCancelationEventsForAllConnectionsLocked(options);
1253 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001254 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1255 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001256 synthesizeCancelationEventsForAllConnectionsLocked(options);
1257 }
1258 break;
1259 }
Chris Yef59a2f42020-10-16 12:55:26 -07001260 case EventEntry::Type::SENSOR: {
1261 break;
1262 }
arthurhungb89ccb02020-12-30 16:19:01 +08001263 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1264 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001265 break;
1266 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001267 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001268 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001269 case EventEntry::Type::CONFIGURATION_CHANGED:
1270 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001271 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001272 break;
1273 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274 }
1275}
1276
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001277static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001278 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1279 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280}
1281
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001282bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1283 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1284 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1285 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286}
1287
1288bool InputDispatcher::isAppSwitchPendingLocked() {
Colin Cross5b799302022-10-18 21:52:41 -07001289 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290}
1291
1292void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001293 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001295 if (DEBUG_APP_SWITCH) {
1296 if (handled) {
1297 ALOGD("App switch has arrived.");
1298 } else {
1299 ALOGD("App switch was abandoned.");
1300 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001301 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302}
1303
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001305 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306}
1307
Prabir Pradhancef936d2021-07-21 16:17:52 +00001308bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001309 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310 return false;
1311 }
1312
1313 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001314 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001315 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001316 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1317 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001318 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001319 return true;
1320}
1321
Prabir Pradhancef936d2021-07-21 16:17:52 +00001322void InputDispatcher::postCommandLocked(Command&& command) {
1323 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324}
1325
1326void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001327 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001328 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001329 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330 releaseInboundEventLocked(entry);
1331 }
1332 traceInboundQueueLengthLocked();
1333}
1334
1335void InputDispatcher::releasePendingEventLocked() {
1336 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001338 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 }
1340}
1341
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001342void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001344 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001345 if (DEBUG_DISPATCH_CYCLE) {
1346 ALOGD("Injected inbound event was dropped.");
1347 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001348 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349 }
1350 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001351 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352 }
1353 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354}
1355
1356void InputDispatcher::resetKeyRepeatLocked() {
1357 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001358 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001359 }
1360}
1361
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001362std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1363 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364
Michael Wright2e732952014-09-24 13:26:59 -07001365 uint32_t policyFlags = entry->policyFlags &
1366 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001367
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001368 std::shared_ptr<KeyEntry> newEntry =
1369 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1370 entry->source, entry->displayId, policyFlags, entry->action,
1371 entry->flags, entry->keyCode, entry->scanCode,
1372 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001373
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001374 newEntry->syntheticRepeat = true;
1375 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001377 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378}
1379
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001380bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001381 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001382 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1383 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1384 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001385
1386 // Reset key repeating in case a keyboard device was added or removed or something.
1387 resetKeyRepeatLocked();
1388
1389 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001390 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1391 scoped_unlock unlock(mLock);
1392 mPolicy->notifyConfigurationChanged(eventTime);
1393 };
1394 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395 return true;
1396}
1397
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001398bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1399 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001400 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1401 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1402 entry.deviceId);
1403 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001404
liushenxiang42232912021-05-21 20:24:09 +08001405 // Reset key repeating in case a keyboard device was disabled or enabled.
1406 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1407 resetKeyRepeatLocked();
1408 }
1409
Michael Wrightfb04fd52022-11-24 22:31:11 +00001410 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001411 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001412 synthesizeCancelationEventsForAllConnectionsLocked(options);
1413 return true;
1414}
1415
Vishnu Nairad321cd2020-08-20 16:40:21 -07001416void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001417 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001418 if (mPendingEvent != nullptr) {
1419 // Move the pending event to the front of the queue. This will give the chance
1420 // for the pending event to get dispatched to the newly focused window
1421 mInboundQueue.push_front(mPendingEvent);
1422 mPendingEvent = nullptr;
1423 }
1424
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001425 std::unique_ptr<FocusEntry> focusEntry =
1426 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1427 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001428
1429 // This event should go to the front of the queue, but behind all other focus events
1430 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001431 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001432 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001433 [](const std::shared_ptr<EventEntry>& event) {
1434 return event->type == EventEntry::Type::FOCUS;
1435 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001436
1437 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001438 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001439}
1440
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001441void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001442 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001443 if (channel == nullptr) {
1444 return; // Window has gone away
1445 }
1446 InputTarget target;
1447 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001448 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001449 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001450 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1451 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001452 std::string reason = std::string("reason=").append(entry->reason);
1453 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001454 dispatchEventLocked(currentTime, entry, {target});
1455}
1456
Prabir Pradhan99987712020-11-10 18:43:05 -08001457void InputDispatcher::dispatchPointerCaptureChangedLocked(
1458 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1459 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001460 dropReason = DropReason::NOT_DROPPED;
1461
Prabir Pradhan99987712020-11-10 18:43:05 -08001462 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001463 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001464
1465 if (entry->pointerCaptureRequest.enable) {
1466 // Enable Pointer Capture.
1467 if (haveWindowWithPointerCapture &&
1468 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001469 // This can happen if pointer capture is disabled and re-enabled before we notify the
1470 // app of the state change, so there is no need to notify the app.
1471 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1472 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001473 }
1474 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001475 // This can happen if a window requests capture and immediately releases capture.
1476 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001477 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001478 return;
1479 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001480 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1481 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1482 return;
1483 }
1484
Vishnu Nairc519ff72021-01-21 08:23:08 -08001485 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001486 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1487 mWindowTokenWithPointerCapture = token;
1488 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001489 // Disable Pointer Capture.
1490 // We do not check if the sequence number matches for requests to disable Pointer Capture
1491 // for two reasons:
1492 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1493 // to disable capture with the same sequence number: one generated by
1494 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1495 // Capture being disabled in InputReader.
1496 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1497 // actual Pointer Capture state that affects events being generated by input devices is
1498 // in InputReader.
1499 if (!haveWindowWithPointerCapture) {
1500 // Pointer capture was already forcefully disabled because of focus change.
1501 dropReason = DropReason::NOT_DROPPED;
1502 return;
1503 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001504 token = mWindowTokenWithPointerCapture;
1505 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001506 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001507 setPointerCaptureLocked(false);
1508 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001509 }
1510
1511 auto channel = getInputChannelLocked(token);
1512 if (channel == nullptr) {
1513 // Window has gone away, clean up Pointer Capture state.
1514 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001515 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001516 setPointerCaptureLocked(false);
1517 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001518 return;
1519 }
1520 InputTarget target;
1521 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001522 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001523 entry->dispatchInProgress = true;
1524 dispatchEventLocked(currentTime, entry, {target});
1525
1526 dropReason = DropReason::NOT_DROPPED;
1527}
1528
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001529void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1530 const std::shared_ptr<TouchModeEntry>& entry) {
1531 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001532 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001533 if (windowHandles.empty()) {
1534 return;
1535 }
1536 const std::vector<InputTarget> inputTargets =
1537 getInputTargetsFromWindowHandlesLocked(windowHandles);
1538 if (inputTargets.empty()) {
1539 return;
1540 }
1541 entry->dispatchInProgress = true;
1542 dispatchEventLocked(currentTime, entry, inputTargets);
1543}
1544
1545std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1546 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1547 std::vector<InputTarget> inputTargets;
1548 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001549 const sp<IBinder>& token = handle->getToken();
1550 if (token == nullptr) {
1551 continue;
1552 }
1553 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1554 if (channel == nullptr) {
1555 continue; // Window has gone away
1556 }
1557 InputTarget target;
1558 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001559 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001560 inputTargets.push_back(target);
1561 }
1562 return inputTargets;
1563}
1564
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001565bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001566 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001568 if (!entry->dispatchInProgress) {
1569 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1570 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1571 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1572 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001573 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574 // We have seen two identical key downs in a row which indicates that the device
1575 // driver is automatically generating key repeats itself. We take note of the
1576 // repeat here, but we disable our own next key repeat timer since it is clear that
1577 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001578 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1579 // Make sure we don't get key down from a different device. If a different
1580 // device Id has same key pressed down, the new device Id will replace the
1581 // current one to hold the key repeat with repeat count reset.
1582 // In the future when got a KEY_UP on the device id, drop it and do not
1583 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1585 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001586 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 } else {
1588 // Not a repeat. Save key down state in case we do see a repeat later.
1589 resetKeyRepeatLocked();
1590 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1591 }
1592 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001593 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1594 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001595 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001596 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001597 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1598 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001599 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 resetKeyRepeatLocked();
1601 }
1602
1603 if (entry->repeatCount == 1) {
1604 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1605 } else {
1606 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1607 }
1608
1609 entry->dispatchInProgress = true;
1610
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001611 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001612 }
1613
1614 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001615 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001616 if (currentTime < entry->interceptKeyWakeupTime) {
1617 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1618 *nextWakeupTime = entry->interceptKeyWakeupTime;
1619 }
1620 return false; // wait until next wakeup
1621 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001622 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001623 entry->interceptKeyWakeupTime = 0;
1624 }
1625
1626 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001627 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001629 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001630 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001631
1632 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1633 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1634 };
1635 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 return false; // wait for the command to run
1637 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001638 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001639 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001640 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001641 if (*dropReason == DropReason::NOT_DROPPED) {
1642 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001643 }
1644 }
1645
1646 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001647 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001648 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001649 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1650 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001651 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 return true;
1653 }
1654
1655 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001656 InputEventInjectionResult injectionResult;
1657 sp<WindowInfoHandle> focusedWindow =
1658 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1659 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001660 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661 return false;
1662 }
1663
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001664 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001665 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 return true;
1667 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001668 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1669
1670 std::vector<InputTarget> inputTargets;
1671 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001672 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001673 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001675 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001676 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001677
1678 // Dispatch the key.
1679 dispatchEventLocked(currentTime, entry, inputTargets);
1680 return true;
1681}
1682
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001683void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001684 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1685 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1686 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1687 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1688 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1689 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1690 entry.metaState, entry.repeatCount, entry.downTime);
1691 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001692}
1693
Prabir Pradhancef936d2021-07-21 16:17:52 +00001694void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1695 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001696 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001697 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1698 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1699 "source=0x%x, sensorType=%s",
1700 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001701 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001702 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001703 auto command = [this, entry]() REQUIRES(mLock) {
1704 scoped_unlock unlock(mLock);
1705
1706 if (entry->accuracyChanged) {
1707 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1708 }
1709 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1710 entry->hwTimestamp, entry->values);
1711 };
1712 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001713}
1714
1715bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001716 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1717 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001718 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001719 }
Chris Yef59a2f42020-10-16 12:55:26 -07001720 { // acquire lock
1721 std::scoped_lock _l(mLock);
1722
1723 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1724 std::shared_ptr<EventEntry> entry = *it;
1725 if (entry->type == EventEntry::Type::SENSOR) {
1726 it = mInboundQueue.erase(it);
1727 releaseInboundEventLocked(entry);
1728 }
1729 }
1730 }
1731 return true;
1732}
1733
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001734bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001735 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001736 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001738 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 entry->dispatchInProgress = true;
1740
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001741 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 }
1743
1744 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001745 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001746 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001747 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1748 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749 return true;
1750 }
1751
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001752 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001753
1754 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001755 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756
1757 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001758 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759 if (isPointerEvent) {
1760 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001761
1762 if (mDragState &&
1763 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1764 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1765 pilferPointersLocked(mDragState->dragWindow->getToken());
1766 }
1767
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001768 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001769 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001770 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001771 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1772 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773 } else {
1774 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001775 sp<WindowInfoHandle> focusedWindow =
1776 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1777 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1778 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1779 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001780 InputTarget::Flags::FOREGROUND |
1781 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001782 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001783 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001785 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001786 return false;
1787 }
1788
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001789 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001790 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001791 return true;
1792 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001793 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001794 CancelationOptions::Mode mode(
1795 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1796 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001797 CancelationOptions options(mode, "input event injection failed");
1798 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 return true;
1800 }
1801
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001802 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001803 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001804
1805 // Dispatch the motion.
1806 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001807 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001808 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 synthesizeCancelationEventsForAllConnectionsLocked(options);
1810 }
1811 dispatchEventLocked(currentTime, entry, inputTargets);
1812 return true;
1813}
1814
chaviw98318de2021-05-19 16:45:23 -05001815void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001816 bool isExiting, const int32_t rawX,
1817 const int32_t rawY) {
1818 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001819 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001820 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1821 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001822
1823 enqueueInboundEventLocked(std::move(dragEntry));
1824}
1825
1826void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1827 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1828 if (channel == nullptr) {
1829 return; // Window has gone away
1830 }
1831 InputTarget target;
1832 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001833 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001834 entry->dispatchInProgress = true;
1835 dispatchEventLocked(currentTime, entry, {target});
1836}
1837
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001838void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001839 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001840 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001841 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001842 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001843 "metaState=0x%x, buttonState=0x%x,"
1844 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001845 prefix, entry.eventTime, entry.deviceId,
1846 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1847 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1848 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1849 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001851 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1852 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1853 "x=%f, y=%f, pressure=%f, size=%f, "
1854 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1855 "orientation=%f",
1856 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1857 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1858 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1859 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1860 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1861 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1862 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1863 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1864 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1865 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1866 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001867 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868}
1869
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001870void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1871 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001872 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001873 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001874 if (DEBUG_DISPATCH_CYCLE) {
1875 ALOGD("dispatchEventToCurrentInputTargets");
1876 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001878 updateInteractionTokensLocked(*eventEntry, inputTargets);
1879
Michael Wrightd02c5b62014-02-10 15:10:22 -08001880 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1881
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001882 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001883
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001884 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001885 sp<Connection> connection =
1886 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001887 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001888 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001890 if (DEBUG_FOCUS) {
1891 ALOGD("Dropping event delivery to target with channel '%s' because it "
1892 "is no longer registered with the input dispatcher.",
1893 inputTarget.inputChannel->getName().c_str());
1894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895 }
1896 }
1897}
1898
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001899void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1900 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1901 // If the policy decides to close the app, we will get a channel removal event via
1902 // unregisterInputChannel, and will clean up the connection that way. We are already not
1903 // sending new pointers to the connection when it blocked, but focused events will continue to
1904 // pile up.
1905 ALOGW("Canceling events for %s because it is unresponsive",
1906 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001907 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001908 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001909 "application not responding");
1910 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911 }
1912}
1913
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001914void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001915 if (DEBUG_FOCUS) {
1916 ALOGD("Resetting ANR timeouts.");
1917 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918
1919 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001920 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001921 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001922}
1923
Tiger Huang721e26f2018-07-24 22:26:19 +08001924/**
1925 * Get the display id that the given event should go to. If this event specifies a valid display id,
1926 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1927 * Focused display is the display that the user most recently interacted with.
1928 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001929int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001930 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001931 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001932 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001933 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1934 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001935 break;
1936 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001937 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001938 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1939 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001940 break;
1941 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001942 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001943 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001944 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001945 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001946 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001947 case EventEntry::Type::SENSOR:
1948 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001949 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001950 return ADISPLAY_ID_NONE;
1951 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001952 }
1953 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1954}
1955
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001956bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1957 const char* focusedWindowName) {
1958 if (mAnrTracker.empty()) {
1959 // already processed all events that we waited for
1960 mKeyIsWaitingForEventsTimeout = std::nullopt;
1961 return false;
1962 }
1963
1964 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1965 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001966 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001967 mKeyIsWaitingForEventsTimeout = currentTime +
1968 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1969 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001970 return true;
1971 }
1972
1973 // We still have pending events, and already started the timer
1974 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1975 return true; // Still waiting
1976 }
1977
1978 // Waited too long, and some connection still hasn't processed all motions
1979 // Just send the key to the focused window
1980 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1981 focusedWindowName);
1982 mKeyIsWaitingForEventsTimeout = std::nullopt;
1983 return false;
1984}
1985
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001986sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
1987 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
1988 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001989 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001990 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991
Tiger Huang721e26f2018-07-24 22:26:19 +08001992 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001993 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001994 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001995 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1996
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997 // If there is no currently focused window and no focused application
1998 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001999 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2000 ALOGI("Dropping %s event because there is no focused window or focused application in "
2001 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002002 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002003 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004 }
2005
Vishnu Nair062a8672021-09-03 16:07:44 -07002006 // Drop key events if requested by input feature
2007 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002008 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002009 }
2010
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002011 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2012 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2013 // start interacting with another application via touch (app switch). This code can be removed
2014 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2015 // an app is expected to have a focused window.
2016 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2017 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2018 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002019 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2020 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2021 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002022 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002023 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002024 ALOGW("Waiting because no window has focus but %s may eventually add a "
2025 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002026 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002027 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002028 outInjectionResult = InputEventInjectionResult::PENDING;
2029 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002030 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2031 // Already raised ANR. Drop the event
2032 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002033 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002034 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002035 } else {
2036 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002037 outInjectionResult = InputEventInjectionResult::PENDING;
2038 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002039 }
2040 }
2041
2042 // we have a valid, non-null focused window
2043 resetNoFocusedWindowTimeoutLocked();
2044
Prabir Pradhan5735a322022-04-11 17:23:34 +00002045 // Verify targeted injection.
2046 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2047 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002048 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2049 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002050 }
2051
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002052 if (focusedWindowHandle->getInfo()->inputConfig.test(
2053 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002054 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002055 outInjectionResult = InputEventInjectionResult::PENDING;
2056 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002057 }
2058
2059 // If the event is a key event, then we must wait for all previous events to
2060 // complete before delivering it because previous events may have the
2061 // side-effect of transferring focus to a different window and we want to
2062 // ensure that the following keys are sent to the new window.
2063 //
2064 // Suppose the user touches a button in a window then immediately presses "A".
2065 // If the button causes a pop-up window to appear then we want to ensure that
2066 // the "A" key is delivered to the new pop-up window. This is because users
2067 // often anticipate pending UI changes when typing on a keyboard.
2068 // To obtain this behavior, we must serialize key events with respect to all
2069 // prior input events.
2070 if (entry.type == EventEntry::Type::KEY) {
2071 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2072 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002073 outInjectionResult = InputEventInjectionResult::PENDING;
2074 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002075 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076 }
2077
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002078 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2079 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080}
2081
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002082/**
2083 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2084 * that are currently unresponsive.
2085 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002086std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2087 const std::vector<Monitor>& monitors) const {
2088 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002089 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002090 [this](const Monitor& monitor) REQUIRES(mLock) {
2091 sp<Connection> connection =
2092 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002093 if (connection == nullptr) {
2094 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002095 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002096 return false;
2097 }
2098 if (!connection->responsive) {
2099 ALOGW("Unresponsive monitor %s will not get the new gesture",
2100 connection->inputChannel->getName().c_str());
2101 return false;
2102 }
2103 return true;
2104 });
2105 return responsiveMonitors;
2106}
2107
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002108/**
2109 * In general, touch should be always split between windows. Some exceptions:
2110 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2111 * from the same device, *and* the window that's receiving the current pointer does not support
2112 * split touch.
2113 * 2. Don't split mouse events
2114 */
2115bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2116 const MotionEntry& entry) const {
2117 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2118 // We should never split mouse events
2119 return false;
2120 }
2121 for (const TouchedWindow& touchedWindow : touchState.windows) {
2122 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2123 // Spy windows should not affect whether or not touch is split.
2124 continue;
2125 }
2126 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2127 continue;
2128 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002129 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2130 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2131 // Wallpaper window should not affect whether or not touch is split
2132 continue;
2133 }
2134
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002135 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2136 // being sent there. For now, use deviceId from touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002137 if (entry.deviceId == touchState.deviceId && touchedWindow.pointerIds.any()) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002138 return false;
2139 }
2140 }
2141 return true;
2142}
2143
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002144std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002145 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2146 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002147 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002149 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 // For security reasons, we defer updating the touch state until we are sure that
2151 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002152 const int32_t displayId = entry.displayId;
2153 const int32_t action = entry.action;
2154 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155
2156 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002157 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002159 // Copy current touch state into tempTouchState.
2160 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2161 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002162 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002163 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002164 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2165 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002166 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002167 }
2168
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002169 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002170 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002171 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002172
2173 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2174 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2175 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002176 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2177 // touchable windows.
2178 const bool wasDown = oldState != nullptr && oldState->isDown();
2179 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2180 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
2181 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002182 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002183
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002184 // If pointers are already down, let's finish the current gesture and ignore the new events
2185 // from another device. However, if the new event is a down event, let's cancel the current
2186 // touch and let the new one take over.
2187 if (switchedDevice && wasDown && !isDown) {
2188 LOG(INFO) << "Dropping event because a pointer for device " << oldState->deviceId
2189 << " is already down in display " << displayId << ": " << entry.getDescription();
2190 // TODO(b/211379801): test multiple simultaneous input streams.
2191 outInjectionResult = InputEventInjectionResult::FAILED;
2192 return {}; // wrong device
2193 }
2194
Michael Wrightd02c5b62014-02-10 15:10:22 -08002195 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002196 // If a new gesture is starting, clear the touch state completely.
2197 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002198 tempTouchState.deviceId = entry.deviceId;
2199 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002200 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002201 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002202 ALOGI("Dropping move event because a pointer for a different device is already active "
2203 "in display %" PRId32,
2204 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002205 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002206 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002207 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002208 }
2209
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002210 if (isHoverAction) {
2211 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2212 // all of the existing hovering pointers and recompute.
2213 tempTouchState.clearHoveringPointers();
2214 }
2215
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2217 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002218 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002219 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002220 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2221 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002222 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002223 auto [newTouchedWindowHandle, outsideTargets] =
2224 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002225
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002226 if (isDown) {
2227 targets += outsideTargets;
2228 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002230 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002231 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002233 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002234 }
2235
Prabir Pradhan5735a322022-04-11 17:23:34 +00002236 // Verify targeted injection.
2237 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2238 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002239 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002240 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002241 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002242 }
2243
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002244 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002245 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002246 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2247 // New window supports splitting, but we should never split mouse events.
2248 isSplit = !isFromMouse;
2249 } else if (isSplit) {
2250 // New window does not support splitting but we have already split events.
2251 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002252 newTouchedWindowHandle = nullptr;
2253 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002254 } else {
2255 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002256 // be delivered to a new window which supports split touch. Pointers from a mouse device
2257 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002258 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002259 }
2260
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002261 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002262 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002263 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002264 // Process the foreground window first so that it is the first to receive the event.
2265 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002266 }
2267
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002268 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002269 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2270 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002271 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002272 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002273 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002274 }
2275
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002276 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002277 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002278 continue;
2279 }
2280
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002281 if (isHoverAction) {
2282 const int32_t pointerId = entry.pointerProperties[0].id;
2283 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2284 // Pointer left. Remove it
2285 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2286 } else {
2287 // The "windowHandle" is the target of this hovering pointer.
2288 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId,
2289 pointerId);
2290 }
2291 }
2292
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002293 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002294 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002295
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002296 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2297 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002298 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002299 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002300
2301 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002302 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002303 }
2304 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002305 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002306 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002307 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002308 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002309
2310 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002311 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002312 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002313 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002314 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002315
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002316 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2317 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2318
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002319 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2320 // still add a window to the touch state. We should avoid doing that, but some of the
2321 // later checks ("at least one foreground window") rely on this in order to dispatch
2322 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002323 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002324 isDownOrPointerDown
2325 ? std::make_optional(entry.eventTime)
2326 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002327
2328 // If this is the pointer going down and the touched window has a wallpaper
2329 // then also add the touched wallpaper windows so they are locked in for the duration
2330 // of the touch gesture.
2331 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2332 // engine only supports touch events. We would need to add a mechanism similar
2333 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002334 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002335 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2336 windowHandle->getInfo()->inputConfig.test(
2337 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2338 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2339 if (wallpaper != nullptr) {
2340 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2341 InputTarget::Flags::WINDOW_IS_OBSCURED |
2342 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2343 InputTarget::Flags::DISPATCH_AS_IS;
2344 if (isSplit) {
2345 wallpaperFlags |= InputTarget::Flags::SPLIT;
2346 }
2347 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2348 entry.eventTime);
2349 }
2350 }
2351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002353
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002354 // If a window is already pilfering some pointers, give it this new pointer as well and
2355 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2356 // which is a specific behaviour that we want.
2357 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2358 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002359 if (touchedWindow.pointerIds.test(pointerId) &&
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002360 touchedWindow.pilferedPointerIds.count() > 0) {
2361 // This window is already pilfering some pointers, and this new pointer is also
2362 // going to it. Therefore, take over this pointer and don't give it to anyone
2363 // else.
2364 touchedWindow.pilferedPointerIds.set(pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002365 }
2366 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002367
2368 // Restrict all pilfered pointers to the pilfering windows.
2369 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370 } else {
2371 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2372
2373 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002374 if (!tempTouchState.isDown()) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002375 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2376 "dropped the pointer down event in display "
2377 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002378 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002379 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380 }
2381
arthurhung6d4bed92021-03-17 11:59:33 +08002382 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002383
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002385 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002386 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002387 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002388 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002389 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002390 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002391 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002392
Prabir Pradhan5735a322022-04-11 17:23:34 +00002393 // Verify targeted injection.
2394 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2395 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002396 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002397 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002398 }
2399
Vishnu Nair062a8672021-09-03 16:07:44 -07002400 // Drop touch events if requested by input feature
2401 if (newTouchedWindowHandle != nullptr &&
2402 shouldDropInput(entry, newTouchedWindowHandle)) {
2403 newTouchedWindowHandle = nullptr;
2404 }
2405
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002406 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2407 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002408 if (DEBUG_FOCUS) {
2409 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2410 oldTouchedWindowHandle->getName().c_str(),
2411 newTouchedWindowHandle->getName().c_str(), displayId);
2412 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002414 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002415 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002416 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002417
2418 const TouchedWindow& touchedWindow =
2419 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2420 addWindowTargetLocked(oldTouchedWindowHandle,
2421 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
2422 touchedWindow.firstDownTimeInTarget, targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002423
2424 // Make a slippery entrance into the new window.
2425 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002426 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002427 }
2428
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002429 ftl::Flags<InputTarget::Flags> targetFlags =
2430 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002431 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002432 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002433 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002434 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002435 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436 }
2437 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002438 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002439 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002440 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441 }
2442
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002443 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2444 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002445
2446 // Check if the wallpaper window should deliver the corresponding event.
2447 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002448 tempTouchState, pointerId, targets);
2449 tempTouchState.removeTouchedPointerFromWindow(pointerId, oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002450 }
2451 }
Arthur Hung96483742022-11-15 03:30:48 +00002452
2453 // Update the pointerIds for non-splittable when it received pointer down.
2454 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2455 // If no split, we suppose all touched windows should receive pointer down.
2456 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2457 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2458 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2459 // Ignore drag window for it should just track one pointer.
2460 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2461 continue;
2462 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002463 touchedWindow.pointerIds.set(entry.pointerProperties[pointerIndex].id);
Arthur Hung96483742022-11-15 03:30:48 +00002464 }
2465 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466 }
2467
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002468 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002469 {
2470 std::vector<TouchedWindow> hoveringWindows =
2471 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2472 for (const TouchedWindow& touchedWindow : hoveringWindows) {
2473 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2474 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2475 targets);
2476 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002477 }
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002478 // Ensure that we have at least one foreground window or at least one window that cannot be a
2479 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2480 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2481 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002482 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2483 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002484 return !canReceiveForegroundTouches(
2485 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002486 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002487 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002488 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2489 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002490 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002491 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002492 }
2493
Prabir Pradhan5735a322022-04-11 17:23:34 +00002494 // Ensure that all touched windows are valid for injection.
2495 if (entry.injectionState != nullptr) {
2496 std::string errs;
2497 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002498 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002499 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2500 // dispatched to any uid, since the coords will be zeroed out later.
2501 continue;
2502 }
2503 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2504 if (err) errs += "\n - " + *err;
2505 }
2506 if (!errs.empty()) {
2507 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2508 "%d:%s",
2509 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002510 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002511 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002512 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002513 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002514
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002515 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2516 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002517 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002518 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002519 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002520 if (foregroundWindowHandle) {
2521 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002522 for (InputTarget& target : targets) {
2523 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2524 sp<WindowInfoHandle> targetWindow =
2525 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2526 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2527 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002528 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002529 }
2530 }
2531 }
2532 }
2533
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002534 // Success! Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002535 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002536 if (touchedWindow.pointerIds.none() && !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002537 // Windows with hovering pointers are getting persisted inside TouchState.
2538 // Do not send this event to those windows.
2539 continue;
2540 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002541 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2542 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2543 targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002544 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002545
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002546 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002547 // Drop the outside or hover touch windows since we will not care about them
2548 // in the next iteration.
2549 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002550
Michael Wrightd02c5b62014-02-10 15:10:22 -08002551 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002552 if (switchedDevice) {
2553 if (DEBUG_FOCUS) {
2554 ALOGD("Conflicting pointer actions: Switched to a different device.");
2555 }
2556 *outConflictingPointerActions = true;
2557 }
2558
2559 if (isHoverAction) {
2560 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002561 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002562 ALOGD_IF(DEBUG_FOCUS,
2563 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002564 *outConflictingPointerActions = true;
2565 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002566 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2567 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2568 tempTouchState.deviceId = entry.deviceId;
2569 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002570 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002571 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2572 // Pointer went up.
2573 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002574 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002575 // All pointers up or canceled.
2576 tempTouchState.reset();
2577 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2578 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002579 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2580 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002581 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002582 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002583 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2584 // One pointer went up.
2585 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2586 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002588 for (size_t i = 0; i < tempTouchState.windows.size();) {
2589 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002590 touchedWindow.pointerIds.reset(pointerId);
2591 if (touchedWindow.pointerIds.none()) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002592 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2593 continue;
2594 }
2595 i += 1;
2596 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597 }
2598
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002599 // Save changes unless the action was scroll in which case the temporary touch
2600 // state was only valid for this one action.
2601 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002602 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002603 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002604 mTouchStatesByDisplay[displayId] = tempTouchState;
2605 } else {
2606 mTouchStatesByDisplay.erase(displayId);
2607 }
2608 }
2609
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002610 if (tempTouchState.windows.empty()) {
2611 mTouchStatesByDisplay.erase(displayId);
2612 }
2613
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002614 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002615}
2616
arthurhung6d4bed92021-03-17 11:59:33 +08002617void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002618 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2619 // have an explicit reason to support it.
2620 constexpr bool isStylus = false;
2621
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002622 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002623 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002624 if (dropWindow) {
2625 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002626 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002627 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002628 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002629 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002630 }
2631 mDragState.reset();
2632}
2633
2634void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002635 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002636 return;
2637 }
2638
arthurhung6d4bed92021-03-17 11:59:33 +08002639 if (!mDragState->isStartDrag) {
2640 mDragState->isStartDrag = true;
2641 mDragState->isStylusButtonDownAtStart =
2642 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2643 }
2644
Arthur Hung54745652022-04-20 07:17:41 +00002645 // Find the pointer index by id.
2646 int32_t pointerIndex = 0;
2647 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2648 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2649 if (pointerProperties.id == mDragState->pointerId) {
2650 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002651 }
Arthur Hung54745652022-04-20 07:17:41 +00002652 }
arthurhung6d4bed92021-03-17 11:59:33 +08002653
Arthur Hung54745652022-04-20 07:17:41 +00002654 if (uint32_t(pointerIndex) == entry.pointerCount) {
2655 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002656 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002657 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002658 return;
2659 }
2660
2661 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2662 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2663 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2664
2665 switch (maskedAction) {
2666 case AMOTION_EVENT_ACTION_MOVE: {
2667 // Handle the special case : stylus button no longer pressed.
2668 bool isStylusButtonDown =
2669 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2670 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2671 finishDragAndDrop(entry.displayId, x, y);
2672 return;
2673 }
2674
2675 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2676 // until we have an explicit reason to support it.
2677 constexpr bool isStylus = false;
2678
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002679 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002680 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002681 // enqueue drag exit if needed.
2682 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2683 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2684 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002685 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002686 y);
2687 }
2688 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2689 }
2690 // enqueue drag location if needed.
2691 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002692 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002693 }
2694 break;
2695 }
2696
2697 case AMOTION_EVENT_ACTION_POINTER_UP:
2698 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2699 break;
2700 }
2701 // The drag pointer is up.
2702 [[fallthrough]];
2703 case AMOTION_EVENT_ACTION_UP:
2704 finishDragAndDrop(entry.displayId, x, y);
2705 break;
2706 case AMOTION_EVENT_ACTION_CANCEL: {
2707 ALOGD("Receiving cancel when drag and drop.");
2708 sendDropWindowCommandLocked(nullptr, 0, 0);
2709 mDragState.reset();
2710 break;
2711 }
arthurhungb89ccb02020-12-30 16:19:01 +08002712 }
2713}
2714
chaviw98318de2021-05-19 16:45:23 -05002715void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002716 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002717 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002718 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002719 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002720 std::vector<InputTarget>::iterator it =
2721 std::find_if(inputTargets.begin(), inputTargets.end(),
2722 [&windowHandle](const InputTarget& inputTarget) {
2723 return inputTarget.inputChannel->getConnectionToken() ==
2724 windowHandle->getToken();
2725 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002726
chaviw98318de2021-05-19 16:45:23 -05002727 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002728
2729 if (it == inputTargets.end()) {
2730 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002731 std::shared_ptr<InputChannel> inputChannel =
2732 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002733 if (inputChannel == nullptr) {
2734 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2735 return;
2736 }
2737 inputTarget.inputChannel = inputChannel;
2738 inputTarget.flags = targetFlags;
2739 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002740 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002741 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2742 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002743 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002744 } else {
Siarhei Vishniakoua06bb552023-02-07 09:38:56 -08002745 // DisplayInfo not found for this window on display windowInfo->displayId.
2746 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002747 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002748 inputTargets.push_back(inputTarget);
2749 it = inputTargets.end() - 1;
2750 }
2751
2752 ALOG_ASSERT(it->flags == targetFlags);
2753 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2754
chaviw1ff3d1e2020-07-01 15:53:47 -07002755 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002756}
2757
Michael Wright3dd60e22019-03-27 22:06:44 +00002758void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002759 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002760 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2761 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002762
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002763 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2764 InputTarget target;
2765 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002766 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002767 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2768 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002769 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2770 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002771 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002772 target.setDefaultPointerTransform(target.displayTransform);
2773 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774 }
2775}
2776
Robert Carrc9bf1d32020-04-13 17:21:08 -07002777/**
2778 * Indicate whether one window handle should be considered as obscuring
2779 * another window handle. We only check a few preconditions. Actually
2780 * checking the bounds is left to the caller.
2781 */
chaviw98318de2021-05-19 16:45:23 -05002782static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2783 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002784 // Compare by token so cloned layers aren't counted
2785 if (haveSameToken(windowHandle, otherHandle)) {
2786 return false;
2787 }
2788 auto info = windowHandle->getInfo();
2789 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002790 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002791 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002792 } else if (otherInfo->alpha == 0 &&
2793 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002794 // Those act as if they were invisible, so we don't need to flag them.
2795 // We do want to potentially flag touchable windows even if they have 0
2796 // opacity, since they can consume touches and alter the effects of the
2797 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002798 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002799 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2800 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002801 } else if (info->ownerUid == otherInfo->ownerUid) {
2802 // If ownerUid is the same we don't generate occlusion events as there
2803 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002804 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002805 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002806 return false;
2807 } else if (otherInfo->displayId != info->displayId) {
2808 return false;
2809 }
2810 return true;
2811}
2812
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002813/**
2814 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2815 * untrusted, one should check:
2816 *
2817 * 1. If result.hasBlockingOcclusion is true.
2818 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2819 * BLOCK_UNTRUSTED.
2820 *
2821 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2822 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2823 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2824 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2825 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2826 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2827 *
2828 * If neither of those is true, then it means the touch can be allowed.
2829 */
2830InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002831 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2832 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002833 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002834 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002835 TouchOcclusionInfo info;
2836 info.hasBlockingOcclusion = false;
2837 info.obscuringOpacity = 0;
2838 info.obscuringUid = -1;
2839 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002840 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002841 if (windowHandle == otherHandle) {
2842 break; // All future windows are below us. Exit early.
2843 }
chaviw98318de2021-05-19 16:45:23 -05002844 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002845 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2846 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002847 if (DEBUG_TOUCH_OCCLUSION) {
2848 info.debugInfo.push_back(
2849 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2850 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002851 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2852 // we perform the checks below to see if the touch can be propagated or not based on the
2853 // window's touch occlusion mode
2854 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2855 info.hasBlockingOcclusion = true;
2856 info.obscuringUid = otherInfo->ownerUid;
2857 info.obscuringPackage = otherInfo->packageName;
2858 break;
2859 }
2860 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2861 uint32_t uid = otherInfo->ownerUid;
2862 float opacity =
2863 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2864 // Given windows A and B:
2865 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2866 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2867 opacityByUid[uid] = opacity;
2868 if (opacity > info.obscuringOpacity) {
2869 info.obscuringOpacity = opacity;
2870 info.obscuringUid = uid;
2871 info.obscuringPackage = otherInfo->packageName;
2872 }
2873 }
2874 }
2875 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002876 if (DEBUG_TOUCH_OCCLUSION) {
2877 info.debugInfo.push_back(
2878 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2879 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002880 return info;
2881}
2882
chaviw98318de2021-05-19 16:45:23 -05002883std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002884 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002885 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2886 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2887 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2888 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002889 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2890 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2891 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2892 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2893 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002894 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002895 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002896}
2897
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002898bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2899 if (occlusionInfo.hasBlockingOcclusion) {
2900 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2901 occlusionInfo.obscuringUid);
2902 return false;
2903 }
2904 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2905 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2906 "%.2f, maximum allowed = %.2f)",
2907 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2908 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2909 return false;
2910 }
2911 return true;
2912}
2913
chaviw98318de2021-05-19 16:45:23 -05002914bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002915 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002916 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002917 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2918 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002919 if (windowHandle == otherHandle) {
2920 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002921 }
chaviw98318de2021-05-19 16:45:23 -05002922 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002923 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002924 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925 return true;
2926 }
2927 }
2928 return false;
2929}
2930
chaviw98318de2021-05-19 16:45:23 -05002931bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002932 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002933 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2934 const WindowInfo* windowInfo = windowHandle->getInfo();
2935 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002936 if (windowHandle == otherHandle) {
2937 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002938 }
chaviw98318de2021-05-19 16:45:23 -05002939 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002940 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002941 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002942 return true;
2943 }
2944 }
2945 return false;
2946}
2947
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002948std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002949 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002950 if (applicationHandle != nullptr) {
2951 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002952 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002953 } else {
2954 return applicationHandle->getName();
2955 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002956 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002957 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002958 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002959 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002960 }
2961}
2962
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002963void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002964 if (!isUserActivityEvent(eventEntry)) {
2965 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002966 return;
2967 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002968 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002969 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002970 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002971 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002972 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002973 if (DEBUG_DISPATCH_CYCLE) {
2974 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2975 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002976 return;
2977 }
2978 }
2979
2980 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002981 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002982 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002983 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2984 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002985 return;
2986 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002987
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002988 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002989 eventType = USER_ACTIVITY_EVENT_TOUCH;
2990 }
2991 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002992 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002993 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002994 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2995 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002996 return;
2997 }
2998 eventType = USER_ACTIVITY_EVENT_BUTTON;
2999 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003000 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003001 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003002 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003003 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003004 break;
3005 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003006 }
3007
Prabir Pradhancef936d2021-07-21 16:17:52 +00003008 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3009 REQUIRES(mLock) {
3010 scoped_unlock unlock(mLock);
3011 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
3012 };
3013 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014}
3015
3016void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003017 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003018 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003019 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003020 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003021 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003022 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003023 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003024 ATRACE_NAME(message.c_str());
3025 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003026 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003027 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003028 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003029 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003030 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003031 inputTarget.getPointerInfoString().c_str());
3032 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033
3034 // Skip this event if the connection status is not normal.
3035 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003036 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003037 if (DEBUG_DISPATCH_CYCLE) {
3038 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003039 connection->getInputChannelName().c_str(),
3040 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003041 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042 return;
3043 }
3044
3045 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003046 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003047 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003048 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003049 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003050
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003051 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003052 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003053 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3054 logDispatchStateLocked();
3055 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3056 "target on connection "
3057 << connection->getInputChannelName() << " for "
3058 << originalMotionEntry.getDescription();
3059 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003060 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003061 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3062 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003063 if (!splitMotionEntry) {
3064 return; // split event was dropped
3065 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003066 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3067 std::string reason = std::string("reason=pointer cancel on split window");
3068 android_log_event_list(LOGTAG_INPUT_CANCEL)
3069 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3070 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003071 if (DEBUG_FOCUS) {
3072 ALOGD("channel '%s' ~ Split motion event.",
3073 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003074 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003075 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003076 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3077 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078 return;
3079 }
3080 }
3081
3082 // Not splitting. Enqueue dispatch entries for the event as is.
3083 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3084}
3085
3086void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003087 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003088 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003089 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003090 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003091 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003092 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003093 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003094 ATRACE_NAME(message.c_str());
3095 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003096 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3097 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003098
hongzuo liu95785e22022-09-06 02:51:35 +00003099 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100
3101 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003102 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003103 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003104 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003105 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003106 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003107 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003108 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003109 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003110 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003111 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003112 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003113 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003114
3115 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003116 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117 startDispatchCycleLocked(currentTime, connection);
3118 }
3119}
3120
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003121void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003122 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003123 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003124 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003125 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003126 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3127 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003128 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003129 ATRACE_NAME(message.c_str());
3130 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003131 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3132 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003133 return;
3134 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003135
3136 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3137 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138
3139 // This is a new event.
3140 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003141 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003142 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003143
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003144 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3145 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003146 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003148 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003149 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003150 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003151 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003152 dispatchEntry->resolvedAction = keyEntry.action;
3153 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003155 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3156 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003157 if (DEBUG_DISPATCH_CYCLE) {
3158 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3159 "event",
3160 connection->getInputChannelName().c_str());
3161 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003162 return; // skip the inconsistent event
3163 }
3164 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003167 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003168 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003169 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3170 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3171 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3172 static_cast<int32_t>(IdGenerator::Source::OTHER);
3173 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003174 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003175 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003176 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003177 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003178 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003179 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003180 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003181 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003182 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003183 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3184 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003185 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003186 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003187 }
3188 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003189 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3190 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003191 if (DEBUG_DISPATCH_CYCLE) {
3192 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3193 "enter event",
3194 connection->getInputChannelName().c_str());
3195 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003196 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3197 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003198 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3199 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003200
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003201 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003202 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3203 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3204 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003205 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003206 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3207 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003208 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003209 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3210 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003211
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003212 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3213 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003214 if (DEBUG_DISPATCH_CYCLE) {
3215 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3216 "event",
3217 connection->getInputChannelName().c_str());
3218 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003219 return; // skip the inconsistent event
3220 }
3221
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003222 dispatchEntry->resolvedEventId =
3223 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3224 ? mIdGenerator.nextId()
3225 : motionEntry.id;
3226 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3227 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3228 ") to MotionEvent(id=0x%" PRIx32 ").",
3229 motionEntry.id, dispatchEntry->resolvedEventId);
3230 ATRACE_NAME(message.c_str());
3231 }
3232
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003233 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3234 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3235 // Skip reporting pointer down outside focus to the policy.
3236 break;
3237 }
3238
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003239 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003240 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003241
3242 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003244 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003245 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003246 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3247 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003248 break;
3249 }
Chris Yef59a2f42020-10-16 12:55:26 -07003250 case EventEntry::Type::SENSOR: {
3251 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3252 break;
3253 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003254 case EventEntry::Type::CONFIGURATION_CHANGED:
3255 case EventEntry::Type::DEVICE_RESET: {
3256 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003257 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003258 break;
3259 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003260 }
3261
3262 // Remember that we are waiting for this dispatch to complete.
3263 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003264 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265 }
3266
3267 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003268 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003269 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003270}
3271
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003272/**
3273 * This function is purely for debugging. It helps us understand where the user interaction
3274 * was taking place. For example, if user is touching launcher, we will see a log that user
3275 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3276 * We will see both launcher and wallpaper in that list.
3277 * Once the interaction with a particular set of connections starts, no new logs will be printed
3278 * until the set of interacted connections changes.
3279 *
3280 * The following items are skipped, to reduce the logspam:
3281 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3282 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3283 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3284 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3285 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003286 */
3287void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3288 const std::vector<InputTarget>& targets) {
3289 // Skip ACTION_UP events, and all events other than keys and motions
3290 if (entry.type == EventEntry::Type::KEY) {
3291 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3292 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3293 return;
3294 }
3295 } else if (entry.type == EventEntry::Type::MOTION) {
3296 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3297 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3298 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3299 return;
3300 }
3301 } else {
3302 return; // Not a key or a motion
3303 }
3304
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003305 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003306 std::vector<sp<Connection>> newConnections;
3307 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003308 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003309 continue; // Skip windows that receive ACTION_OUTSIDE
3310 }
3311
3312 sp<IBinder> token = target.inputChannel->getConnectionToken();
3313 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003314 if (connection == nullptr) {
3315 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003316 }
3317 newConnectionTokens.insert(std::move(token));
3318 newConnections.emplace_back(connection);
3319 }
3320 if (newConnectionTokens == mInteractionConnectionTokens) {
3321 return; // no change
3322 }
3323 mInteractionConnectionTokens = newConnectionTokens;
3324
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003325 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003326 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003327 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003328 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003329 std::string message = "Interaction with: " + targetList;
3330 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003331 message += "<none>";
3332 }
3333 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3334}
3335
chaviwfd6d3512019-03-25 13:23:49 -07003336void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003337 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003338 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003339 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3340 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003341 return;
3342 }
3343
Vishnu Nairc519ff72021-01-21 08:23:08 -08003344 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003345 if (focusedToken == token) {
3346 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003347 return;
3348 }
3349
Prabir Pradhancef936d2021-07-21 16:17:52 +00003350 auto command = [this, token]() REQUIRES(mLock) {
3351 scoped_unlock unlock(mLock);
3352 mPolicy->onPointerDownOutsideFocus(token);
3353 };
3354 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355}
3356
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003357status_t InputDispatcher::publishMotionEvent(Connection& connection,
3358 DispatchEntry& dispatchEntry) const {
3359 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3360 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3361
3362 PointerCoords scaledCoords[MAX_POINTERS];
3363 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3364
3365 // Set the X and Y offset and X and Y scale depending on the input source.
3366 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003367 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003368 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3369 if (globalScaleFactor != 1.0f) {
3370 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3371 scaledCoords[i] = motionEntry.pointerCoords[i];
3372 // Don't apply window scale here since we don't want scale to affect raw
3373 // coordinates. The scale will be sent back to the client and applied
3374 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003375 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003376 }
3377 usingCoords = scaledCoords;
3378 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003379 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003380 // We don't want the dispatch target to know the coordinates
3381 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3382 scaledCoords[i].clear();
3383 }
3384 usingCoords = scaledCoords;
3385 }
3386
3387 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3388
3389 // Publish the motion event.
3390 return connection.inputPublisher
3391 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3392 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3393 std::move(hmac), dispatchEntry.resolvedAction,
3394 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3395 motionEntry.edgeFlags, motionEntry.metaState,
3396 motionEntry.buttonState, motionEntry.classification,
3397 dispatchEntry.transform, motionEntry.xPrecision,
3398 motionEntry.yPrecision, motionEntry.xCursorPosition,
3399 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3400 motionEntry.downTime, motionEntry.eventTime,
3401 motionEntry.pointerCount, motionEntry.pointerProperties,
3402 usingCoords);
3403}
3404
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003406 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003407 if (ATRACE_ENABLED()) {
3408 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003409 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003410 ATRACE_NAME(message.c_str());
3411 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003412 if (DEBUG_DISPATCH_CYCLE) {
3413 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3414 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003415
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003416 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003417 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003419 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003420 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421
3422 // Publish the event.
3423 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003424 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3425 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003426 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003427 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3428 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003429 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3430 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3431 << connection->getInputChannelName();
3432 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003434 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003435 status = connection->inputPublisher
3436 .publishKeyEvent(dispatchEntry->seq,
3437 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3438 keyEntry.source, keyEntry.displayId,
3439 std::move(hmac), dispatchEntry->resolvedAction,
3440 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3441 keyEntry.scanCode, keyEntry.metaState,
3442 keyEntry.repeatCount, keyEntry.downTime,
3443 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003444 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003445 }
3446
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003447 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003448 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3449 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3450 << connection->getInputChannelName();
3451 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003452 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003453 break;
3454 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003455
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003456 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003457 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003458 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003459 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003460 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003461 break;
3462 }
3463
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003464 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3465 const TouchModeEntry& touchModeEntry =
3466 static_cast<const TouchModeEntry&>(eventEntry);
3467 status = connection->inputPublisher
3468 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3469 touchModeEntry.inTouchMode);
3470
3471 break;
3472 }
3473
Prabir Pradhan99987712020-11-10 18:43:05 -08003474 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3475 const auto& captureEntry =
3476 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3477 status = connection->inputPublisher
3478 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003479 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003480 break;
3481 }
3482
arthurhungb89ccb02020-12-30 16:19:01 +08003483 case EventEntry::Type::DRAG: {
3484 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3485 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3486 dragEntry.id, dragEntry.x,
3487 dragEntry.y,
3488 dragEntry.isExiting);
3489 break;
3490 }
3491
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003492 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003493 case EventEntry::Type::DEVICE_RESET:
3494 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003495 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003496 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003497 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003498 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499 }
3500
3501 // Check the result.
3502 if (status) {
3503 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003504 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003506 "This is unexpected because the wait queue is empty, so the pipe "
3507 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003508 "event to it, status=%s(%d)",
3509 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3510 status);
Harry Cutts33476232023-01-30 19:57:29 +00003511 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512 } else {
3513 // Pipe is full and we are waiting for the app to finish process some events
3514 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003515 if (DEBUG_DISPATCH_CYCLE) {
3516 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3517 "waiting for the application to catch up",
3518 connection->getInputChannelName().c_str());
3519 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520 }
3521 } else {
3522 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003523 "status=%s(%d)",
3524 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3525 status);
Harry Cutts33476232023-01-30 19:57:29 +00003526 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 }
3528 return;
3529 }
3530
3531 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003532 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3533 connection->outboundQueue.end(),
3534 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003535 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003536 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003537 if (connection->responsive) {
3538 mAnrTracker.insert(dispatchEntry->timeoutTime,
3539 connection->inputChannel->getConnectionToken());
3540 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003541 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542 }
3543}
3544
chaviw09c8d2d2020-08-24 15:48:26 -07003545std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3546 size_t size;
3547 switch (event.type) {
3548 case VerifiedInputEvent::Type::KEY: {
3549 size = sizeof(VerifiedKeyEvent);
3550 break;
3551 }
3552 case VerifiedInputEvent::Type::MOTION: {
3553 size = sizeof(VerifiedMotionEvent);
3554 break;
3555 }
3556 }
3557 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3558 return mHmacKeyManager.sign(start, size);
3559}
3560
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003561const std::array<uint8_t, 32> InputDispatcher::getSignature(
3562 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003563 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3564 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003565 // Only sign events up and down events as the purely move events
3566 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003567 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003568 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003569
3570 VerifiedMotionEvent verifiedEvent =
3571 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3572 verifiedEvent.actionMasked = actionMasked;
3573 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3574 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003575}
3576
3577const std::array<uint8_t, 32> InputDispatcher::getSignature(
3578 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3579 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3580 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3581 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003582 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003583}
3584
Michael Wrightd02c5b62014-02-10 15:10:22 -08003585void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003586 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003587 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003588 if (DEBUG_DISPATCH_CYCLE) {
3589 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3590 connection->getInputChannelName().c_str(), seq, toString(handled));
3591 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003593 if (connection->status == Connection::Status::BROKEN ||
3594 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595 return;
3596 }
3597
3598 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003599 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3600 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3601 };
3602 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603}
3604
3605void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003606 const sp<Connection>& connection,
3607 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003608 if (DEBUG_DISPATCH_CYCLE) {
3609 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3610 connection->getInputChannelName().c_str(), toString(notify));
3611 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612
3613 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003614 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003615 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003616 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003617 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618
3619 // The connection appears to be unrecoverably broken.
3620 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003621 if (connection->status == Connection::Status::NORMAL) {
3622 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623
3624 if (notify) {
3625 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003626 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3627 connection->getInputChannelName().c_str());
3628
3629 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003630 scoped_unlock unlock(mLock);
3631 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3632 };
3633 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634 }
3635 }
3636}
3637
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003638void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3639 while (!queue.empty()) {
3640 DispatchEntry* dispatchEntry = queue.front();
3641 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003642 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643 }
3644}
3645
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003646void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003647 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003648 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649 }
3650 delete dispatchEntry;
3651}
3652
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003653int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3654 std::scoped_lock _l(mLock);
3655 sp<Connection> connection = getConnectionLocked(connectionToken);
3656 if (connection == nullptr) {
3657 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3658 connectionToken.get(), events);
3659 return 0; // remove the callback
3660 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003662 bool notify;
3663 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3664 if (!(events & ALOOPER_EVENT_INPUT)) {
3665 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3666 "events=0x%x",
3667 connection->getInputChannelName().c_str(), events);
3668 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003669 }
3670
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003671 nsecs_t currentTime = now();
3672 bool gotOne = false;
3673 status_t status = OK;
3674 for (;;) {
3675 Result<InputPublisher::ConsumerResponse> result =
3676 connection->inputPublisher.receiveConsumerResponse();
3677 if (!result.ok()) {
3678 status = result.error().code();
3679 break;
3680 }
3681
3682 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3683 const InputPublisher::Finished& finish =
3684 std::get<InputPublisher::Finished>(*result);
3685 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3686 finish.consumeTime);
3687 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003688 if (shouldReportMetricsForConnection(*connection)) {
3689 const InputPublisher::Timeline& timeline =
3690 std::get<InputPublisher::Timeline>(*result);
3691 mLatencyTracker
3692 .trackGraphicsLatency(timeline.inputEventId,
3693 connection->inputChannel->getConnectionToken(),
3694 std::move(timeline.graphicsTimeline));
3695 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003696 }
3697 gotOne = true;
3698 }
3699 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003700 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003701 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702 return 1;
3703 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704 }
3705
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003706 notify = status != DEAD_OBJECT || !connection->monitor;
3707 if (notify) {
3708 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3709 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3710 status);
3711 }
3712 } else {
3713 // Monitor channels are never explicitly unregistered.
3714 // We do it automatically when the remote endpoint is closed so don't warn about them.
3715 const bool stillHaveWindowHandle =
3716 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3717 notify = !connection->monitor && stillHaveWindowHandle;
3718 if (notify) {
3719 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3720 connection->getInputChannelName().c_str(), events);
3721 }
3722 }
3723
3724 // Remove the channel.
3725 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3726 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727}
3728
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003729void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003731 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003732 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733 }
3734}
3735
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003736void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003737 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003738 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003739 for (const Monitor& monitor : monitors) {
3740 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003741 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003742 }
3743}
3744
Michael Wrightd02c5b62014-02-10 15:10:22 -08003745void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003746 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003747 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003748 if (connection == nullptr) {
3749 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003750 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003751
3752 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753}
3754
3755void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3756 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003757 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758 return;
3759 }
3760
3761 nsecs_t currentTime = now();
3762
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003763 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003764 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003766 if (cancelationEvents.empty()) {
3767 return;
3768 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003769 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3770 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003771 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003772 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003773 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003774 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003775
Arthur Hungb3307ee2021-10-14 10:57:37 +00003776 std::string reason = std::string("reason=").append(options.reason);
3777 android_log_event_list(LOGTAG_INPUT_CANCEL)
3778 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3779
Svet Ganov5d3bc372020-01-26 23:11:07 -08003780 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003781 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003782 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3783 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003784 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003785 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003786 target.globalScaleFactor = windowInfo->globalScaleFactor;
3787 }
3788 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003789 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003790
hongzuo liu95785e22022-09-06 02:51:35 +00003791 const bool wasEmpty = connection->outboundQueue.empty();
3792
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003793 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003794 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003795 switch (cancelationEventEntry->type) {
3796 case EventEntry::Type::KEY: {
3797 logOutboundKeyDetails("cancel - ",
3798 static_cast<const KeyEntry&>(*cancelationEventEntry));
3799 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003801 case EventEntry::Type::MOTION: {
3802 logOutboundMotionDetails("cancel - ",
3803 static_cast<const MotionEntry&>(*cancelationEventEntry));
3804 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003806 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003807 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003808 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3809 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003810 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003811 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003812 break;
3813 }
3814 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003815 case EventEntry::Type::DEVICE_RESET:
3816 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003817 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003818 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003819 break;
3820 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003821 }
3822
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003823 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003824 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003825 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003826
hongzuo liu95785e22022-09-06 02:51:35 +00003827 // If the outbound queue was previously empty, start the dispatch cycle going.
3828 if (wasEmpty && !connection->outboundQueue.empty()) {
3829 startDispatchCycleLocked(currentTime, connection);
3830 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831}
3832
Svet Ganov5d3bc372020-01-26 23:11:07 -08003833void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Arthur Hungc539dbb2022-12-08 07:45:36 +00003834 const nsecs_t downTime, const sp<Connection>& connection,
3835 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003836 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003837 return;
3838 }
3839
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003840 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003841 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003842
3843 if (downEvents.empty()) {
3844 return;
3845 }
3846
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003847 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003848 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3849 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003850 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003851
3852 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003853 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003854 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3855 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003856 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003857 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003858 target.globalScaleFactor = windowInfo->globalScaleFactor;
3859 }
3860 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00003861 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003862
hongzuo liu95785e22022-09-06 02:51:35 +00003863 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003864 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003865 switch (downEventEntry->type) {
3866 case EventEntry::Type::MOTION: {
3867 logOutboundMotionDetails("down - ",
3868 static_cast<const MotionEntry&>(*downEventEntry));
3869 break;
3870 }
3871
3872 case EventEntry::Type::KEY:
3873 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003874 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003875 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003876 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003877 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003878 case EventEntry::Type::SENSOR:
3879 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003880 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003881 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003882 break;
3883 }
3884 }
3885
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003886 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003887 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003888 }
3889
hongzuo liu95785e22022-09-06 02:51:35 +00003890 // If the outbound queue was previously empty, start the dispatch cycle going.
3891 if (wasEmpty && !connection->outboundQueue.empty()) {
3892 startDispatchCycleLocked(downTime, connection);
3893 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003894}
3895
Arthur Hungc539dbb2022-12-08 07:45:36 +00003896void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
3897 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
3898 if (windowHandle != nullptr) {
3899 sp<Connection> wallpaperConnection = getConnectionLocked(windowHandle->getToken());
3900 if (wallpaperConnection != nullptr) {
3901 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
3902 }
3903 }
3904}
3905
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003906std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003907 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
3908 nsecs_t splitDownTime) {
3909 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910
3911 uint32_t splitPointerIndexMap[MAX_POINTERS];
3912 PointerProperties splitPointerProperties[MAX_POINTERS];
3913 PointerCoords splitPointerCoords[MAX_POINTERS];
3914
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003915 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003916 uint32_t splitPointerCount = 0;
3917
3918 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003919 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003921 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003923 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3925 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3926 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003927 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928 splitPointerCount += 1;
3929 }
3930 }
3931
3932 if (splitPointerCount != pointerIds.count()) {
3933 // This is bad. We are missing some of the pointers that we expected to deliver.
3934 // Most likely this indicates that we received an ACTION_MOVE events that has
3935 // different pointer ids than we expected based on the previous ACTION_DOWN
3936 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3937 // in this way.
3938 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003939 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003940 "a broken sequence of pointer ids from the input device: %s",
3941 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07003942 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943 }
3944
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003945 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003946 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003947 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3948 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3950 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003951 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003953 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954 if (pointerIds.count() == 1) {
3955 // The first/last pointer went down/up.
3956 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003957 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003958 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3959 ? AMOTION_EVENT_ACTION_CANCEL
3960 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961 } else {
3962 // A secondary pointer went down/up.
3963 uint32_t splitPointerIndex = 0;
3964 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3965 splitPointerIndex += 1;
3966 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003967 action = maskedAction |
3968 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 }
3970 } else {
3971 // An unrelated pointer changed.
3972 action = AMOTION_EVENT_ACTION_MOVE;
3973 }
3974 }
3975
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003976 if (action == AMOTION_EVENT_ACTION_DOWN) {
3977 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3978 "Split motion event has mismatching downTime and eventTime for "
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08003979 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
3980 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003981 }
3982
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003983 int32_t newId = mIdGenerator.nextId();
3984 if (ATRACE_ENABLED()) {
3985 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3986 ") to MotionEvent(id=0x%" PRIx32 ").",
3987 originalMotionEntry.id, newId);
3988 ATRACE_NAME(message.c_str());
3989 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003990 std::unique_ptr<MotionEntry> splitMotionEntry =
3991 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3992 originalMotionEntry.deviceId, originalMotionEntry.source,
3993 originalMotionEntry.displayId,
3994 originalMotionEntry.policyFlags, action,
3995 originalMotionEntry.actionButton,
3996 originalMotionEntry.flags, originalMotionEntry.metaState,
3997 originalMotionEntry.buttonState,
3998 originalMotionEntry.classification,
3999 originalMotionEntry.edgeFlags,
4000 originalMotionEntry.xPrecision,
4001 originalMotionEntry.yPrecision,
4002 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004003 originalMotionEntry.yCursorPosition, splitDownTime,
4004 splitPointerCount, splitPointerProperties,
4005 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004006
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004007 if (originalMotionEntry.injectionState) {
4008 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009 splitMotionEntry->injectionState->refCount += 1;
4010 }
4011
4012 return splitMotionEntry;
4013}
4014
4015void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004016 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004017 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
4018 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019
Antonio Kantekf16f2832021-09-28 04:39:20 +00004020 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004022 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004023
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004024 std::unique_ptr<ConfigurationChangedEntry> newEntry =
4025 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
4026 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004027 } // release lock
4028
4029 if (needWake) {
4030 mLooper->wake();
4031 }
4032}
4033
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004034/**
4035 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004036 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4037 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4038 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4039 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4040 * potentially handle the back key presses.
4041 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4042 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004043 */
4044void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004045 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004046 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4047 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004048 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004049 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004050 }
4051 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004052 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004053 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004054 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004055 keyCode = newKeyCode;
4056 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4057 }
4058 } else if (action == AKEY_EVENT_ACTION_UP) {
4059 // In order to maintain a consistent stream of up and down events, check to see if the key
4060 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4061 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004062 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004063 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004064 auto replacementIt = mReplacedKeys.find(replacement);
4065 if (replacementIt != mReplacedKeys.end()) {
4066 keyCode = replacementIt->second;
4067 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004068 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4069 }
4070 }
4071}
4072
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004074 ALOGD_IF(debugInboundEventDetails(),
4075 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4076 ", deviceId=%d, source=%s, displayId=%" PRId32
4077 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4078 "downTime=%" PRId64,
4079 args->id, args->eventTime, args->deviceId,
4080 inputEventSourceToString(args->source).c_str(), args->displayId, args->policyFlags,
4081 KeyEvent::actionToString(args->action), args->flags, KeyEvent::getLabel(args->keyCode),
4082 args->scanCode, args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083 if (!validateKeyEvent(args->action)) {
4084 return;
4085 }
4086
4087 uint32_t policyFlags = args->policyFlags;
4088 int32_t flags = args->flags;
4089 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004090 // InputDispatcher tracks and generates key repeats on behalf of
4091 // whatever notifies it, so repeatCount should always be set to 0
4092 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004093 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4094 policyFlags |= POLICY_FLAG_VIRTUAL;
4095 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4096 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 if (policyFlags & POLICY_FLAG_FUNCTION) {
4098 metaState |= AMETA_FUNCTION_ON;
4099 }
4100
4101 policyFlags |= POLICY_FLAG_TRUSTED;
4102
Michael Wright78f24442014-08-06 15:55:28 -07004103 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004104 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004105
Michael Wrightd02c5b62014-02-10 15:10:22 -08004106 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004107 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08004108 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
4109 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110
Michael Wright2b3c3302018-03-02 17:19:13 +00004111 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004112 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004113 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4114 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004115 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004116 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117
Antonio Kantekf16f2832021-09-28 04:39:20 +00004118 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119 { // acquire lock
4120 mLock.lock();
4121
4122 if (shouldSendKeyToInputFilterLocked(args)) {
4123 mLock.unlock();
4124
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004125 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4127 return; // event was consumed by the filter
4128 }
4129
4130 mLock.lock();
4131 }
4132
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004133 std::unique_ptr<KeyEntry> newEntry =
4134 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4135 args->displayId, policyFlags, args->action, flags,
4136 keyCode, args->scanCode, metaState, repeatCount,
4137 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004139 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 mLock.unlock();
4141 } // release lock
4142
4143 if (needWake) {
4144 mLooper->wake();
4145 }
4146}
4147
4148bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4149 return mInputFilterEnabled;
4150}
4151
4152void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004153 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004154 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004155 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004156 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004157 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4158 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhan96282b02023-02-24 22:36:17 +00004159 args->id, args->eventTime, args->deviceId,
4160 inputEventSourceToString(args->source).c_str(), args->displayId, args->policyFlags,
4161 MotionEvent::actionToString(args->action).c_str(), args->actionButton, args->flags,
4162 args->metaState, args->buttonState, args->edgeFlags, args->xPrecision,
4163 args->yPrecision, args->xCursorPosition, args->yCursorPosition, args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004164 for (uint32_t i = 0; i < args->pointerCount; i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004165 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4166 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
4167 i, args->pointerProperties[i].id,
4168 motionToolTypeToString(args->pointerProperties[i].toolType),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004169 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4170 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4171 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4172 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4173 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4174 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4175 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4176 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4177 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4178 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179 }
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004180
4181 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4182 args->pointerProperties)) {
4183 LOG(ERROR) << "Invalid event: " << args->dump();
4184 return;
4185 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186
4187 uint32_t policyFlags = args->policyFlags;
4188 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004189
4190 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004191 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004192 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4193 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004194 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004195 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196
Antonio Kantekf16f2832021-09-28 04:39:20 +00004197 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 { // acquire lock
4199 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004200 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4201 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4202 // complete the processing of the current stroke.
4203 const auto touchStateIt = mTouchStatesByDisplay.find(args->displayId);
4204 if (touchStateIt != mTouchStatesByDisplay.end()) {
4205 const TouchState& touchState = touchStateIt->second;
4206 if (touchState.deviceId == args->deviceId && touchState.isDown()) {
4207 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4208 }
4209 }
4210 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211
4212 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004213 ui::Transform displayTransform;
4214 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4215 displayTransform = it->second.transform;
4216 }
4217
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218 mLock.unlock();
4219
4220 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004221 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4222 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004223 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004224 displayTransform, args->xPrecision, args->yPrecision,
4225 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004226 args->downTime, args->eventTime, args->pointerCount,
4227 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228
4229 policyFlags |= POLICY_FLAG_FILTERED;
4230 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4231 return; // event was consumed by the filter
4232 }
4233
4234 mLock.lock();
4235 }
4236
4237 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004238 std::unique_ptr<MotionEntry> newEntry =
4239 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4240 args->source, args->displayId, policyFlags,
4241 args->action, args->actionButton, args->flags,
4242 args->metaState, args->buttonState,
4243 args->classification, args->edgeFlags,
4244 args->xPrecision, args->yPrecision,
4245 args->xCursorPosition, args->yCursorPosition,
4246 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004247 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004249 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4250 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4251 !mInputFilterEnabled) {
4252 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4253 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4254 }
4255
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004256 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257 mLock.unlock();
4258 } // release lock
4259
4260 if (needWake) {
4261 mLooper->wake();
4262 }
4263}
4264
Chris Yef59a2f42020-10-16 12:55:26 -07004265void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004266 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004267 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4268 " sensorType=%s",
4269 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004270 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004271 }
Chris Yef59a2f42020-10-16 12:55:26 -07004272
Antonio Kantekf16f2832021-09-28 04:39:20 +00004273 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004274 { // acquire lock
4275 mLock.lock();
4276
4277 // Just enqueue a new sensor event.
4278 std::unique_ptr<SensorEntry> newEntry =
4279 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
Harry Cutts33476232023-01-30 19:57:29 +00004280 args->source, /* policyFlags=*/0, args->hwTimestamp,
Chris Yef59a2f42020-10-16 12:55:26 -07004281 args->sensorType, args->accuracy,
4282 args->accuracyChanged, args->values);
4283
4284 needWake = enqueueInboundEventLocked(std::move(newEntry));
4285 mLock.unlock();
4286 } // release lock
4287
4288 if (needWake) {
4289 mLooper->wake();
4290 }
4291}
4292
Chris Yefb552902021-02-03 17:18:37 -08004293void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004294 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004295 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4296 args->deviceId, args->isOn);
4297 }
Chris Yefb552902021-02-03 17:18:37 -08004298 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4299}
4300
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004302 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303}
4304
4305void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004306 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004307 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4308 "switchMask=0x%08x",
4309 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4310 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311
4312 uint32_t policyFlags = args->policyFlags;
4313 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004314 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315}
4316
4317void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004318 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004319 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4320 args->deviceId);
4321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322
Antonio Kantekf16f2832021-09-28 04:39:20 +00004323 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004325 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004327 std::unique_ptr<DeviceResetEntry> newEntry =
4328 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4329 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330 } // release lock
4331
4332 if (needWake) {
4333 mLooper->wake();
4334 }
4335}
4336
Prabir Pradhan7e186182020-11-10 13:56:45 -08004337void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004338 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004339 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004340 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004341 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004342
Antonio Kantekf16f2832021-09-28 04:39:20 +00004343 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004344 { // acquire lock
4345 std::scoped_lock _l(mLock);
4346 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004347 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004348 needWake = enqueueInboundEventLocked(std::move(entry));
4349 } // release lock
4350
4351 if (needWake) {
4352 mLooper->wake();
4353 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004354}
4355
Prabir Pradhan5735a322022-04-11 17:23:34 +00004356InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4357 std::optional<int32_t> targetUid,
4358 InputEventInjectionSync syncMode,
4359 std::chrono::milliseconds timeout,
4360 uint32_t policyFlags) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004361 if (debugInboundEventDetails()) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004362 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4363 "policyFlags=0x%08x",
4364 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4365 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004366 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004367 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368
Prabir Pradhan5735a322022-04-11 17:23:34 +00004369 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004370
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004371 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004372 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4373 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4374 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4375 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4376 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004377 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004378 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004379 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004380 }
4381
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004382 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004384 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004385 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4386 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004387 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004388 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004390
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004391 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004392 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4393 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4394 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004395 int32_t keyCode = incomingKey.getKeyCode();
4396 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004397 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004398 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004399 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004400 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004401 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4402 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4403 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004405 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4406 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004407 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004408
4409 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4410 android::base::Timer t;
4411 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4412 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4413 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4414 std::to_string(t.duration().count()).c_str());
4415 }
4416 }
4417
4418 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004419 std::unique_ptr<KeyEntry> injectedEntry =
4420 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004421 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004422 incomingKey.getDisplayId(), policyFlags, action,
4423 flags, keyCode, incomingKey.getScanCode(), metaState,
4424 incomingKey.getRepeatCount(),
4425 incomingKey.getDownTime());
4426 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004427 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004428 }
4429
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004430 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004431 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004432 const int32_t action = motionEvent.getAction();
4433 const bool isPointerEvent =
4434 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4435 // If a pointer event has no displayId specified, inject it to the default display.
4436 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4437 ? ADISPLAY_ID_DEFAULT
4438 : event->getDisplayId();
4439 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004440 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004441 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004442 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004443 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004444 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004445 }
4446
4447 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004448 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004449 android::base::Timer t;
4450 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4451 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4452 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4453 std::to_string(t.duration().count()).c_str());
4454 }
4455 }
4456
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004457 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4458 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4459 }
4460
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004461 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004462 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4463 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004464 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004465 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4466 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004467 displayId, policyFlags, action, actionButton,
4468 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004469 motionEvent.getButtonState(),
4470 motionEvent.getClassification(),
4471 motionEvent.getEdgeFlags(),
4472 motionEvent.getXPrecision(),
4473 motionEvent.getYPrecision(),
4474 motionEvent.getRawXCursorPosition(),
4475 motionEvent.getRawYCursorPosition(),
4476 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004477 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004478 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004479 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004480 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004481 sampleEventTimes += 1;
4482 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004483 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004484 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4485 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004486 displayId, policyFlags, action, actionButton,
4487 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004488 motionEvent.getButtonState(),
4489 motionEvent.getClassification(),
4490 motionEvent.getEdgeFlags(),
4491 motionEvent.getXPrecision(),
4492 motionEvent.getYPrecision(),
4493 motionEvent.getRawXCursorPosition(),
4494 motionEvent.getRawYCursorPosition(),
4495 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004496 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004497 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004498 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4499 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004500 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004501 }
4502 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004505 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004506 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004507 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508 }
4509
Prabir Pradhan5735a322022-04-11 17:23:34 +00004510 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004511 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512 injectionState->injectionIsAsync = true;
4513 }
4514
4515 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004516 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004517
4518 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004519 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004520 if (DEBUG_INJECTION) {
4521 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4522 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004523 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004524 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525 }
4526
4527 mLock.unlock();
4528
4529 if (needWake) {
4530 mLooper->wake();
4531 }
4532
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004533 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004535 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004536
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004537 if (syncMode == InputEventInjectionSync::NONE) {
4538 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004539 } else {
4540 for (;;) {
4541 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004542 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543 break;
4544 }
4545
4546 nsecs_t remainingTimeout = endTime - now();
4547 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004548 if (DEBUG_INJECTION) {
4549 ALOGD("injectInputEvent - Timed out waiting for injection result "
4550 "to become available.");
4551 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004552 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553 break;
4554 }
4555
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004556 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557 }
4558
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004559 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4560 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004561 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004562 if (DEBUG_INJECTION) {
4563 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4564 injectionState->pendingForegroundDispatches);
4565 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004566 nsecs_t remainingTimeout = endTime - now();
4567 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004568 if (DEBUG_INJECTION) {
4569 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4570 "dispatches to finish.");
4571 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004572 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004573 break;
4574 }
4575
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004576 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004577 }
4578 }
4579 }
4580
4581 injectionState->release();
4582 } // release lock
4583
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004584 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004585 LOG(DEBUG) << "injectInputEvent - Finished with result "
4586 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004587 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588
4589 return injectionResult;
4590}
4591
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004592std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004593 std::array<uint8_t, 32> calculatedHmac;
4594 std::unique_ptr<VerifiedInputEvent> result;
4595 switch (event.getType()) {
4596 case AINPUT_EVENT_TYPE_KEY: {
4597 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4598 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4599 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004600 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004601 break;
4602 }
4603 case AINPUT_EVENT_TYPE_MOTION: {
4604 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4605 VerifiedMotionEvent verifiedMotionEvent =
4606 verifiedMotionEventFromMotionEvent(motionEvent);
4607 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004608 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004609 break;
4610 }
4611 default: {
4612 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4613 return nullptr;
4614 }
4615 }
4616 if (calculatedHmac == INVALID_HMAC) {
4617 return nullptr;
4618 }
4619 if (calculatedHmac != event.getHmac()) {
4620 return nullptr;
4621 }
4622 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004623}
4624
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004625void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004626 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004627 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004629 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004630 LOG(DEBUG) << "Setting input event injection result to "
4631 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004632 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004633
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004634 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004635 // Log the outcome since the injector did not wait for the injection result.
4636 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004637 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004638 ALOGV("Asynchronous input event injection succeeded.");
4639 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004640 case InputEventInjectionResult::TARGET_MISMATCH:
4641 ALOGV("Asynchronous input event injection target mismatch.");
4642 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004643 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004644 ALOGW("Asynchronous input event injection failed.");
4645 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004646 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004647 ALOGW("Asynchronous input event injection timed out.");
4648 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004649 case InputEventInjectionResult::PENDING:
4650 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4651 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004652 }
4653 }
4654
4655 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004656 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004657 }
4658}
4659
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004660void InputDispatcher::transformMotionEntryForInjectionLocked(
4661 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004662 // Input injection works in the logical display coordinate space, but the input pipeline works
4663 // display space, so we need to transform the injected events accordingly.
4664 const auto it = mDisplayInfos.find(entry.displayId);
4665 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004666 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004667
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004668 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4669 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4670 const vec2 cursor =
4671 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4672 {entry.xCursorPosition, entry.yCursorPosition});
4673 entry.xCursorPosition = cursor.x;
4674 entry.yCursorPosition = cursor.y;
4675 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004676 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004677 entry.pointerCoords[i] =
4678 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4679 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004680 }
4681}
4682
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004683void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4684 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004685 if (injectionState) {
4686 injectionState->pendingForegroundDispatches += 1;
4687 }
4688}
4689
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004690void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4691 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004692 if (injectionState) {
4693 injectionState->pendingForegroundDispatches -= 1;
4694
4695 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004696 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004697 }
4698 }
4699}
4700
chaviw98318de2021-05-19 16:45:23 -05004701const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004702 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004703 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004704 auto it = mWindowHandlesByDisplay.find(displayId);
4705 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004706}
4707
chaviw98318de2021-05-19 16:45:23 -05004708sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004709 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004710 if (windowHandleToken == nullptr) {
4711 return nullptr;
4712 }
4713
Arthur Hungb92218b2018-08-14 12:00:21 +08004714 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004715 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4716 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004717 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004718 return windowHandle;
4719 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720 }
4721 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004722 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723}
4724
chaviw98318de2021-05-19 16:45:23 -05004725sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4726 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004727 if (windowHandleToken == nullptr) {
4728 return nullptr;
4729 }
4730
chaviw98318de2021-05-19 16:45:23 -05004731 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004732 if (windowHandle->getToken() == windowHandleToken) {
4733 return windowHandle;
4734 }
4735 }
4736 return nullptr;
4737}
4738
chaviw98318de2021-05-19 16:45:23 -05004739sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4740 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004741 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004742 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4743 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004744 if (handle->getId() == windowHandle->getId() &&
4745 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004746 if (windowHandle->getInfo()->displayId != it.first) {
4747 ALOGE("Found window %s in display %" PRId32
4748 ", but it should belong to display %" PRId32,
4749 windowHandle->getName().c_str(), it.first,
4750 windowHandle->getInfo()->displayId);
4751 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004752 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004753 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004754 }
4755 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004756 return nullptr;
4757}
4758
chaviw98318de2021-05-19 16:45:23 -05004759sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004760 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4761 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004762}
4763
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004764bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4765 const MotionEntry& motionEntry) const {
4766 const WindowInfo& info = *window->getInfo();
4767
4768 // Skip spy window targets that are not valid for targeted injection.
4769 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004770 return false;
4771 }
4772
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004773 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4774 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4775 return false;
4776 }
4777
4778 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4779 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4780 window->getName().c_str());
4781 return false;
4782 }
4783
4784 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004785 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004786 ALOGW("Not sending touch to %s because there's no corresponding connection",
4787 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004788 return false;
4789 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004790
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004791 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004792 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004793 return false;
4794 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004795
4796 // Drop events that can't be trusted due to occlusion
4797 const auto [x, y] = resolveTouchedPosition(motionEntry);
4798 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4799 if (!isTouchTrustedLocked(occlusionInfo)) {
4800 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004801 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004802 for (const auto& log : occlusionInfo.debugInfo) {
4803 ALOGD("%s", log.c_str());
4804 }
4805 }
4806 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4807 occlusionInfo.obscuringUid);
4808 return false;
4809 }
4810
4811 // Drop touch events if requested by input feature
4812 if (shouldDropInput(motionEntry, window)) {
4813 return false;
4814 }
4815
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004816 return true;
4817}
4818
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004819std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4820 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004821 auto connectionIt = mConnectionsByToken.find(token);
4822 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004823 return nullptr;
4824 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004825 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004826}
4827
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004828void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004829 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4830 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004831 // Remove all handles on a display if there are no windows left.
4832 mWindowHandlesByDisplay.erase(displayId);
4833 return;
4834 }
4835
4836 // Since we compare the pointer of input window handles across window updates, we need
4837 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004838 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4839 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4840 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004841 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004842 }
4843
chaviw98318de2021-05-19 16:45:23 -05004844 std::vector<sp<WindowInfoHandle>> newHandles;
4845 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004846 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004847 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004848 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004849 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004850 const bool canReceiveInput =
4851 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4852 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004853 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004854 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004855 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004856 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004857 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004858 }
4859
4860 if (info->displayId != displayId) {
4861 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4862 handle->getName().c_str(), displayId, info->displayId);
4863 continue;
4864 }
4865
Robert Carredd13602020-04-13 17:24:34 -07004866 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4867 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004868 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004869 oldHandle->updateFrom(handle);
4870 newHandles.push_back(oldHandle);
4871 } else {
4872 newHandles.push_back(handle);
4873 }
4874 }
4875
4876 // Insert or replace
4877 mWindowHandlesByDisplay[displayId] = newHandles;
4878}
4879
Arthur Hung72d8dc32020-03-28 00:48:39 +00004880void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004881 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004882 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004883 { // acquire lock
4884 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004885 for (const auto& [displayId, handles] : handlesPerDisplay) {
4886 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004887 }
4888 }
4889 // Wake up poll loop since it may need to make new input dispatching choices.
4890 mLooper->wake();
4891}
4892
Arthur Hungb92218b2018-08-14 12:00:21 +08004893/**
4894 * Called from InputManagerService, update window handle list by displayId that can receive input.
4895 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4896 * If set an empty list, remove all handles from the specific display.
4897 * For focused handle, check if need to change and send a cancel event to previous one.
4898 * For removed handle, check if need to send a cancel event if already in touch.
4899 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004900void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004901 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004902 if (DEBUG_FOCUS) {
4903 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004904 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004905 windowList += iwh->getName() + " ";
4906 }
4907 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004909
Prabir Pradhand65552b2021-10-07 11:23:50 -07004910 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004911 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004912 const WindowInfo& info = *window->getInfo();
4913
4914 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004915 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004916 if (noInputWindow && window->getToken() != nullptr) {
4917 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4918 window->getName().c_str());
4919 window->releaseChannel();
4920 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004921
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004922 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004923 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4924 !info.inputConfig.test(
4925 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004926 "%s has feature SPY, but is not a trusted overlay.",
4927 window->getName().c_str());
4928
Prabir Pradhand65552b2021-10-07 11:23:50 -07004929 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004930 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4931 !info.inputConfig.test(
4932 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004933 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4934 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004935 }
4936
Arthur Hung72d8dc32020-03-28 00:48:39 +00004937 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004938 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004939
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004940 // Save the old windows' orientation by ID before it gets updated.
4941 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004942 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004943 oldWindowOrientations.emplace(handle->getId(),
4944 handle->getInfo()->transform.getOrientation());
4945 }
4946
chaviw98318de2021-05-19 16:45:23 -05004947 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004948
chaviw98318de2021-05-19 16:45:23 -05004949 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004950
Vishnu Nairc519ff72021-01-21 08:23:08 -08004951 std::optional<FocusResolver::FocusChanges> changes =
4952 mFocusResolver.setInputWindows(displayId, windowHandles);
4953 if (changes) {
4954 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004956
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004957 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4958 mTouchStatesByDisplay.find(displayId);
4959 if (stateIt != mTouchStatesByDisplay.end()) {
4960 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004961 for (size_t i = 0; i < state.windows.size();) {
4962 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004963 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004964 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004965 ALOGD("Touched window was removed: %s in display %" PRId32,
4966 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004967 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004968 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004969 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4970 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004971 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00004972 "touched window was removed");
4973 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004974 // Since we are about to drop the touch, cancel the events for the wallpaper as
4975 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004976 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004977 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4978 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004979 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004980 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004982 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004983 state.windows.erase(state.windows.begin() + i);
4984 } else {
4985 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004986 }
4987 }
arthurhungb89ccb02020-12-30 16:19:01 +08004988
arthurhung6d4bed92021-03-17 11:59:33 +08004989 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004990 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004991 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004992 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004993 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004994 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4995 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004996 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004997 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004998 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004999
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005000 // Determine if the orientation of any of the input windows have changed, and cancel all
5001 // pointer events if necessary.
5002 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
5003 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
5004 if (newWindowHandle != nullptr &&
5005 newWindowHandle->getInfo()->transform.getOrientation() !=
5006 oldWindowOrientations[oldWindowHandle->getId()]) {
5007 std::shared_ptr<InputChannel> inputChannel =
5008 getInputChannelLocked(newWindowHandle->getToken());
5009 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005010 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005011 "touched window's orientation changed");
5012 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005013 }
5014 }
5015 }
5016
Arthur Hung72d8dc32020-03-28 00:48:39 +00005017 // Release information for windows that are no longer present.
5018 // This ensures that unused input channels are released promptly.
5019 // Otherwise, they might stick around until the window handle is destroyed
5020 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005021 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005022 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005023 if (DEBUG_FOCUS) {
5024 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005025 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005026 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005027 }
chaviw291d88a2019-02-14 10:33:58 -08005028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005029}
5030
5031void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005032 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005033 if (DEBUG_FOCUS) {
5034 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5035 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5036 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005037 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005038 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005039 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005040 } // release lock
5041
5042 // Wake up poll loop since it may need to make new input dispatching choices.
5043 mLooper->wake();
5044}
5045
Vishnu Nair599f1412021-06-21 10:39:58 -07005046void InputDispatcher::setFocusedApplicationLocked(
5047 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5048 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5049 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5050
5051 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5052 return; // This application is already focused. No need to wake up or change anything.
5053 }
5054
5055 // Set the new application handle.
5056 if (inputApplicationHandle != nullptr) {
5057 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5058 } else {
5059 mFocusedApplicationHandlesByDisplay.erase(displayId);
5060 }
5061
5062 // No matter what the old focused application was, stop waiting on it because it is
5063 // no longer focused.
5064 resetNoFocusedWindowTimeoutLocked();
5065}
5066
Tiger Huang721e26f2018-07-24 22:26:19 +08005067/**
5068 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5069 * the display not specified.
5070 *
5071 * We track any unreleased events for each window. If a window loses the ability to receive the
5072 * released event, we will send a cancel event to it. So when the focused display is changed, we
5073 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5074 * display. The display-specified events won't be affected.
5075 */
5076void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005077 if (DEBUG_FOCUS) {
5078 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5079 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005080 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005081 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005082
5083 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005084 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005085 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005086 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005087 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005088 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005089 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005090 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005091 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005092 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005093 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005094 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5095 }
5096 }
5097 mFocusedDisplayId = displayId;
5098
Chris Ye3c2d6f52020-08-09 10:39:48 -07005099 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005100 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005101 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005102
Vishnu Nairad321cd2020-08-20 16:40:21 -07005103 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005104 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005105 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005106 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005107 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005108 }
5109 }
5110 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005111 } // release lock
5112
5113 // Wake up poll loop since it may need to make new input dispatching choices.
5114 mLooper->wake();
5115}
5116
Michael Wrightd02c5b62014-02-10 15:10:22 -08005117void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005118 if (DEBUG_FOCUS) {
5119 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5120 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005121
5122 bool changed;
5123 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005124 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005125
5126 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5127 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005128 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005129 }
5130
5131 if (mDispatchEnabled && !enabled) {
5132 resetAndDropEverythingLocked("dispatcher is being disabled");
5133 }
5134
5135 mDispatchEnabled = enabled;
5136 mDispatchFrozen = frozen;
5137 changed = true;
5138 } else {
5139 changed = false;
5140 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141 } // release lock
5142
5143 if (changed) {
5144 // Wake up poll loop since it may need to make new input dispatching choices.
5145 mLooper->wake();
5146 }
5147}
5148
5149void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005150 if (DEBUG_FOCUS) {
5151 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5152 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153
5154 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005155 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005156
5157 if (mInputFilterEnabled == enabled) {
5158 return;
5159 }
5160
5161 mInputFilterEnabled = enabled;
5162 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5163 } // release lock
5164
5165 // Wake up poll loop since there might be work to do to drop everything.
5166 mLooper->wake();
5167}
5168
Antonio Kanteka042c022022-07-06 16:51:07 -07005169bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5170 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005171 bool needWake = false;
5172 {
5173 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005174 ALOGD_IF(DEBUG_TOUCH_MODE,
5175 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5176 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5177 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5178 mTouchModePerDisplay.count(displayId) == 0
5179 ? "not set"
5180 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5181
Antonio Kantek15beb512022-06-13 22:35:41 +00005182 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5183 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005184 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005185 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005186 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005187 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5188 !recentWindowsAreOwnedByLocked(pid, uid)) {
5189 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5190 "window nor none of the previously interacted window",
5191 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005192 return false;
5193 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005194 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005195 mTouchModePerDisplay[displayId] = inTouchMode;
5196 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5197 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005198 needWake = enqueueInboundEventLocked(std::move(entry));
5199 } // release lock
5200
5201 if (needWake) {
5202 mLooper->wake();
5203 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005204 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005205}
5206
Antonio Kantek48710e42022-03-24 14:19:30 -07005207bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5208 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5209 if (focusedToken == nullptr) {
5210 return false;
5211 }
5212 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5213 return isWindowOwnedBy(windowHandle, pid, uid);
5214}
5215
5216bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5217 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5218 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5219 const sp<WindowInfoHandle> windowHandle =
5220 getWindowHandleLocked(connectionToken);
5221 return isWindowOwnedBy(windowHandle, pid, uid);
5222 }) != mInteractionConnectionTokens.end();
5223}
5224
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005225void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5226 if (opacity < 0 || opacity > 1) {
5227 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5228 return;
5229 }
5230
5231 std::scoped_lock lock(mLock);
5232 mMaximumObscuringOpacityForTouch = opacity;
5233}
5234
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005235std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5236InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005237 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5238 for (TouchedWindow& w : state.windows) {
5239 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005240 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005241 }
5242 }
5243 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005244 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005245}
5246
arthurhungb89ccb02020-12-30 16:19:01 +08005247bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5248 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005249 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005250 if (DEBUG_FOCUS) {
5251 ALOGD("Trivial transfer to same window.");
5252 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005253 return true;
5254 }
5255
Michael Wrightd02c5b62014-02-10 15:10:22 -08005256 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005257 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005258
Arthur Hungabbb9d82021-09-01 14:52:30 +00005259 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005260 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005261 if (state == nullptr || touchedWindow == nullptr) {
5262 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005263 return false;
5264 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005265
Arthur Hungabbb9d82021-09-01 14:52:30 +00005266 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5267 if (toWindowHandle == nullptr) {
5268 ALOGW("Cannot transfer focus because to window not found.");
5269 return false;
5270 }
5271
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005272 if (DEBUG_FOCUS) {
5273 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005274 touchedWindow->windowHandle->getName().c_str(),
5275 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005276 }
5277
Arthur Hungabbb9d82021-09-01 14:52:30 +00005278 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005279 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005280 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005281 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005282 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005283
Arthur Hungabbb9d82021-09-01 14:52:30 +00005284 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005285 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005286 ftl::Flags<InputTarget::Flags> newTargetFlags =
5287 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005288 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005289 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005290 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005291 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005292
Arthur Hungabbb9d82021-09-01 14:52:30 +00005293 // Store the dragging window.
5294 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005295 if (pointerIds.count() != 1) {
5296 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5297 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005298 return false;
5299 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005300 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005301 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005302 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005303 }
5304
Arthur Hungabbb9d82021-09-01 14:52:30 +00005305 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005306 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5307 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005308 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005309 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005310 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005311 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005312 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005314 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5315 newTargetFlags);
5316
5317 // Check if the wallpaper window should deliver the corresponding event.
5318 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5319 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005321 } // release lock
5322
5323 // Wake up poll loop since it may need to make new input dispatching choices.
5324 mLooper->wake();
5325 return true;
5326}
5327
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005328/**
5329 * Get the touched foreground window on the given display.
5330 * Return null if there are no windows touched on that display, or if more than one foreground
5331 * window is being touched.
5332 */
5333sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5334 auto stateIt = mTouchStatesByDisplay.find(displayId);
5335 if (stateIt == mTouchStatesByDisplay.end()) {
5336 ALOGI("No touch state on display %" PRId32, displayId);
5337 return nullptr;
5338 }
5339
5340 const TouchState& state = stateIt->second;
5341 sp<WindowInfoHandle> touchedForegroundWindow;
5342 // If multiple foreground windows are touched, return nullptr
5343 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005344 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005345 if (touchedForegroundWindow != nullptr) {
5346 ALOGI("Two or more foreground windows: %s and %s",
5347 touchedForegroundWindow->getName().c_str(),
5348 window.windowHandle->getName().c_str());
5349 return nullptr;
5350 }
5351 touchedForegroundWindow = window.windowHandle;
5352 }
5353 }
5354 return touchedForegroundWindow;
5355}
5356
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005357// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005358bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005359 sp<IBinder> fromToken;
5360 { // acquire lock
5361 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005362 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005363 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005364 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5365 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005366 return false;
5367 }
5368
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005369 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5370 if (from == nullptr) {
5371 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5372 return false;
5373 }
5374
5375 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005376 } // release lock
5377
5378 return transferTouchFocus(fromToken, destChannelToken);
5379}
5380
Michael Wrightd02c5b62014-02-10 15:10:22 -08005381void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005382 if (DEBUG_FOCUS) {
5383 ALOGD("Resetting and dropping all events (%s).", reason);
5384 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005385
Michael Wrightfb04fd52022-11-24 22:31:11 +00005386 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005387 synthesizeCancelationEventsForAllConnectionsLocked(options);
5388
5389 resetKeyRepeatLocked();
5390 releasePendingEventLocked();
5391 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005392 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005393
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005394 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005395 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005396 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005397}
5398
5399void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005400 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005401 dumpDispatchStateLocked(dump);
5402
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005403 std::istringstream stream(dump);
5404 std::string line;
5405
5406 while (std::getline(stream, line, '\n')) {
5407 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408 }
5409}
5410
Prabir Pradhan99987712020-11-10 18:43:05 -08005411std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5412 std::string dump;
5413
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005414 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5415 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005416
5417 std::string windowName = "None";
5418 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005419 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005420 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5421 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5422 : "token has capture without window";
5423 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005424 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005425
5426 return dump;
5427}
5428
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005429void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005430 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5431 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5432 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005433 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005434
Tiger Huang721e26f2018-07-24 22:26:19 +08005435 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5436 dump += StringPrintf(INDENT "FocusedApplications:\n");
5437 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5438 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005439 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005440 const std::chrono::duration timeout =
5441 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005442 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005443 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005444 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005445 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005446 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005447 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005448 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005449
Vishnu Nairc519ff72021-01-21 08:23:08 -08005450 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005451 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005452
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005453 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005454 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005455 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005456 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5457 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005458 }
5459 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005460 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005461 }
5462
arthurhung6d4bed92021-03-17 11:59:33 +08005463 if (mDragState) {
5464 dump += StringPrintf(INDENT "DragState:\n");
5465 mDragState->dump(dump, INDENT2);
5466 }
5467
Arthur Hungb92218b2018-08-14 12:00:21 +08005468 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005469 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5470 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5471 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5472 const auto& displayInfo = it->second;
5473 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5474 displayInfo.logicalHeight);
5475 displayInfo.transform.dump(dump, "transform", INDENT4);
5476 } else {
5477 dump += INDENT2 "No DisplayInfo found!\n";
5478 }
5479
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005480 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005481 dump += INDENT2 "Windows:\n";
5482 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005483 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5484 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005486 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005487 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005488 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005489 "applicationInfo.name=%s, "
5490 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005491 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005492 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005493 windowInfo->displayId,
5494 windowInfo->inputConfig.string().c_str(),
5495 windowInfo->alpha, windowInfo->frameLeft,
5496 windowInfo->frameTop, windowInfo->frameRight,
5497 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005498 windowInfo->applicationInfo.name.c_str(),
5499 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005500 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005501 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005502 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005503 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005504 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005505 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005506 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005507 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005508 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005509 }
5510 } else {
5511 dump += INDENT2 "Windows: <none>\n";
5512 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005513 }
5514 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005515 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005516 }
5517
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005518 if (!mGlobalMonitorsByDisplay.empty()) {
5519 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5520 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005521 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005523 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005524 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005525 }
5526
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005527 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005528
5529 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005530 if (!mRecentQueue.empty()) {
5531 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005532 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005533 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005534 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005535 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005536 }
5537 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005538 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005539 }
5540
5541 // Dump event currently being dispatched.
5542 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005543 dump += INDENT "PendingEvent:\n";
5544 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005545 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005546 dump += StringPrintf(", age=%" PRId64 "ms\n",
5547 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005548 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005549 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005550 }
5551
5552 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005553 if (!mInboundQueue.empty()) {
5554 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005555 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005556 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005557 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005558 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005559 }
5560 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005561 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562 }
5563
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005564 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005565 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005566 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005567 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005568 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005569 }
5570 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005571 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005572 }
5573
Prabir Pradhancef936d2021-07-21 16:17:52 +00005574 if (!mCommandQueue.empty()) {
5575 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5576 } else {
5577 dump += INDENT "CommandQueue: <empty>\n";
5578 }
5579
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005580 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005581 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005582 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005583 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005584 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005585 connection->inputChannel->getFd().get(),
5586 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005587 connection->getWindowName().c_str(),
5588 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005589 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005590
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005591 if (!connection->outboundQueue.empty()) {
5592 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5593 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005594 dump += dumpQueue(connection->outboundQueue, currentTime);
5595
Michael Wrightd02c5b62014-02-10 15:10:22 -08005596 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005597 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005598 }
5599
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005600 if (!connection->waitQueue.empty()) {
5601 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5602 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005603 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005604 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005605 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005606 }
5607 }
5608 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005609 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005610 }
5611
5612 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005613 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5614 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005615 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005616 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005617 }
5618
Antonio Kantek15beb512022-06-13 22:35:41 +00005619 if (!mTouchModePerDisplay.empty()) {
5620 dump += INDENT "TouchModePerDisplay:\n";
5621 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5622 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5623 std::to_string(touchMode).c_str());
5624 }
5625 } else {
5626 dump += INDENT "TouchModePerDisplay: <none>\n";
5627 }
5628
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005629 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005630 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5631 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5632 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005633 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005634 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005635}
5636
Michael Wright3dd60e22019-03-27 22:06:44 +00005637void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5638 const size_t numMonitors = monitors.size();
5639 for (size_t i = 0; i < numMonitors; i++) {
5640 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005641 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005642 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5643 dump += "\n";
5644 }
5645}
5646
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005647class LooperEventCallback : public LooperCallback {
5648public:
5649 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5650 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5651
5652private:
5653 std::function<int(int events)> mCallback;
5654};
5655
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005656Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005657 if (DEBUG_CHANNEL_CREATION) {
5658 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5659 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005660
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005661 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005662 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005663 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005664
5665 if (result) {
5666 return base::Error(result) << "Failed to open input channel pair with name " << name;
5667 }
5668
Michael Wrightd02c5b62014-02-10 15:10:22 -08005669 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005670 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005671 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005672 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005673 sp<Connection> connection =
Harry Cutts33476232023-01-30 19:57:29 +00005674 sp<Connection>::make(std::move(serverChannel), /*monitor=*/false, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005675
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005676 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5677 ALOGE("Created a new connection, but the token %p is already known", token.get());
5678 }
5679 mConnectionsByToken.emplace(token, connection);
5680
5681 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5682 this, std::placeholders::_1, token);
5683
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005684 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5685 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005686 } // release lock
5687
5688 // Wake the looper because some connections have changed.
5689 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005690 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005691}
5692
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005693Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005694 const std::string& name,
5695 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005696 std::shared_ptr<InputChannel> serverChannel;
5697 std::unique_ptr<InputChannel> clientChannel;
5698 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5699 if (result) {
5700 return base::Error(result) << "Failed to open input channel pair with name " << name;
5701 }
5702
Michael Wright3dd60e22019-03-27 22:06:44 +00005703 { // acquire lock
5704 std::scoped_lock _l(mLock);
5705
5706 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005707 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5708 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005709 }
5710
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005711 sp<Connection> connection =
Harry Cutts33476232023-01-30 19:57:29 +00005712 sp<Connection>::make(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005713 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005714 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005715
5716 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5717 ALOGE("Created a new connection, but the token %p is already known", token.get());
5718 }
5719 mConnectionsByToken.emplace(token, connection);
5720 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5721 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005722
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005723 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005724
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005725 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5726 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005727 }
Garfield Tan15601662020-09-22 15:32:38 -07005728
Michael Wright3dd60e22019-03-27 22:06:44 +00005729 // Wake the looper because some connections have changed.
5730 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005731 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005732}
5733
Garfield Tan15601662020-09-22 15:32:38 -07005734status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005735 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005736 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005737
Harry Cutts33476232023-01-30 19:57:29 +00005738 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005739 if (status) {
5740 return status;
5741 }
5742 } // release lock
5743
5744 // Wake the poll loop because removing the connection may have changed the current
5745 // synchronization state.
5746 mLooper->wake();
5747 return OK;
5748}
5749
Garfield Tan15601662020-09-22 15:32:38 -07005750status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5751 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005752 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005753 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005754 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005755 return BAD_VALUE;
5756 }
5757
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005758 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005759
Michael Wrightd02c5b62014-02-10 15:10:22 -08005760 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005761 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005762 }
5763
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005764 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005765
5766 nsecs_t currentTime = now();
5767 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5768
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005769 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005770 return OK;
5771}
5772
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005773void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005774 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5775 auto& [displayId, monitors] = *it;
5776 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5777 return monitor.inputChannel->getConnectionToken() == connectionToken;
5778 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005779
Michael Wright3dd60e22019-03-27 22:06:44 +00005780 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005781 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005782 } else {
5783 ++it;
5784 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005785 }
5786}
5787
Michael Wright3dd60e22019-03-27 22:06:44 +00005788status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005789 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005790 return pilferPointersLocked(token);
5791}
Michael Wright3dd60e22019-03-27 22:06:44 +00005792
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005793status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005794 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5795 if (!requestingChannel) {
5796 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5797 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005798 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005799
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005800 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005801 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.none()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005802 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5803 " Ignoring.");
5804 return BAD_VALUE;
5805 }
5806
5807 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005808 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005809 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005810 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005811 "input channel stole pointer stream");
5812 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005813 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005814 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005815 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005816 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005817 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005818 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005819 if (channel != nullptr && channel->getConnectionToken() != token) {
5820 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5821 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5822 canceledWindows += channel->getName();
5823 }
5824 }
5825 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5826 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5827 canceledWindows.c_str());
5828
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005829 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005830 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005831 window.pilferedPointerIds |= window.pointerIds;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005832
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005833 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005834 return OK;
5835}
5836
Prabir Pradhan99987712020-11-10 18:43:05 -08005837void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5838 { // acquire lock
5839 std::scoped_lock _l(mLock);
5840 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005841 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005842 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5843 windowHandle != nullptr ? windowHandle->getName().c_str()
5844 : "token without window");
5845 }
5846
Vishnu Nairc519ff72021-01-21 08:23:08 -08005847 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005848 if (focusedToken != windowToken) {
5849 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5850 enabled ? "enable" : "disable");
5851 return;
5852 }
5853
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005854 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005855 ALOGW("Ignoring request to %s Pointer Capture: "
5856 "window has %s requested pointer capture.",
5857 enabled ? "enable" : "disable", enabled ? "already" : "not");
5858 return;
5859 }
5860
Christine Franksb768bb42021-11-29 12:11:31 -08005861 if (enabled) {
5862 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5863 mIneligibleDisplaysForPointerCapture.end(),
5864 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5865 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5866 return;
5867 }
5868 }
5869
Prabir Pradhan99987712020-11-10 18:43:05 -08005870 setPointerCaptureLocked(enabled);
5871 } // release lock
5872
5873 // Wake the thread to process command entries.
5874 mLooper->wake();
5875}
5876
Christine Franksb768bb42021-11-29 12:11:31 -08005877void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5878 { // acquire lock
5879 std::scoped_lock _l(mLock);
5880 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5881 if (!isEligible) {
5882 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5883 }
5884 } // release lock
5885}
5886
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005887std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5888 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005889 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005890 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005891 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005892 }
5893 }
5894 }
5895 return std::nullopt;
5896}
5897
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005898sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005899 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005900 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005901 }
5902
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005903 for (const auto& [token, connection] : mConnectionsByToken) {
5904 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005905 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005906 }
5907 }
Robert Carr4e670e52018-08-15 13:26:12 -07005908
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005909 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005910}
5911
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005912std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5913 sp<Connection> connection = getConnectionLocked(connectionToken);
5914 if (connection == nullptr) {
5915 return "<nullptr>";
5916 }
5917 return connection->getInputChannelName();
5918}
5919
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005920void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005921 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005922 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005923}
5924
Prabir Pradhancef936d2021-07-21 16:17:52 +00005925void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5926 const sp<Connection>& connection, uint32_t seq,
5927 bool handled, nsecs_t consumeTime) {
5928 // Handle post-event policy actions.
5929 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5930 if (dispatchEntryIt == connection->waitQueue.end()) {
5931 return;
5932 }
5933 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5934 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5935 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5936 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5937 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5938 }
5939 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5940 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5941 connection->inputChannel->getConnectionToken(),
5942 dispatchEntry->deliveryTime, consumeTime, finishTime);
5943 }
5944
5945 bool restartEvent;
5946 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5947 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5948 restartEvent =
5949 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5950 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5951 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5952 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5953 handled);
5954 } else {
5955 restartEvent = false;
5956 }
5957
5958 // Dequeue the event and start the next cycle.
5959 // Because the lock might have been released, it is possible that the
5960 // contents of the wait queue to have been drained, so we need to double-check
5961 // a few things.
5962 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5963 if (dispatchEntryIt != connection->waitQueue.end()) {
5964 dispatchEntry = *dispatchEntryIt;
5965 connection->waitQueue.erase(dispatchEntryIt);
5966 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5967 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5968 if (!connection->responsive) {
5969 connection->responsive = isConnectionResponsive(*connection);
5970 if (connection->responsive) {
5971 // The connection was unresponsive, and now it's responsive.
5972 processConnectionResponsiveLocked(*connection);
5973 }
5974 }
5975 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005976 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005977 connection->outboundQueue.push_front(dispatchEntry);
5978 traceOutboundQueueLength(*connection);
5979 } else {
5980 releaseDispatchEntry(dispatchEntry);
5981 }
5982 }
5983
5984 // Start the next dispatch cycle for this connection.
5985 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005986}
5987
Prabir Pradhancef936d2021-07-21 16:17:52 +00005988void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5989 const sp<IBinder>& newToken) {
5990 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5991 scoped_unlock unlock(mLock);
5992 mPolicy->notifyFocusChanged(oldToken, newToken);
5993 };
5994 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005995}
5996
Prabir Pradhancef936d2021-07-21 16:17:52 +00005997void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5998 auto command = [this, token, x, y]() REQUIRES(mLock) {
5999 scoped_unlock unlock(mLock);
6000 mPolicy->notifyDropWindow(token, x, y);
6001 };
6002 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006003}
6004
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006005void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
6006 if (connection == nullptr) {
6007 LOG_ALWAYS_FATAL("Caller must check for nullness");
6008 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006009 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6010 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006011 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006012 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006013 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006014 return;
6015 }
6016 /**
6017 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6018 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6019 * has changed. This could cause newer entries to time out before the already dispatched
6020 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6021 * processes the events linearly. So providing information about the oldest entry seems to be
6022 * most useful.
6023 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006024 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006025 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6026 std::string reason =
6027 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006028 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006029 ns2ms(currentWait),
6030 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006031 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006032 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006033
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006034 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6035
6036 // Stop waking up for events on this connection, it is already unresponsive
6037 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006038}
6039
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006040void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6041 std::string reason =
6042 StringPrintf("%s does not have a focused window", application->getName().c_str());
6043 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006044
Prabir Pradhancef936d2021-07-21 16:17:52 +00006045 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
6046 scoped_unlock unlock(mLock);
6047 mPolicy->notifyNoFocusedWindowAnr(application);
6048 };
6049 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006050}
6051
chaviw98318de2021-05-19 16:45:23 -05006052void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006053 const std::string& reason) {
6054 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6055 updateLastAnrStateLocked(windowLabel, reason);
6056}
6057
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006058void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6059 const std::string& reason) {
6060 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006061 updateLastAnrStateLocked(windowLabel, reason);
6062}
6063
6064void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6065 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006066 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006067 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006068 struct tm tm;
6069 localtime_r(&t, &tm);
6070 char timestr[64];
6071 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006072 mLastAnrState.clear();
6073 mLastAnrState += INDENT "ANR:\n";
6074 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006075 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6076 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006077 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006078}
6079
Prabir Pradhancef936d2021-07-21 16:17:52 +00006080void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6081 KeyEntry& entry) {
6082 const KeyEvent event = createKeyEvent(entry);
6083 nsecs_t delay = 0;
6084 { // release lock
6085 scoped_unlock unlock(mLock);
6086 android::base::Timer t;
6087 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
6088 entry.policyFlags);
6089 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6090 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6091 std::to_string(t.duration().count()).c_str());
6092 }
6093 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006094
6095 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006096 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006097 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006098 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006099 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006100 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006101 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006102 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006103}
6104
Prabir Pradhancef936d2021-07-21 16:17:52 +00006105void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006106 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006107 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006108 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006109 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006110 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006111 };
6112 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006113}
6114
Prabir Pradhanedd96402022-02-15 01:46:16 -08006115void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6116 std::optional<int32_t> pid) {
6117 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006118 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006119 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006120 };
6121 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006122}
6123
6124/**
6125 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6126 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6127 * command entry to the command queue.
6128 */
6129void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6130 std::string reason) {
6131 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006132 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006133 if (connection.monitor) {
6134 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6135 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006136 pid = findMonitorPidByTokenLocked(connectionToken);
6137 } else {
6138 // The connection is a window
6139 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6140 reason.c_str());
6141 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6142 if (handle != nullptr) {
6143 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006144 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006145 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006146 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006147}
6148
6149/**
6150 * Tell the policy that a connection has become responsive so that it can stop ANR.
6151 */
6152void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6153 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006154 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006155 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006156 pid = findMonitorPidByTokenLocked(connectionToken);
6157 } else {
6158 // The connection is a window
6159 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6160 if (handle != nullptr) {
6161 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006162 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006163 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006164 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006165}
6166
Prabir Pradhancef936d2021-07-21 16:17:52 +00006167bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006168 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006169 KeyEntry& keyEntry, bool handled) {
6170 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006171 if (!handled) {
6172 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006173 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006174 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006175 return false;
6176 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006177
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006178 // Get the fallback key state.
6179 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006180 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006181 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006182 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006183 connection->inputState.removeFallbackKey(originalKeyCode);
6184 }
6185
6186 if (handled || !dispatchEntry->hasForegroundTarget()) {
6187 // If the application handles the original key for which we previously
6188 // generated a fallback or if the window is not a foreground window,
6189 // then cancel the associated fallback key, if any.
6190 if (fallbackKeyCode != -1) {
6191 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006192 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6193 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6194 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6195 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6196 keyEntry.policyFlags);
6197 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006198 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006199 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006200
6201 mLock.unlock();
6202
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006203 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006204 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006205
6206 mLock.lock();
6207
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006208 // Cancel the fallback key.
6209 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006210 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006211 "application handled the original non-fallback key "
6212 "or is no longer a foreground target, "
6213 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006214 options.keyCode = fallbackKeyCode;
6215 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006216 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006217 connection->inputState.removeFallbackKey(originalKeyCode);
6218 }
6219 } else {
6220 // If the application did not handle a non-fallback key, first check
6221 // that we are in a good state to perform unhandled key event processing
6222 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006223 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006224 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006225 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6226 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6227 "since this is not an initial down. "
6228 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6229 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6230 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006231 return false;
6232 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006233
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006234 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006235 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6236 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6237 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6238 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6239 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006240 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006241
6242 mLock.unlock();
6243
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006244 bool fallback =
6245 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006246 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006247
6248 mLock.lock();
6249
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006250 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006251 connection->inputState.removeFallbackKey(originalKeyCode);
6252 return false;
6253 }
6254
6255 // Latch the fallback keycode for this key on an initial down.
6256 // The fallback keycode cannot change at any other point in the lifecycle.
6257 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006258 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006259 fallbackKeyCode = event.getKeyCode();
6260 } else {
6261 fallbackKeyCode = AKEYCODE_UNKNOWN;
6262 }
6263 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6264 }
6265
6266 ALOG_ASSERT(fallbackKeyCode != -1);
6267
6268 // Cancel the fallback key if the policy decides not to send it anymore.
6269 // We will continue to dispatch the key to the policy but we will no
6270 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006271 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6272 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006273 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6274 if (fallback) {
6275 ALOGD("Unhandled key event: Policy requested to send key %d"
6276 "as a fallback for %d, but on the DOWN it had requested "
6277 "to send %d instead. Fallback canceled.",
6278 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6279 } else {
6280 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6281 "but on the DOWN it had requested to send %d. "
6282 "Fallback canceled.",
6283 originalKeyCode, fallbackKeyCode);
6284 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006285 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006286
Michael Wrightfb04fd52022-11-24 22:31:11 +00006287 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006288 "canceling fallback, policy no longer desires it");
6289 options.keyCode = fallbackKeyCode;
6290 synthesizeCancelationEventsForConnectionLocked(connection, options);
6291
6292 fallback = false;
6293 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006294 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006295 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006296 }
6297 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006298
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006299 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6300 {
6301 std::string msg;
6302 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6303 connection->inputState.getFallbackKeys();
6304 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6305 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6306 }
6307 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6308 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006309 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006310 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006311
6312 if (fallback) {
6313 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006314 keyEntry.eventTime = event.getEventTime();
6315 keyEntry.deviceId = event.getDeviceId();
6316 keyEntry.source = event.getSource();
6317 keyEntry.displayId = event.getDisplayId();
6318 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6319 keyEntry.keyCode = fallbackKeyCode;
6320 keyEntry.scanCode = event.getScanCode();
6321 keyEntry.metaState = event.getMetaState();
6322 keyEntry.repeatCount = event.getRepeatCount();
6323 keyEntry.downTime = event.getDownTime();
6324 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006325
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006326 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6327 ALOGD("Unhandled key event: Dispatching fallback key. "
6328 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6329 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6330 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006331 return true; // restart the event
6332 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006333 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6334 ALOGD("Unhandled key event: No fallback key.");
6335 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006336
6337 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006338 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006339 }
6340 }
6341 return false;
6342}
6343
Prabir Pradhancef936d2021-07-21 16:17:52 +00006344bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006345 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006346 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006347 return false;
6348}
6349
Michael Wrightd02c5b62014-02-10 15:10:22 -08006350void InputDispatcher::traceInboundQueueLengthLocked() {
6351 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006352 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006353 }
6354}
6355
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006356void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006357 if (ATRACE_ENABLED()) {
6358 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006359 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6360 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006361 }
6362}
6363
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006364void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006365 if (ATRACE_ENABLED()) {
6366 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006367 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6368 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006369 }
6370}
6371
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006372void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006373 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006374
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006375 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006376 dumpDispatchStateLocked(dump);
6377
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006378 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006379 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006380 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006381 }
6382}
6383
6384void InputDispatcher::monitor() {
6385 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006386 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006387 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006388 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006389}
6390
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006391/**
6392 * Wake up the dispatcher and wait until it processes all events and commands.
6393 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6394 * this method can be safely called from any thread, as long as you've ensured that
6395 * the work you are interested in completing has already been queued.
6396 */
6397bool InputDispatcher::waitForIdle() {
6398 /**
6399 * Timeout should represent the longest possible time that a device might spend processing
6400 * events and commands.
6401 */
6402 constexpr std::chrono::duration TIMEOUT = 100ms;
6403 std::unique_lock lock(mLock);
6404 mLooper->wake();
6405 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6406 return result == std::cv_status::no_timeout;
6407}
6408
Vishnu Naire798b472020-07-23 13:52:21 -07006409/**
6410 * Sets focus to the window identified by the token. This must be called
6411 * after updating any input window handles.
6412 *
6413 * Params:
6414 * request.token - input channel token used to identify the window that should gain focus.
6415 * request.focusedToken - the token that the caller expects currently to be focused. If the
6416 * specified token does not match the currently focused window, this request will be dropped.
6417 * If the specified focused token matches the currently focused window, the call will succeed.
6418 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6419 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6420 * when requesting the focus change. This determines which request gets
6421 * precedence if there is a focus change request from another source such as pointer down.
6422 */
Vishnu Nair958da932020-08-21 17:12:37 -07006423void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6424 { // acquire lock
6425 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006426 std::optional<FocusResolver::FocusChanges> changes =
6427 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6428 if (changes) {
6429 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006430 }
6431 } // release lock
6432 // Wake up poll loop since it may need to make new input dispatching choices.
6433 mLooper->wake();
6434}
6435
Vishnu Nairc519ff72021-01-21 08:23:08 -08006436void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6437 if (changes.oldFocus) {
6438 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006439 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006440 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006441 "focus left window");
6442 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006443 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006444 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006445 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006446 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006447 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006448 }
6449
Prabir Pradhan99987712020-11-10 18:43:05 -08006450 // If a window has pointer capture, then it must have focus. We need to ensure that this
6451 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6452 // If the window loses focus before it loses pointer capture, then the window can be in a state
6453 // where it has pointer capture but not focus, violating the contract. Therefore we must
6454 // dispatch the pointer capture event before the focus event. Since focus events are added to
6455 // the front of the queue (above), we add the pointer capture event to the front of the queue
6456 // after the focus events are added. This ensures the pointer capture event ends up at the
6457 // front.
6458 disablePointerCaptureForcedLocked();
6459
Vishnu Nairc519ff72021-01-21 08:23:08 -08006460 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006461 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006462 }
6463}
Vishnu Nair958da932020-08-21 17:12:37 -07006464
Prabir Pradhan99987712020-11-10 18:43:05 -08006465void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006466 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006467 return;
6468 }
6469
6470 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6471
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006472 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006473 setPointerCaptureLocked(false);
6474 }
6475
6476 if (!mWindowTokenWithPointerCapture) {
6477 // No need to send capture changes because no window has capture.
6478 return;
6479 }
6480
6481 if (mPendingEvent != nullptr) {
6482 // Move the pending event to the front of the queue. This will give the chance
6483 // for the pending event to be dropped if it is a captured event.
6484 mInboundQueue.push_front(mPendingEvent);
6485 mPendingEvent = nullptr;
6486 }
6487
6488 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006489 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006490 mInboundQueue.push_front(std::move(entry));
6491}
6492
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006493void InputDispatcher::setPointerCaptureLocked(bool enable) {
6494 mCurrentPointerCaptureRequest.enable = enable;
6495 mCurrentPointerCaptureRequest.seq++;
6496 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006497 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006498 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006499 };
6500 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006501}
6502
Vishnu Nair599f1412021-06-21 10:39:58 -07006503void InputDispatcher::displayRemoved(int32_t displayId) {
6504 { // acquire lock
6505 std::scoped_lock _l(mLock);
6506 // Set an empty list to remove all handles from the specific display.
6507 setInputWindowsLocked(/* window handles */ {}, displayId);
6508 setFocusedApplicationLocked(displayId, nullptr);
6509 // Call focus resolver to clean up stale requests. This must be called after input windows
6510 // have been removed for the removed display.
6511 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006512 // Reset pointer capture eligibility, regardless of previous state.
6513 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006514 // Remove the associated touch mode state.
6515 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006516 } // release lock
6517
6518 // Wake up poll loop since it may need to make new input dispatching choices.
6519 mLooper->wake();
6520}
6521
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006522void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6523 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006524 // The listener sends the windows as a flattened array. Separate the windows by display for
6525 // more convenient parsing.
6526 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006527 for (const auto& info : windowInfos) {
6528 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006529 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006530 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006531
6532 { // acquire lock
6533 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006534
6535 // Ensure that we have an entry created for all existing displays so that if a displayId has
6536 // no windows, we can tell that the windows were removed from the display.
6537 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6538 handlesPerDisplay[displayId];
6539 }
6540
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006541 mDisplayInfos.clear();
6542 for (const auto& displayInfo : displayInfos) {
6543 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6544 }
6545
6546 for (const auto& [displayId, handles] : handlesPerDisplay) {
6547 setInputWindowsLocked(handles, displayId);
6548 }
6549 }
6550 // Wake up poll loop since it may need to make new input dispatching choices.
6551 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006552}
6553
Vishnu Nair062a8672021-09-03 16:07:44 -07006554bool InputDispatcher::shouldDropInput(
6555 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006556 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6557 (windowHandle->getInfo()->inputConfig.test(
6558 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006559 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006560 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6561 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006562 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006563 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006564 windowHandle->getInfo()->displayId);
6565 return true;
6566 }
6567 return false;
6568}
6569
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006570void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6571 const std::vector<gui::WindowInfo>& windowInfos,
6572 const std::vector<DisplayInfo>& displayInfos) {
6573 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6574}
6575
Arthur Hungdfd528e2021-12-08 13:23:04 +00006576void InputDispatcher::cancelCurrentTouch() {
6577 {
6578 std::scoped_lock _l(mLock);
6579 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006580 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006581 "cancel current touch");
6582 synthesizeCancelationEventsForAllConnectionsLocked(options);
6583
6584 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006585 }
6586 // Wake up poll loop since there might be work to do.
6587 mLooper->wake();
6588}
6589
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006590void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6591 std::scoped_lock _l(mLock);
6592 mMonitorDispatchingTimeout = timeout;
6593}
6594
Arthur Hungc539dbb2022-12-08 07:45:36 +00006595void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6596 const sp<WindowInfoHandle>& oldWindowHandle,
6597 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006598 TouchState& state, int32_t pointerId,
6599 std::vector<InputTarget>& targets) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006600 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6601 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006602 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6603 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6604 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6605 newWindowHandle->getInfo()->inputConfig.test(
6606 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6607 const sp<WindowInfoHandle> oldWallpaper =
6608 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6609 const sp<WindowInfoHandle> newWallpaper =
6610 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6611 if (oldWallpaper == newWallpaper) {
6612 return;
6613 }
6614
6615 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006616 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6617 addWindowTargetLocked(oldWallpaper,
6618 oldTouchedWindow.targetFlags |
6619 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6620 pointerIds, oldTouchedWindow.firstDownTimeInTarget, targets);
6621 state.removeTouchedPointerFromWindow(pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006622 }
6623
6624 if (newWallpaper != nullptr) {
6625 state.addOrUpdateWindow(newWallpaper,
6626 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6627 InputTarget::Flags::WINDOW_IS_OBSCURED |
6628 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6629 pointerIds);
6630 }
6631}
6632
6633void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6634 ftl::Flags<InputTarget::Flags> newTargetFlags,
6635 const sp<WindowInfoHandle> fromWindowHandle,
6636 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006637 TouchState& state,
6638 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006639 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6640 fromWindowHandle->getInfo()->inputConfig.test(
6641 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6642 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6643 toWindowHandle->getInfo()->inputConfig.test(
6644 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6645
6646 const sp<WindowInfoHandle> oldWallpaper =
6647 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6648 const sp<WindowInfoHandle> newWallpaper =
6649 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6650 if (oldWallpaper == newWallpaper) {
6651 return;
6652 }
6653
6654 if (oldWallpaper != nullptr) {
6655 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6656 "transferring touch focus to another window");
6657 state.removeWindowByToken(oldWallpaper->getToken());
6658 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6659 }
6660
6661 if (newWallpaper != nullptr) {
6662 nsecs_t downTimeInTarget = now();
6663 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6664 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6665 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6666 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6667 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
6668 sp<Connection> wallpaperConnection = getConnectionLocked(newWallpaper->getToken());
6669 if (wallpaperConnection != nullptr) {
6670 sp<Connection> toConnection = getConnectionLocked(toWindowHandle->getToken());
6671 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6672 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6673 wallpaperFlags);
6674 }
6675 }
6676}
6677
6678sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6679 const sp<WindowInfoHandle>& windowHandle) const {
6680 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6681 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6682 bool foundWindow = false;
6683 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6684 if (!foundWindow && otherHandle != windowHandle) {
6685 continue;
6686 }
6687 if (windowHandle == otherHandle) {
6688 foundWindow = true;
6689 continue;
6690 }
6691
6692 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6693 return otherHandle;
6694 }
6695 }
6696 return nullptr;
6697}
6698
Garfield Tane84e6f92019-08-29 17:28:41 -07006699} // namespace android::inputdispatcher