blob: 6b9ad446ce56ad9af177187da23017b6689b6c35 [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>
tyiu1573a672023-02-21 22:38:32 +000034#include <openssl/mem.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070035#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010036#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070037#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080038
Michael Wright44753b12020-07-08 13:48:11 +010039#include <cerrno>
40#include <cinttypes>
41#include <climits>
42#include <cstddef>
43#include <ctime>
44#include <queue>
45#include <sstream>
46
47#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000048#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070049#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010050
Michael Wrightd02c5b62014-02-10 15:10:22 -080051#define INDENT " "
52#define INDENT2 " "
53#define INDENT3 " "
54#define INDENT4 " "
55
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080056using namespace android::ftl::flag_operators;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080057using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000058using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080059using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070060using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050061using android::gui::FocusRequest;
62using android::gui::TouchOcclusionMode;
63using android::gui::WindowInfo;
64using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080065using android::os::InputEventInjectionResult;
66using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067
Garfield Tane84e6f92019-08-29 17:28:41 -070068namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080069
Prabir Pradhancef936d2021-07-21 16:17:52 +000070namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000071// Temporarily releases a held mutex for the lifetime of the instance.
72// Named to match std::scoped_lock
73class scoped_unlock {
74public:
75 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
76 ~scoped_unlock() { mMutex.lock(); }
77
78private:
79 std::mutex& mMutex;
80};
81
Michael Wrightd02c5b62014-02-10 15:10:22 -080082// Default input dispatching timeout if there is no focused application or paused window
83// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080084const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
85 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
86 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080087
88// Amount of time to allow for all pending events to be processed when an app switch
89// key is on the way. This is used to preempt input dispatch and drop input events
90// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000091constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080092
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080093const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080094
Michael Wrightd02c5b62014-02-10 15:10:22 -080095// 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 +000096constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
97
98// Log a warning when an interception call takes longer than this to process.
99constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800100
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700101// Additional key latency in case a connection is still processing some motion events.
102// This will help with the case when a user touched a button that opens a new window,
103// and gives us the chance to dispatch the key to this new window.
104constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
105
Michael Wrightd02c5b62014-02-10 15:10:22 -0800106// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000107constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
108
Antonio Kantekea47acb2021-12-23 12:41:25 -0800109// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000110constexpr int LOGTAG_INPUT_INTERACTION = 62000;
111constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000112constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000113
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000114const ui::Transform kIdentityTransform;
115
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000116inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800117 return systemTime(SYSTEM_TIME_MONOTONIC);
118}
119
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700120inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000121 if (binder == nullptr) {
122 return "<null>";
123 }
124 return StringPrintf("%p", binder.get());
125}
126
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000127inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700128 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
129 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800130}
131
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000132bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800133 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700134 case AKEY_EVENT_ACTION_DOWN:
135 case AKEY_EVENT_ACTION_UP:
136 return true;
137 default:
138 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139 }
140}
141
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000142bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700143 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144 ALOGE("Key event has invalid action code 0x%x", action);
145 return false;
146 }
147 return true;
148}
149
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000150bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800151 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700152 case AMOTION_EVENT_ACTION_DOWN:
153 case AMOTION_EVENT_ACTION_UP:
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800154 return pointerCount == 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700155 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700156 case AMOTION_EVENT_ACTION_HOVER_ENTER:
157 case AMOTION_EVENT_ACTION_HOVER_MOVE:
158 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800159 return pointerCount >= 1;
160 case AMOTION_EVENT_ACTION_CANCEL:
161 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700162 case AMOTION_EVENT_ACTION_SCROLL:
163 return true;
164 case AMOTION_EVENT_ACTION_POINTER_DOWN:
165 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800166 const int32_t index = MotionEvent::getActionIndex(action);
167 return index >= 0 && index < pointerCount && pointerCount > 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700168 }
169 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
170 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
171 return actionButton != 0;
172 default:
173 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800174 }
175}
176
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000177int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500178 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
179}
180
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000181bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
182 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700183 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800184 ALOGE("Motion event has invalid action code 0x%x", action);
185 return false;
186 }
187 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800188 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %zu.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700189 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800190 return false;
191 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800192 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800193 for (size_t i = 0; i < pointerCount; i++) {
194 int32_t id = pointerProperties[i].id;
195 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700196 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
197 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800198 return false;
199 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800200 if (pointerIdBits.test(id)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800201 ALOGE("Motion event has duplicate pointer id %d", id);
202 return false;
203 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800204 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800205 }
206 return true;
207}
208
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000209std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800210 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000211 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800212 }
213
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000214 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800215 bool first = true;
216 Region::const_iterator cur = region.begin();
217 Region::const_iterator const tail = region.end();
218 while (cur != tail) {
219 if (first) {
220 first = false;
221 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800222 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800224 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800225 cur++;
226 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000227 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800228}
229
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000230std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500231 constexpr size_t maxEntries = 50; // max events to print
232 constexpr size_t skipBegin = maxEntries / 2;
233 const size_t skipEnd = queue.size() - maxEntries / 2;
234 // skip from maxEntries / 2 ... size() - maxEntries/2
235 // only print from 0 .. skipBegin and then from skipEnd .. size()
236
237 std::string dump;
238 for (size_t i = 0; i < queue.size(); i++) {
239 const DispatchEntry& entry = *queue[i];
240 if (i >= skipBegin && i < skipEnd) {
241 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
242 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
243 continue;
244 }
245 dump.append(INDENT4);
246 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800247 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
248 "ms",
249 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500250 ns2ms(currentTime - entry.eventEntry->eventTime));
251 if (entry.deliveryTime != 0) {
252 // This entry was delivered, so add information on how long we've been waiting
253 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
254 }
255 dump.append("\n");
256 }
257 return dump;
258}
259
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700260/**
261 * Find the entry in std::unordered_map by key, and return it.
262 * If the entry is not found, return a default constructed entry.
263 *
264 * Useful when the entries are vectors, since an empty vector will be returned
265 * if the entry is not found.
266 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
267 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700268template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000269V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700270 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700271 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800272}
273
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000274bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700275 if (first == second) {
276 return true;
277 }
278
279 if (first == nullptr || second == nullptr) {
280 return false;
281 }
282
283 return first->getToken() == second->getToken();
284}
285
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000286bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000287 if (first == nullptr || second == nullptr) {
288 return false;
289 }
290 return first->applicationInfo.token != nullptr &&
291 first->applicationInfo.token == second->applicationInfo.token;
292}
293
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800294template <typename T>
295size_t firstMarkedBit(T set) {
296 // TODO: replace with std::countr_zero from <bit> when that's available
297 LOG_ALWAYS_FATAL_IF(set.none());
298 size_t i = 0;
299 while (!set.test(i)) {
300 i++;
301 }
302 return i;
303}
304
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800305std::unique_ptr<DispatchEntry> createDispatchEntry(
306 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
307 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700308 if (inputTarget.useDefaultPointerTransform()) {
309 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700310 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700311 inputTarget.displayTransform,
312 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000313 }
314
315 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
316 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
317
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700318 std::vector<PointerCoords> pointerCoords;
319 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000320
321 // Use the first pointer information to normalize all other pointers. This could be any pointer
322 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700323 // uses the transform for the normalized pointer.
324 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800325 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700326 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000327
328 // Iterate through all pointers in the event to normalize against the first.
329 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
330 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
331 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700332 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000333
334 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700335 // First, apply the current pointer's transform to update the coordinates into
336 // window space.
337 pointerCoords[pointerIndex].transform(currTransform);
338 // Next, apply the inverse transform of the normalized coordinates so the
339 // current coordinates are transformed into the normalized coordinate space.
340 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000341 }
342
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700343 std::unique_ptr<MotionEntry> combinedMotionEntry =
344 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
345 motionEntry.deviceId, motionEntry.source,
346 motionEntry.displayId, motionEntry.policyFlags,
347 motionEntry.action, motionEntry.actionButton,
348 motionEntry.flags, motionEntry.metaState,
349 motionEntry.buttonState, motionEntry.classification,
350 motionEntry.edgeFlags, motionEntry.xPrecision,
351 motionEntry.yPrecision, motionEntry.xCursorPosition,
352 motionEntry.yCursorPosition, motionEntry.downTime,
353 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000354 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000355
356 if (motionEntry.injectionState) {
357 combinedMotionEntry->injectionState = motionEntry.injectionState;
358 combinedMotionEntry->injectionState->refCount += 1;
359 }
360
361 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700362 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700363 firstPointerTransform, inputTarget.displayTransform,
364 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000365 return dispatchEntry;
366}
367
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000368status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
369 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700370 std::unique_ptr<InputChannel> uniqueServerChannel;
371 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
372
373 serverChannel = std::move(uniqueServerChannel);
374 return result;
375}
376
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500377template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000378bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500379 if (lhs == nullptr && rhs == nullptr) {
380 return true;
381 }
382 if (lhs == nullptr || rhs == nullptr) {
383 return false;
384 }
385 return *lhs == *rhs;
386}
387
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000388KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000389 KeyEvent event;
390 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
391 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
392 entry.repeatCount, entry.downTime, entry.eventTime);
393 return event;
394}
395
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000396bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000397 // Do not keep track of gesture monitors. They receive every event and would disproportionately
398 // affect the statistics.
399 if (connection.monitor) {
400 return false;
401 }
402 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
403 if (!connection.responsive) {
404 return false;
405 }
406 return true;
407}
408
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000409bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000410 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
411 const int32_t& inputEventId = eventEntry.id;
412 if (inputEventId != dispatchEntry.resolvedEventId) {
413 // Event was transmuted
414 return false;
415 }
416 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
417 return false;
418 }
419 // Only track latency for events that originated from hardware
420 if (eventEntry.isSynthesized()) {
421 return false;
422 }
423 const EventEntry::Type& inputEventEntryType = eventEntry.type;
424 if (inputEventEntryType == EventEntry::Type::KEY) {
425 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
426 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
427 return false;
428 }
429 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
430 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
431 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
432 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
433 return false;
434 }
435 } else {
436 // Not a key or a motion
437 return false;
438 }
439 if (!shouldReportMetricsForConnection(connection)) {
440 return false;
441 }
442 return true;
443}
444
Prabir Pradhancef936d2021-07-21 16:17:52 +0000445/**
446 * Connection is responsive if it has no events in the waitQueue that are older than the
447 * current time.
448 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000449bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000450 const nsecs_t currentTime = now();
451 for (const DispatchEntry* entry : connection.waitQueue) {
452 if (entry->timeoutTime < currentTime) {
453 return false;
454 }
455 }
456 return true;
457}
458
Antonio Kantekf16f2832021-09-28 04:39:20 +0000459// Returns true if the event type passed as argument represents a user activity.
460bool isUserActivityEvent(const EventEntry& eventEntry) {
461 switch (eventEntry.type) {
462 case EventEntry::Type::FOCUS:
463 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
464 case EventEntry::Type::DRAG:
465 case EventEntry::Type::TOUCH_MODE_CHANGED:
466 case EventEntry::Type::SENSOR:
467 case EventEntry::Type::CONFIGURATION_CHANGED:
468 return false;
469 case EventEntry::Type::DEVICE_RESET:
470 case EventEntry::Type::KEY:
471 case EventEntry::Type::MOTION:
472 return true;
473 }
474}
475
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800476// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000477bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000478 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800479 const auto inputConfig = windowInfo.inputConfig;
480 if (windowInfo.displayId != displayId ||
481 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800482 return false;
483 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700484 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800485 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800486 return false;
487 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000488
489 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
490 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
491 // the window. Points on the right and bottom edges should not be inside the window, so we need
492 // to be careful about performing a hit test when the display is rotated, since the "right" and
493 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
494 // logical display in which WM determined the bounds. Perform the hit test in the logical
495 // display space to ensure these edges are considered correctly in all orientations.
496 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
497 const auto p = displayTransform.transform(x, y);
498 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800499 return false;
500 }
501 return true;
502}
503
Prabir Pradhand65552b2021-10-07 11:23:50 -0700504bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
505 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000506 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700507}
508
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800509// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000510// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
511// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
512// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800513// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000514bool canReceiveForegroundTouches(const WindowInfo& info) {
515 // A non-touchable window can still receive touch events (e.g. in the case of
516 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
517 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
518}
519
Antonio Kantek48710e42022-03-24 14:19:30 -0700520bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
521 if (windowHandle == nullptr) {
522 return false;
523 }
524 const WindowInfo* windowInfo = windowHandle->getInfo();
525 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
526 return true;
527 }
528 return false;
529}
530
Prabir Pradhan5735a322022-04-11 17:23:34 +0000531// Checks targeted injection using the window's owner's uid.
532// Returns an empty string if an entry can be sent to the given window, or an error message if the
533// entry is a targeted injection whose uid target doesn't match the window owner.
534std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
535 const EventEntry& entry) {
536 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
537 // The event was not injected, or the injected event does not target a window.
538 return {};
539 }
540 const int32_t uid = *entry.injectionState->targetUid;
541 if (window == nullptr) {
542 return StringPrintf("No valid window target for injection into uid %d.", uid);
543 }
544 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
545 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
546 "owned by uid %d.",
547 uid, window->getName().c_str(), window->getInfo()->ownerUid);
548 }
549 return {};
550}
551
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000552std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700553 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
554 // Always dispatch mouse events to cursor position.
555 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000556 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700557 }
558
559 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000560 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
561 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700562}
563
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700564std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
565 if (eventEntry.type == EventEntry::Type::KEY) {
566 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
567 return keyEntry.downTime;
568 } else if (eventEntry.type == EventEntry::Type::MOTION) {
569 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
570 return motionEntry.downTime;
571 }
572 return std::nullopt;
573}
574
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000575/**
576 * Compare the old touch state to the new touch state, and generate the corresponding touched
577 * windows (== input targets).
578 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
579 * If the pointer just entered the new window, produce HOVER_ENTER.
580 * For pointers remaining in the window, produce HOVER_MOVE.
581 */
582std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
583 const TouchState& newTouchState,
584 const MotionEntry& entry) {
585 std::vector<TouchedWindow> out;
586 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
587 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
588 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
589 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
590 // Not a hover event - don't need to do anything
591 return out;
592 }
593
594 // We should consider all hovering pointers here. But for now, just use the first one
595 const int32_t pointerId = entry.pointerProperties[0].id;
596
597 std::set<sp<WindowInfoHandle>> oldWindows;
598 if (oldState != nullptr) {
599 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
600 }
601
602 std::set<sp<WindowInfoHandle>> newWindows =
603 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
604
605 // If the pointer is no longer in the new window set, send HOVER_EXIT.
606 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
607 if (newWindows.find(oldWindow) == newWindows.end()) {
608 TouchedWindow touchedWindow;
609 touchedWindow.windowHandle = oldWindow;
610 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800611 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000612 out.push_back(touchedWindow);
613 }
614 }
615
616 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
617 TouchedWindow touchedWindow;
618 touchedWindow.windowHandle = newWindow;
619 if (oldWindows.find(newWindow) == oldWindows.end()) {
620 // Any windows that have this pointer now, and didn't have it before, should get
621 // HOVER_ENTER
622 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
623 } else {
624 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700625 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
626 LOG(FATAL) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
627 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000628 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
629 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800630 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000631 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
632 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
633 }
634 out.push_back(touchedWindow);
635 }
636 return out;
637}
638
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800639template <typename T>
640std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
641 left.insert(left.end(), right.begin(), right.end());
642 return left;
643}
644
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000645} // namespace
646
Michael Wrightd02c5b62014-02-10 15:10:22 -0800647// --- InputDispatcher ---
648
Garfield Tan00f511d2019-06-12 16:55:40 -0700649InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800650 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
651
652InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
653 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700654 : mPolicy(policy),
655 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700656 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800657 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700658 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700659 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700660 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800661 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700662 mDispatchEnabled(false),
663 mDispatchFrozen(false),
664 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100665 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000666 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800667 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800668 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000669 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000670 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700671 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800672 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800673
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700674 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700675#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700676 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700677#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700678 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800679 policy->getDispatcherConfiguration(&mConfig);
680}
681
682InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000683 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800684
Prabir Pradhancef936d2021-07-21 16:17:52 +0000685 resetKeyRepeatLocked();
686 releasePendingEventLocked();
687 drainInboundQueueLocked();
688 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000690 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700691 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000692 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800693 }
694}
695
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700696status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700697 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700698 return ALREADY_EXISTS;
699 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700700 mThread = std::make_unique<InputThread>(
701 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
702 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700703}
704
705status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700706 if (mThread && mThread->isCallingThread()) {
707 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700708 return INVALID_OPERATION;
709 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700710 mThread.reset();
711 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700712}
713
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700715 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800717 std::scoped_lock _l(mLock);
718 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800719
720 // Run a dispatch loop if there are no pending commands.
721 // The dispatch loop might enqueue commands to run afterwards.
722 if (!haveCommandsLocked()) {
723 dispatchOnceInnerLocked(&nextWakeupTime);
724 }
725
726 // Run all pending commands if there are any.
727 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000728 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700729 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800730 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800731
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700732 // If we are still waiting for ack on some events,
733 // we might have to wake up earlier to check if an app is anr'ing.
734 const nsecs_t nextAnrCheck = processAnrsLocked();
735 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
736
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800737 // We are about to enter an infinitely long sleep, because we have no commands or
738 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700739 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800740 mDispatcherEnteredIdle.notify_all();
741 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742 } // release lock
743
744 // Wait for callback or timeout or wake. (make sure we round up, not down)
745 nsecs_t currentTime = now();
746 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
747 mLooper->pollOnce(timeoutMillis);
748}
749
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700750/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500751 * Raise ANR if there is no focused window.
752 * Before the ANR is raised, do a final state check:
753 * 1. The currently focused application must be the same one we are waiting for.
754 * 2. Ensure we still don't have a focused window.
755 */
756void InputDispatcher::processNoFocusedWindowAnrLocked() {
757 // Check if the application that we are waiting for is still focused.
758 std::shared_ptr<InputApplicationHandle> focusedApplication =
759 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
760 if (focusedApplication == nullptr ||
761 focusedApplication->getApplicationToken() !=
762 mAwaitedFocusedApplication->getApplicationToken()) {
763 // Unexpected because we should have reset the ANR timer when focused application changed
764 ALOGE("Waited for a focused window, but focused application has already changed to %s",
765 focusedApplication->getName().c_str());
766 return; // The focused application has changed.
767 }
768
chaviw98318de2021-05-19 16:45:23 -0500769 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500770 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
771 if (focusedWindowHandle != nullptr) {
772 return; // We now have a focused window. No need for ANR.
773 }
774 onAnrLocked(mAwaitedFocusedApplication);
775}
776
777/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700778 * Check if any of the connections' wait queues have events that are too old.
779 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
780 * Return the time at which we should wake up next.
781 */
782nsecs_t InputDispatcher::processAnrsLocked() {
783 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700784 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700785 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
786 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
787 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500788 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700789 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500790 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700791 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700792 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500793 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700794 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
795 }
796 }
797
798 // Check if any connection ANRs are due
799 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
800 if (currentTime < nextAnrCheck) { // most likely scenario
801 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
802 }
803
804 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700805 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700806 if (connection == nullptr) {
807 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
808 return nextAnrCheck;
809 }
810 connection->responsive = false;
811 // Stop waking up for this unresponsive connection
812 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000813 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700814 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700815}
816
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800817std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700818 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800819 if (connection->monitor) {
820 return mMonitorDispatchingTimeout;
821 }
822 const sp<WindowInfoHandle> window =
823 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700824 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500825 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700826 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500827 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700828}
829
Michael Wrightd02c5b62014-02-10 15:10:22 -0800830void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
831 nsecs_t currentTime = now();
832
Jeff Browndc5992e2014-04-11 01:27:26 -0700833 // Reset the key repeat timer whenever normal dispatch is suspended while the
834 // device is in a non-interactive state. This is to ensure that we abort a key
835 // repeat if the device is just coming out of sleep.
836 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837 resetKeyRepeatLocked();
838 }
839
840 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
841 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100842 if (DEBUG_FOCUS) {
843 ALOGD("Dispatch frozen. Waiting some more.");
844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845 return;
846 }
847
848 // Optimize latency of app switches.
849 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
850 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
851 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
852 if (mAppSwitchDueTime < *nextWakeupTime) {
853 *nextWakeupTime = mAppSwitchDueTime;
854 }
855
856 // Ready to start a new event.
857 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700858 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700859 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860 if (isAppSwitchDue) {
861 // The inbound queue is empty so the app switch key we were waiting
862 // for will never arrive. Stop waiting for it.
863 resetPendingAppSwitchLocked(false);
864 isAppSwitchDue = false;
865 }
866
867 // Synthesize a key repeat if appropriate.
868 if (mKeyRepeatState.lastKeyEntry) {
869 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
870 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
871 } else {
872 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
873 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
874 }
875 }
876 }
877
878 // Nothing to do if there is no pending event.
879 if (!mPendingEvent) {
880 return;
881 }
882 } else {
883 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700884 mPendingEvent = mInboundQueue.front();
885 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886 traceInboundQueueLengthLocked();
887 }
888
889 // Poke user activity for this event.
890 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700891 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893 }
894
895 // Now we have an event to dispatch.
896 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700897 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700899 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700901 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700903 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 }
905
906 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700907 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 }
909
910 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700911 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700912 const ConfigurationChangedEntry& typedEntry =
913 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700914 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700915 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700916 break;
917 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800918
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700919 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700920 const DeviceResetEntry& typedEntry =
921 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700922 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700923 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700924 break;
925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100927 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700928 std::shared_ptr<FocusEntry> typedEntry =
929 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100930 dispatchFocusLocked(currentTime, typedEntry);
931 done = true;
932 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
933 break;
934 }
935
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700936 case EventEntry::Type::TOUCH_MODE_CHANGED: {
937 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
938 dispatchTouchModeChangeLocked(currentTime, typedEntry);
939 done = true;
940 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
941 break;
942 }
943
Prabir Pradhan99987712020-11-10 18:43:05 -0800944 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
945 const auto typedEntry =
946 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
947 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
948 done = true;
949 break;
950 }
951
arthurhungb89ccb02020-12-30 16:19:01 +0800952 case EventEntry::Type::DRAG: {
953 std::shared_ptr<DragEntry> typedEntry =
954 std::static_pointer_cast<DragEntry>(mPendingEvent);
955 dispatchDragLocked(currentTime, typedEntry);
956 done = true;
957 break;
958 }
959
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700960 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700961 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700962 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700963 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700964 resetPendingAppSwitchLocked(true);
965 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700966 } else if (dropReason == DropReason::NOT_DROPPED) {
967 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700968 }
969 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700970 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700971 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700972 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700973 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
974 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700975 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700976 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700977 break;
978 }
979
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700980 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700981 std::shared_ptr<MotionEntry> motionEntry =
982 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700983 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
984 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700986 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700987 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700988 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700989 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
990 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700991 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700992 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700993 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 }
Chris Yef59a2f42020-10-16 12:55:26 -0700995
996 case EventEntry::Type::SENSOR: {
997 std::shared_ptr<SensorEntry> sensorEntry =
998 std::static_pointer_cast<SensorEntry>(mPendingEvent);
999 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1000 dropReason = DropReason::APP_SWITCH;
1001 }
1002 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1003 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1004 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1005 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1006 dropReason = DropReason::STALE;
1007 }
1008 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1009 done = true;
1010 break;
1011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012 }
1013
1014 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001015 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001016 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 }
Michael Wright3a981722015-06-10 15:26:13 +01001018 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001019
1020 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001021 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001022 }
1023}
1024
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001025bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1026 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1027}
1028
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001029/**
1030 * Return true if the events preceding this incoming motion event should be dropped
1031 * Return false otherwise (the default behaviour)
1032 */
1033bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001034 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001035 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001036
1037 // Optimize case where the current application is unresponsive and the user
1038 // decides to touch a window in a different application.
1039 // If the application takes too long to catch up then we drop all events preceding
1040 // the touch into the other window.
1041 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001042 const int32_t displayId = motionEntry.displayId;
1043 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001044 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001045
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001046 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001047 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001048 touchedWindowHandle->getApplicationToken() !=
1049 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001050 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001051 ALOGI("Pruning input queue because user touched a different application while waiting "
1052 "for %s",
1053 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001054 return true;
1055 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001056
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001057 // Alternatively, maybe there's a spy window that could handle this event.
1058 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1059 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1060 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001061 const std::shared_ptr<Connection> connection =
1062 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001063 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001064 // This spy window could take more input. Drop all events preceding this
1065 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001066 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001067 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001068 mAwaitedFocusedApplication->getName().c_str());
1069 return true;
1070 }
1071 }
1072 }
1073
1074 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1075 // yet been processed by some connections, the dispatcher will wait for these motion
1076 // events to be processed before dispatching the key event. This is because these motion events
1077 // may cause a new window to be launched, which the user might expect to receive focus.
1078 // To prevent waiting forever for such events, just send the key to the currently focused window
1079 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1080 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1081 "just send the pending key event to the focused window.");
1082 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001083 }
1084 return false;
1085}
1086
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001087bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001088 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001089 mInboundQueue.push_back(std::move(newEntry));
1090 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091 traceInboundQueueLengthLocked();
1092
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001093 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001094 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001095 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1096 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001097 // Optimize app switch latency.
1098 // If the application takes too long to catch up then we drop all events preceding
1099 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001100 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001101 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001102 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001103 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001104 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001105 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001106 if (DEBUG_APP_SWITCH) {
1107 ALOGD("App switch is pending!");
1108 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001109 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001110 mAppSwitchSawKeyDown = false;
1111 needWake = true;
1112 }
1113 }
1114 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001115
1116 // If a new up event comes in, and the pending event with same key code has been asked
1117 // to try again later because of the policy. We have to reset the intercept key wake up
1118 // time for it may have been handled in the policy and could be dropped.
1119 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1120 mPendingEvent->type == EventEntry::Type::KEY) {
1121 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1122 if (pendingKey.keyCode == keyEntry.keyCode &&
1123 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001124 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1125 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001126 pendingKey.interceptKeyWakeupTime = 0;
1127 needWake = true;
1128 }
1129 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001130 break;
1131 }
1132
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001133 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001134 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1135 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001136 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1137 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001138 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001140 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001142 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001143 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1144 break;
1145 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001146 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001147 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001148 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001149 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001150 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1151 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001152 // nothing to do
1153 break;
1154 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155 }
1156
1157 return needWake;
1158}
1159
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001160void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001161 // Do not store sensor event in recent queue to avoid flooding the queue.
1162 if (entry->type != EventEntry::Type::SENSOR) {
1163 mRecentQueue.push_back(entry);
1164 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001165 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001166 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167 }
1168}
1169
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001170std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001171InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001172 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001174 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001175 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001176 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001177 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001178 continue;
1179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001181 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001182 if (!info.isSpy() &&
1183 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001184 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001185 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001186
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001187 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1188 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001189 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001190 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 }
1192 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001193 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194}
1195
Prabir Pradhand65552b2021-10-07 11:23:50 -07001196std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001197 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001198 // Traverse windows from front to back and gather the touched spy windows.
1199 std::vector<sp<WindowInfoHandle>> spyWindows;
1200 const auto& windowHandles = getWindowHandlesLocked(displayId);
1201 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1202 const WindowInfo& info = *windowHandle->getInfo();
1203
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001204 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001205 continue;
1206 }
1207 if (!info.isSpy()) {
1208 // The first touched non-spy window was found, so return the spy windows touched so far.
1209 return spyWindows;
1210 }
1211 spyWindows.push_back(windowHandle);
1212 }
1213 return spyWindows;
1214}
1215
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001216void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 const char* reason;
1218 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001219 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001220 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001221 ALOGD("Dropped event because policy consumed it.");
1222 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001223 reason = "inbound event was dropped because the policy consumed it";
1224 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001225 case DropReason::DISABLED:
1226 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001227 ALOGI("Dropped event because input dispatch is disabled.");
1228 }
1229 reason = "inbound event was dropped because input dispatch is disabled";
1230 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001231 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001232 ALOGI("Dropped event because of pending overdue app switch.");
1233 reason = "inbound event was dropped because of pending overdue app switch";
1234 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001235 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001236 ALOGI("Dropped event because the current application is not responding and the user "
1237 "has started interacting with a different application.");
1238 reason = "inbound event was dropped because the current application is not responding "
1239 "and the user has started interacting with a different application";
1240 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001241 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001242 ALOGI("Dropped event because it is stale.");
1243 reason = "inbound event was dropped because it is stale";
1244 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001245 case DropReason::NO_POINTER_CAPTURE:
1246 ALOGI("Dropped event because there is no window with Pointer Capture.");
1247 reason = "inbound event was dropped because there is no window with Pointer Capture";
1248 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001249 case DropReason::NOT_DROPPED: {
1250 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001251 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253 }
1254
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001255 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001256 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001257 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001259 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001261 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001262 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1263 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001264 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001265 synthesizeCancelationEventsForAllConnectionsLocked(options);
1266 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001267 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1268 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001269 synthesizeCancelationEventsForAllConnectionsLocked(options);
1270 }
1271 break;
1272 }
Chris Yef59a2f42020-10-16 12:55:26 -07001273 case EventEntry::Type::SENSOR: {
1274 break;
1275 }
arthurhungb89ccb02020-12-30 16:19:01 +08001276 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1277 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001278 break;
1279 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001280 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001281 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001282 case EventEntry::Type::CONFIGURATION_CHANGED:
1283 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001284 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001285 break;
1286 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001287 }
1288}
1289
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001290static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001291 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1292 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293}
1294
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001295bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1296 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1297 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1298 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299}
1300
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001301bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001302 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303}
1304
1305void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001306 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001308 if (DEBUG_APP_SWITCH) {
1309 if (handled) {
1310 ALOGD("App switch has arrived.");
1311 } else {
1312 ALOGD("App switch was abandoned.");
1313 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001314 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315}
1316
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001318 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001319}
1320
Prabir Pradhancef936d2021-07-21 16:17:52 +00001321bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001322 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 return false;
1324 }
1325
1326 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001327 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001328 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001329 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1330 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001331 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332 return true;
1333}
1334
Prabir Pradhancef936d2021-07-21 16:17:52 +00001335void InputDispatcher::postCommandLocked(Command&& command) {
1336 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337}
1338
1339void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001340 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001341 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001342 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343 releaseInboundEventLocked(entry);
1344 }
1345 traceInboundQueueLengthLocked();
1346}
1347
1348void InputDispatcher::releasePendingEventLocked() {
1349 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001350 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001351 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352 }
1353}
1354
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001355void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001357 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001358 if (DEBUG_DISPATCH_CYCLE) {
1359 ALOGD("Injected inbound event was dropped.");
1360 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001361 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 }
1363 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001364 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365 }
1366 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001367}
1368
1369void InputDispatcher::resetKeyRepeatLocked() {
1370 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001371 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001372 }
1373}
1374
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001375std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1376 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377
Michael Wright2e732952014-09-24 13:26:59 -07001378 uint32_t policyFlags = entry->policyFlags &
1379 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001381 std::shared_ptr<KeyEntry> newEntry =
1382 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1383 entry->source, entry->displayId, policyFlags, entry->action,
1384 entry->flags, entry->keyCode, entry->scanCode,
1385 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001387 newEntry->syntheticRepeat = true;
1388 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001390 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001391}
1392
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001393bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001394 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001395 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1396 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1397 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001398
1399 // Reset key repeating in case a keyboard device was added or removed or something.
1400 resetKeyRepeatLocked();
1401
1402 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001403 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1404 scoped_unlock unlock(mLock);
1405 mPolicy->notifyConfigurationChanged(eventTime);
1406 };
1407 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408 return true;
1409}
1410
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001411bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1412 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001413 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1414 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1415 entry.deviceId);
1416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417
liushenxiang42232912021-05-21 20:24:09 +08001418 // Reset key repeating in case a keyboard device was disabled or enabled.
1419 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1420 resetKeyRepeatLocked();
1421 }
1422
Michael Wrightfb04fd52022-11-24 22:31:11 +00001423 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001424 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001425 synthesizeCancelationEventsForAllConnectionsLocked(options);
1426 return true;
1427}
1428
Vishnu Nairad321cd2020-08-20 16:40:21 -07001429void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001430 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001431 if (mPendingEvent != nullptr) {
1432 // Move the pending event to the front of the queue. This will give the chance
1433 // for the pending event to get dispatched to the newly focused window
1434 mInboundQueue.push_front(mPendingEvent);
1435 mPendingEvent = nullptr;
1436 }
1437
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001438 std::unique_ptr<FocusEntry> focusEntry =
1439 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1440 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001441
1442 // This event should go to the front of the queue, but behind all other focus events
1443 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001444 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001445 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001446 [](const std::shared_ptr<EventEntry>& event) {
1447 return event->type == EventEntry::Type::FOCUS;
1448 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001449
1450 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001451 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001452}
1453
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001454void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001455 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001456 if (channel == nullptr) {
1457 return; // Window has gone away
1458 }
1459 InputTarget target;
1460 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001461 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001462 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001463 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1464 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001465 std::string reason = std::string("reason=").append(entry->reason);
1466 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001467 dispatchEventLocked(currentTime, entry, {target});
1468}
1469
Prabir Pradhan99987712020-11-10 18:43:05 -08001470void InputDispatcher::dispatchPointerCaptureChangedLocked(
1471 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1472 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001473 dropReason = DropReason::NOT_DROPPED;
1474
Prabir Pradhan99987712020-11-10 18:43:05 -08001475 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001476 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001477
1478 if (entry->pointerCaptureRequest.enable) {
1479 // Enable Pointer Capture.
1480 if (haveWindowWithPointerCapture &&
1481 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001482 // This can happen if pointer capture is disabled and re-enabled before we notify the
1483 // app of the state change, so there is no need to notify the app.
1484 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1485 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001486 }
1487 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001488 // This can happen if a window requests capture and immediately releases capture.
1489 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001490 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001491 return;
1492 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001493 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1494 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1495 return;
1496 }
1497
Vishnu Nairc519ff72021-01-21 08:23:08 -08001498 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001499 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1500 mWindowTokenWithPointerCapture = token;
1501 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001502 // Disable Pointer Capture.
1503 // We do not check if the sequence number matches for requests to disable Pointer Capture
1504 // for two reasons:
1505 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1506 // to disable capture with the same sequence number: one generated by
1507 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1508 // Capture being disabled in InputReader.
1509 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1510 // actual Pointer Capture state that affects events being generated by input devices is
1511 // in InputReader.
1512 if (!haveWindowWithPointerCapture) {
1513 // Pointer capture was already forcefully disabled because of focus change.
1514 dropReason = DropReason::NOT_DROPPED;
1515 return;
1516 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001517 token = mWindowTokenWithPointerCapture;
1518 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001519 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001520 setPointerCaptureLocked(false);
1521 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001522 }
1523
1524 auto channel = getInputChannelLocked(token);
1525 if (channel == nullptr) {
1526 // Window has gone away, clean up Pointer Capture state.
1527 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001528 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001529 setPointerCaptureLocked(false);
1530 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001531 return;
1532 }
1533 InputTarget target;
1534 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001535 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001536 entry->dispatchInProgress = true;
1537 dispatchEventLocked(currentTime, entry, {target});
1538
1539 dropReason = DropReason::NOT_DROPPED;
1540}
1541
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001542void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1543 const std::shared_ptr<TouchModeEntry>& entry) {
1544 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001545 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001546 if (windowHandles.empty()) {
1547 return;
1548 }
1549 const std::vector<InputTarget> inputTargets =
1550 getInputTargetsFromWindowHandlesLocked(windowHandles);
1551 if (inputTargets.empty()) {
1552 return;
1553 }
1554 entry->dispatchInProgress = true;
1555 dispatchEventLocked(currentTime, entry, inputTargets);
1556}
1557
1558std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1559 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1560 std::vector<InputTarget> inputTargets;
1561 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001562 const sp<IBinder>& token = handle->getToken();
1563 if (token == nullptr) {
1564 continue;
1565 }
1566 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1567 if (channel == nullptr) {
1568 continue; // Window has gone away
1569 }
1570 InputTarget target;
1571 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001572 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001573 inputTargets.push_back(target);
1574 }
1575 return inputTargets;
1576}
1577
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001578bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001579 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001581 if (!entry->dispatchInProgress) {
1582 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1583 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1584 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1585 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001586 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 // We have seen two identical key downs in a row which indicates that the device
1588 // driver is automatically generating key repeats itself. We take note of the
1589 // repeat here, but we disable our own next key repeat timer since it is clear that
1590 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001591 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1592 // Make sure we don't get key down from a different device. If a different
1593 // device Id has same key pressed down, the new device Id will replace the
1594 // current one to hold the key repeat with repeat count reset.
1595 // In the future when got a KEY_UP on the device id, drop it and do not
1596 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1598 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001599 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 } else {
1601 // Not a repeat. Save key down state in case we do see a repeat later.
1602 resetKeyRepeatLocked();
1603 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1604 }
1605 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001606 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1607 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001608 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001609 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001610 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1611 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001612 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613 resetKeyRepeatLocked();
1614 }
1615
1616 if (entry->repeatCount == 1) {
1617 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1618 } else {
1619 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1620 }
1621
1622 entry->dispatchInProgress = true;
1623
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001624 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625 }
1626
1627 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001628 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629 if (currentTime < entry->interceptKeyWakeupTime) {
1630 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1631 *nextWakeupTime = entry->interceptKeyWakeupTime;
1632 }
1633 return false; // wait until next wakeup
1634 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001635 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 entry->interceptKeyWakeupTime = 0;
1637 }
1638
1639 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001640 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001642 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001643 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001644
1645 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1646 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1647 };
1648 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 return false; // wait for the command to run
1650 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001651 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001653 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001654 if (*dropReason == DropReason::NOT_DROPPED) {
1655 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656 }
1657 }
1658
1659 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001660 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001661 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001662 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1663 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001664 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665 return true;
1666 }
1667
1668 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001669 InputEventInjectionResult injectionResult;
1670 sp<WindowInfoHandle> focusedWindow =
1671 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1672 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001673 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 return false;
1675 }
1676
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001677 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001678 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679 return true;
1680 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001681 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1682
1683 std::vector<InputTarget> inputTargets;
1684 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001685 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001686 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001687
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001688 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001689 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690
1691 // Dispatch the key.
1692 dispatchEventLocked(currentTime, entry, inputTargets);
1693 return true;
1694}
1695
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001696void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001697 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1698 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1699 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1700 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1701 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1702 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1703 entry.metaState, entry.repeatCount, entry.downTime);
1704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001705}
1706
Prabir Pradhancef936d2021-07-21 16:17:52 +00001707void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1708 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001709 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001710 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1711 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1712 "source=0x%x, sensorType=%s",
1713 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001714 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001715 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001716 auto command = [this, entry]() REQUIRES(mLock) {
1717 scoped_unlock unlock(mLock);
1718
1719 if (entry->accuracyChanged) {
1720 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1721 }
1722 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1723 entry->hwTimestamp, entry->values);
1724 };
1725 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001726}
1727
1728bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001729 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1730 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001731 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001732 }
Chris Yef59a2f42020-10-16 12:55:26 -07001733 { // acquire lock
1734 std::scoped_lock _l(mLock);
1735
1736 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1737 std::shared_ptr<EventEntry> entry = *it;
1738 if (entry->type == EventEntry::Type::SENSOR) {
1739 it = mInboundQueue.erase(it);
1740 releaseInboundEventLocked(entry);
1741 }
1742 }
1743 }
1744 return true;
1745}
1746
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001747bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001748 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001749 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001751 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752 entry->dispatchInProgress = true;
1753
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001754 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 }
1756
1757 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001758 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001759 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001760 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1761 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762 return true;
1763 }
1764
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001765 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766
1767 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001768 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769
1770 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001771 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772 if (isPointerEvent) {
1773 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001774
1775 if (mDragState &&
1776 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1777 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1778 pilferPointersLocked(mDragState->dragWindow->getToken());
1779 }
1780
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001781 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001782 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001783 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001784 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1785 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001786 } else {
1787 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001788 sp<WindowInfoHandle> focusedWindow =
1789 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1790 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1791 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1792 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001793 InputTarget::Flags::FOREGROUND |
1794 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001795 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001796 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001798 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 return false;
1800 }
1801
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001802 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001803 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001804 return true;
1805 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001806 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001807 CancelationOptions::Mode mode(
1808 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1809 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001810 CancelationOptions options(mode, "input event injection failed");
1811 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 return true;
1813 }
1814
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001815 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001816 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001817
1818 // Dispatch the motion.
1819 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001820 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001821 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 synthesizeCancelationEventsForAllConnectionsLocked(options);
1823 }
1824 dispatchEventLocked(currentTime, entry, inputTargets);
1825 return true;
1826}
1827
chaviw98318de2021-05-19 16:45:23 -05001828void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001829 bool isExiting, const int32_t rawX,
1830 const int32_t rawY) {
1831 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001832 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001833 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1834 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001835
1836 enqueueInboundEventLocked(std::move(dragEntry));
1837}
1838
1839void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1840 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1841 if (channel == nullptr) {
1842 return; // Window has gone away
1843 }
1844 InputTarget target;
1845 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001846 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001847 entry->dispatchInProgress = true;
1848 dispatchEventLocked(currentTime, entry, {target});
1849}
1850
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001851void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001852 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001853 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001854 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001855 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001856 "metaState=0x%x, buttonState=0x%x,"
1857 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001858 prefix, entry.eventTime, entry.deviceId,
1859 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1860 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1861 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1862 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001864 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001865 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001866 "x=%f, y=%f, pressure=%f, size=%f, "
1867 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1868 "orientation=%f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001869 i, entry.pointerProperties[i].id,
1870 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001871 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1872 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1873 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1874 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1875 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1876 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1877 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1878 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1879 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1880 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882}
1883
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001884void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1885 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001886 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001887 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001888 if (DEBUG_DISPATCH_CYCLE) {
1889 ALOGD("dispatchEventToCurrentInputTargets");
1890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001891
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001892 updateInteractionTokensLocked(*eventEntry, inputTargets);
1893
Michael Wrightd02c5b62014-02-10 15:10:22 -08001894 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1895
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001896 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001898 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001899 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001900 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001901 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001902 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001904 if (DEBUG_FOCUS) {
1905 ALOGD("Dropping event delivery to target with channel '%s' because it "
1906 "is no longer registered with the input dispatcher.",
1907 inputTarget.inputChannel->getName().c_str());
1908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909 }
1910 }
1911}
1912
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001913void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001914 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1915 // If the policy decides to close the app, we will get a channel removal event via
1916 // unregisterInputChannel, and will clean up the connection that way. We are already not
1917 // sending new pointers to the connection when it blocked, but focused events will continue to
1918 // pile up.
1919 ALOGW("Canceling events for %s because it is unresponsive",
1920 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001921 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001922 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001923 "application not responding");
1924 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 }
1926}
1927
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001928void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001929 if (DEBUG_FOCUS) {
1930 ALOGD("Resetting ANR timeouts.");
1931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932
1933 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001934 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001935 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936}
1937
Tiger Huang721e26f2018-07-24 22:26:19 +08001938/**
1939 * Get the display id that the given event should go to. If this event specifies a valid display id,
1940 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1941 * Focused display is the display that the user most recently interacted with.
1942 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001943int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001944 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001945 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001946 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001947 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1948 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001949 break;
1950 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001951 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001952 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1953 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001954 break;
1955 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001956 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001957 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001958 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001959 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001960 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001961 case EventEntry::Type::SENSOR:
1962 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001963 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001964 return ADISPLAY_ID_NONE;
1965 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001966 }
1967 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1968}
1969
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001970bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1971 const char* focusedWindowName) {
1972 if (mAnrTracker.empty()) {
1973 // already processed all events that we waited for
1974 mKeyIsWaitingForEventsTimeout = std::nullopt;
1975 return false;
1976 }
1977
1978 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1979 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001980 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001981 mKeyIsWaitingForEventsTimeout = currentTime +
1982 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1983 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001984 return true;
1985 }
1986
1987 // We still have pending events, and already started the timer
1988 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1989 return true; // Still waiting
1990 }
1991
1992 // Waited too long, and some connection still hasn't processed all motions
1993 // Just send the key to the focused window
1994 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1995 focusedWindowName);
1996 mKeyIsWaitingForEventsTimeout = std::nullopt;
1997 return false;
1998}
1999
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002000sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2001 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2002 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002003 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002004 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005
Tiger Huang721e26f2018-07-24 22:26:19 +08002006 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002007 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002008 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002009 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2010
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011 // If there is no currently focused window and no focused application
2012 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002013 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2014 ALOGI("Dropping %s event because there is no focused window or focused application in "
2015 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002016 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002017 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018 }
2019
Vishnu Nair062a8672021-09-03 16:07:44 -07002020 // Drop key events if requested by input feature
2021 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002022 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002023 }
2024
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002025 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2026 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2027 // start interacting with another application via touch (app switch). This code can be removed
2028 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2029 // an app is expected to have a focused window.
2030 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2031 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2032 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002033 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2034 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2035 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002036 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002037 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002038 ALOGW("Waiting because no window has focus but %s may eventually add a "
2039 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002040 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002041 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002042 outInjectionResult = InputEventInjectionResult::PENDING;
2043 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002044 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2045 // Already raised ANR. Drop the event
2046 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002047 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002048 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002049 } else {
2050 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002051 outInjectionResult = InputEventInjectionResult::PENDING;
2052 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002053 }
2054 }
2055
2056 // we have a valid, non-null focused window
2057 resetNoFocusedWindowTimeoutLocked();
2058
Prabir Pradhan5735a322022-04-11 17:23:34 +00002059 // Verify targeted injection.
2060 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2061 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002062 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2063 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 }
2065
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002066 if (focusedWindowHandle->getInfo()->inputConfig.test(
2067 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002068 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002069 outInjectionResult = InputEventInjectionResult::PENDING;
2070 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002071 }
2072
2073 // If the event is a key event, then we must wait for all previous events to
2074 // complete before delivering it because previous events may have the
2075 // side-effect of transferring focus to a different window and we want to
2076 // ensure that the following keys are sent to the new window.
2077 //
2078 // Suppose the user touches a button in a window then immediately presses "A".
2079 // If the button causes a pop-up window to appear then we want to ensure that
2080 // the "A" key is delivered to the new pop-up window. This is because users
2081 // often anticipate pending UI changes when typing on a keyboard.
2082 // To obtain this behavior, we must serialize key events with respect to all
2083 // prior input events.
2084 if (entry.type == EventEntry::Type::KEY) {
2085 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2086 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002087 outInjectionResult = InputEventInjectionResult::PENDING;
2088 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090 }
2091
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002092 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2093 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094}
2095
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002096/**
2097 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2098 * that are currently unresponsive.
2099 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002100std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2101 const std::vector<Monitor>& monitors) const {
2102 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002103 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002104 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002105 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002106 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002107 if (connection == nullptr) {
2108 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002109 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002110 return false;
2111 }
2112 if (!connection->responsive) {
2113 ALOGW("Unresponsive monitor %s will not get the new gesture",
2114 connection->inputChannel->getName().c_str());
2115 return false;
2116 }
2117 return true;
2118 });
2119 return responsiveMonitors;
2120}
2121
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002122/**
2123 * In general, touch should be always split between windows. Some exceptions:
2124 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2125 * from the same device, *and* the window that's receiving the current pointer does not support
2126 * split touch.
2127 * 2. Don't split mouse events
2128 */
2129bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2130 const MotionEntry& entry) const {
2131 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2132 // We should never split mouse events
2133 return false;
2134 }
2135 for (const TouchedWindow& touchedWindow : touchState.windows) {
2136 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2137 // Spy windows should not affect whether or not touch is split.
2138 continue;
2139 }
2140 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2141 continue;
2142 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002143 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2144 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2145 // Wallpaper window should not affect whether or not touch is split
2146 continue;
2147 }
2148
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002149 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2150 // being sent there. For now, use deviceId from touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002151 if (entry.deviceId == touchState.deviceId && touchedWindow.pointerIds.any()) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002152 return false;
2153 }
2154 }
2155 return true;
2156}
2157
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002158std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002159 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2160 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002161 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002163 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164 // For security reasons, we defer updating the touch state until we are sure that
2165 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002166 const int32_t displayId = entry.displayId;
2167 const int32_t action = entry.action;
2168 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169
2170 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002171 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002173 // Copy current touch state into tempTouchState.
2174 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2175 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002176 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002177 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002178 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2179 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002180 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002181 }
2182
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002183 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002184 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002185 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002186
2187 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2188 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2189 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002190 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2191 // touchable windows.
2192 const bool wasDown = oldState != nullptr && oldState->isDown();
2193 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2194 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
2195 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002196 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002197
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002198 // If pointers are already down, let's finish the current gesture and ignore the new events
2199 // from another device. However, if the new event is a down event, let's cancel the current
2200 // touch and let the new one take over.
2201 if (switchedDevice && wasDown && !isDown) {
2202 LOG(INFO) << "Dropping event because a pointer for device " << oldState->deviceId
2203 << " is already down in display " << displayId << ": " << entry.getDescription();
2204 // TODO(b/211379801): test multiple simultaneous input streams.
2205 outInjectionResult = InputEventInjectionResult::FAILED;
2206 return {}; // wrong device
2207 }
2208
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002210 // If a new gesture is starting, clear the touch state completely.
2211 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002212 tempTouchState.deviceId = entry.deviceId;
2213 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002215 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002216 ALOGI("Dropping move event because a pointer for a different device is already active "
2217 "in display %" PRId32,
2218 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002219 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002220 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002221 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222 }
2223
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002224 if (isHoverAction) {
2225 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2226 // all of the existing hovering pointers and recompute.
2227 tempTouchState.clearHoveringPointers();
2228 }
2229
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2231 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002232 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002233 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002234 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2235 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002236 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002237 auto [newTouchedWindowHandle, outsideTargets] =
2238 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002239
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002240 if (isDown) {
2241 targets += outsideTargets;
2242 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002244 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002245 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002247 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002248 }
2249
Prabir Pradhan5735a322022-04-11 17:23:34 +00002250 // Verify targeted injection.
2251 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2252 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002253 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002254 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002255 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002256 }
2257
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002258 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002259 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002260 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2261 // New window supports splitting, but we should never split mouse events.
2262 isSplit = !isFromMouse;
2263 } else if (isSplit) {
2264 // New window does not support splitting but we have already split events.
2265 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002266 newTouchedWindowHandle = nullptr;
2267 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002268 } else {
2269 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002270 // be delivered to a new window which supports split touch. Pointers from a mouse device
2271 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002272 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002273 }
2274
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002275 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002276 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002277 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002278 // Process the foreground window first so that it is the first to receive the event.
2279 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002280 }
2281
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002282 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002283 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2284 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002285 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002286 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002287 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002288 }
2289
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002290 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002291 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002292 continue;
2293 }
2294
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002295 if (isHoverAction) {
2296 const int32_t pointerId = entry.pointerProperties[0].id;
2297 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2298 // Pointer left. Remove it
2299 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2300 } else {
2301 // The "windowHandle" is the target of this hovering pointer.
2302 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId,
2303 pointerId);
2304 }
2305 }
2306
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002307 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002308 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002309
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002310 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2311 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002312 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002313 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002314
2315 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002316 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002317 }
2318 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002319 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002320 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002321 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002322 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002323
2324 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002325 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002326 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002327 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002328 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002329
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002330 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2331 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2332
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002333 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2334 // still add a window to the touch state. We should avoid doing that, but some of the
2335 // later checks ("at least one foreground window") rely on this in order to dispatch
2336 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002337 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002338 isDownOrPointerDown
2339 ? std::make_optional(entry.eventTime)
2340 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002341
2342 // If this is the pointer going down and the touched window has a wallpaper
2343 // then also add the touched wallpaper windows so they are locked in for the duration
2344 // of the touch gesture.
2345 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2346 // engine only supports touch events. We would need to add a mechanism similar
2347 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002348 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002349 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2350 windowHandle->getInfo()->inputConfig.test(
2351 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2352 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2353 if (wallpaper != nullptr) {
2354 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2355 InputTarget::Flags::WINDOW_IS_OBSCURED |
2356 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2357 InputTarget::Flags::DISPATCH_AS_IS;
2358 if (isSplit) {
2359 wallpaperFlags |= InputTarget::Flags::SPLIT;
2360 }
2361 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2362 entry.eventTime);
2363 }
2364 }
2365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002367
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002368 // If a window is already pilfering some pointers, give it this new pointer as well and
2369 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2370 // which is a specific behaviour that we want.
2371 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2372 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002373 if (touchedWindow.pointerIds.test(pointerId) &&
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002374 touchedWindow.pilferedPointerIds.count() > 0) {
2375 // This window is already pilfering some pointers, and this new pointer is also
2376 // going to it. Therefore, take over this pointer and don't give it to anyone
2377 // else.
2378 touchedWindow.pilferedPointerIds.set(pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002379 }
2380 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002381
2382 // Restrict all pilfered pointers to the pilfering windows.
2383 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384 } else {
2385 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2386
2387 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002388 if (!tempTouchState.isDown()) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002389 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2390 "dropped the pointer down event in display "
2391 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002392 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002393 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 }
2395
arthurhung6d4bed92021-03-17 11:59:33 +08002396 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002397
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002399 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002400 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002401 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002402 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002403 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002404 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002405 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002406
Prabir Pradhan5735a322022-04-11 17:23:34 +00002407 // Verify targeted injection.
2408 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2409 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002410 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002411 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002412 }
2413
Vishnu Nair062a8672021-09-03 16:07:44 -07002414 // Drop touch events if requested by input feature
2415 if (newTouchedWindowHandle != nullptr &&
2416 shouldDropInput(entry, newTouchedWindowHandle)) {
2417 newTouchedWindowHandle = nullptr;
2418 }
2419
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002420 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2421 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002422 if (DEBUG_FOCUS) {
2423 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2424 oldTouchedWindowHandle->getName().c_str(),
2425 newTouchedWindowHandle->getName().c_str(), displayId);
2426 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002427 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002428 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002429 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002430 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002431
2432 const TouchedWindow& touchedWindow =
2433 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2434 addWindowTargetLocked(oldTouchedWindowHandle,
2435 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
2436 touchedWindow.firstDownTimeInTarget, targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437
2438 // Make a slippery entrance into the new window.
2439 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002440 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441 }
2442
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002443 ftl::Flags<InputTarget::Flags> targetFlags =
2444 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002445 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002446 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002447 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002449 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002450 }
2451 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002452 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002453 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002454 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002455 }
2456
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002457 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2458 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002459
2460 // Check if the wallpaper window should deliver the corresponding event.
2461 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002462 tempTouchState, pointerId, targets);
2463 tempTouchState.removeTouchedPointerFromWindow(pointerId, oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464 }
2465 }
Arthur Hung96483742022-11-15 03:30:48 +00002466
2467 // Update the pointerIds for non-splittable when it received pointer down.
2468 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2469 // If no split, we suppose all touched windows should receive pointer down.
2470 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2471 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2472 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2473 // Ignore drag window for it should just track one pointer.
2474 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2475 continue;
2476 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002477 touchedWindow.pointerIds.set(entry.pointerProperties[pointerIndex].id);
Arthur Hung96483742022-11-15 03:30:48 +00002478 }
2479 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002480 }
2481
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002482 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002483 {
2484 std::vector<TouchedWindow> hoveringWindows =
2485 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2486 for (const TouchedWindow& touchedWindow : hoveringWindows) {
2487 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2488 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2489 targets);
2490 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491 }
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002492 // Ensure that we have at least one foreground window or at least one window that cannot be a
2493 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2494 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2495 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002496 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2497 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002498 return !canReceiveForegroundTouches(
2499 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002500 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002501 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002502 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2503 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002504 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002505 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002506 }
2507
Prabir Pradhan5735a322022-04-11 17:23:34 +00002508 // Ensure that all touched windows are valid for injection.
2509 if (entry.injectionState != nullptr) {
2510 std::string errs;
2511 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002512 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002513 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2514 // dispatched to any uid, since the coords will be zeroed out later.
2515 continue;
2516 }
2517 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2518 if (err) errs += "\n - " + *err;
2519 }
2520 if (!errs.empty()) {
2521 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2522 "%d:%s",
2523 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002524 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002525 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002526 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002527 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002528
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002529 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2530 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002531 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002532 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002533 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002534 if (foregroundWindowHandle) {
2535 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002536 for (InputTarget& target : targets) {
2537 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2538 sp<WindowInfoHandle> targetWindow =
2539 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2540 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2541 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002543 }
2544 }
2545 }
2546 }
2547
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002548 // Success! Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002549 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002550 if (touchedWindow.pointerIds.none() && !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002551 // Windows with hovering pointers are getting persisted inside TouchState.
2552 // Do not send this event to those windows.
2553 continue;
2554 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002555 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2556 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2557 targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002558 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002559
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002560 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002561 // Drop the outside or hover touch windows since we will not care about them
2562 // in the next iteration.
2563 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002566 if (switchedDevice) {
2567 if (DEBUG_FOCUS) {
2568 ALOGD("Conflicting pointer actions: Switched to a different device.");
2569 }
2570 *outConflictingPointerActions = true;
2571 }
2572
2573 if (isHoverAction) {
2574 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002575 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002576 ALOGD_IF(DEBUG_FOCUS,
2577 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002578 *outConflictingPointerActions = true;
2579 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002580 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2581 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2582 tempTouchState.deviceId = entry.deviceId;
2583 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002584 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002585 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2586 // Pointer went up.
2587 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002588 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002589 // All pointers up or canceled.
2590 tempTouchState.reset();
2591 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2592 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002593 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2594 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002595 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002596 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002597 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2598 // One pointer went up.
2599 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2600 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002601
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002602 for (size_t i = 0; i < tempTouchState.windows.size();) {
2603 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002604 touchedWindow.pointerIds.reset(pointerId);
2605 if (touchedWindow.pointerIds.none()) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002606 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2607 continue;
2608 }
2609 i += 1;
2610 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002611 }
2612
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002613 // Save changes unless the action was scroll in which case the temporary touch
2614 // state was only valid for this one action.
2615 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002616 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002617 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002618 mTouchStatesByDisplay[displayId] = tempTouchState;
2619 } else {
2620 mTouchStatesByDisplay.erase(displayId);
2621 }
2622 }
2623
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002624 if (tempTouchState.windows.empty()) {
2625 mTouchStatesByDisplay.erase(displayId);
2626 }
2627
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002628 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002629}
2630
arthurhung6d4bed92021-03-17 11:59:33 +08002631void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002632 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2633 // have an explicit reason to support it.
2634 constexpr bool isStylus = false;
2635
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002636 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002637 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002638 if (dropWindow) {
2639 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002640 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002641 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002642 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002643 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002644 }
2645 mDragState.reset();
2646}
2647
2648void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002649 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002650 return;
2651 }
2652
arthurhung6d4bed92021-03-17 11:59:33 +08002653 if (!mDragState->isStartDrag) {
2654 mDragState->isStartDrag = true;
2655 mDragState->isStylusButtonDownAtStart =
2656 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2657 }
2658
Arthur Hung54745652022-04-20 07:17:41 +00002659 // Find the pointer index by id.
2660 int32_t pointerIndex = 0;
2661 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2662 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2663 if (pointerProperties.id == mDragState->pointerId) {
2664 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002665 }
Arthur Hung54745652022-04-20 07:17:41 +00002666 }
arthurhung6d4bed92021-03-17 11:59:33 +08002667
Arthur Hung54745652022-04-20 07:17:41 +00002668 if (uint32_t(pointerIndex) == entry.pointerCount) {
2669 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002670 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002671 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002672 return;
2673 }
2674
2675 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2676 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2677 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2678
2679 switch (maskedAction) {
2680 case AMOTION_EVENT_ACTION_MOVE: {
2681 // Handle the special case : stylus button no longer pressed.
2682 bool isStylusButtonDown =
2683 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2684 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2685 finishDragAndDrop(entry.displayId, x, y);
2686 return;
2687 }
2688
2689 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2690 // until we have an explicit reason to support it.
2691 constexpr bool isStylus = false;
2692
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002693 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002694 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002695 // enqueue drag exit if needed.
2696 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2697 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2698 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002699 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002700 y);
2701 }
2702 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2703 }
2704 // enqueue drag location if needed.
2705 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002706 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002707 }
2708 break;
2709 }
2710
2711 case AMOTION_EVENT_ACTION_POINTER_UP:
2712 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2713 break;
2714 }
2715 // The drag pointer is up.
2716 [[fallthrough]];
2717 case AMOTION_EVENT_ACTION_UP:
2718 finishDragAndDrop(entry.displayId, x, y);
2719 break;
2720 case AMOTION_EVENT_ACTION_CANCEL: {
2721 ALOGD("Receiving cancel when drag and drop.");
2722 sendDropWindowCommandLocked(nullptr, 0, 0);
2723 mDragState.reset();
2724 break;
2725 }
arthurhungb89ccb02020-12-30 16:19:01 +08002726 }
2727}
2728
chaviw98318de2021-05-19 16:45:23 -05002729void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002730 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002731 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002732 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002733 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002734 std::vector<InputTarget>::iterator it =
2735 std::find_if(inputTargets.begin(), inputTargets.end(),
2736 [&windowHandle](const InputTarget& inputTarget) {
2737 return inputTarget.inputChannel->getConnectionToken() ==
2738 windowHandle->getToken();
2739 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002740
chaviw98318de2021-05-19 16:45:23 -05002741 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002742
2743 if (it == inputTargets.end()) {
2744 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002745 std::shared_ptr<InputChannel> inputChannel =
2746 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002747 if (inputChannel == nullptr) {
2748 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2749 return;
2750 }
2751 inputTarget.inputChannel = inputChannel;
2752 inputTarget.flags = targetFlags;
2753 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002754 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002755 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2756 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002757 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002758 } else {
Siarhei Vishniakoua06bb552023-02-07 09:38:56 -08002759 // DisplayInfo not found for this window on display windowInfo->displayId.
2760 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002761 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002762 inputTargets.push_back(inputTarget);
2763 it = inputTargets.end() - 1;
2764 }
2765
2766 ALOG_ASSERT(it->flags == targetFlags);
2767 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2768
chaviw1ff3d1e2020-07-01 15:53:47 -07002769 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770}
2771
Michael Wright3dd60e22019-03-27 22:06:44 +00002772void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002773 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002774 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2775 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002776
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002777 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2778 InputTarget target;
2779 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002780 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002781 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2782 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002783 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2784 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002785 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002786 target.setDefaultPointerTransform(target.displayTransform);
2787 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788 }
2789}
2790
Robert Carrc9bf1d32020-04-13 17:21:08 -07002791/**
2792 * Indicate whether one window handle should be considered as obscuring
2793 * another window handle. We only check a few preconditions. Actually
2794 * checking the bounds is left to the caller.
2795 */
chaviw98318de2021-05-19 16:45:23 -05002796static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2797 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002798 // Compare by token so cloned layers aren't counted
2799 if (haveSameToken(windowHandle, otherHandle)) {
2800 return false;
2801 }
2802 auto info = windowHandle->getInfo();
2803 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002804 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002805 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002806 } else if (otherInfo->alpha == 0 &&
2807 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002808 // Those act as if they were invisible, so we don't need to flag them.
2809 // We do want to potentially flag touchable windows even if they have 0
2810 // opacity, since they can consume touches and alter the effects of the
2811 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002812 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002813 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2814 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002815 } else if (info->ownerUid == otherInfo->ownerUid) {
2816 // If ownerUid is the same we don't generate occlusion events as there
2817 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002818 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002819 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002820 return false;
2821 } else if (otherInfo->displayId != info->displayId) {
2822 return false;
2823 }
2824 return true;
2825}
2826
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002827/**
2828 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2829 * untrusted, one should check:
2830 *
2831 * 1. If result.hasBlockingOcclusion is true.
2832 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2833 * BLOCK_UNTRUSTED.
2834 *
2835 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2836 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2837 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2838 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2839 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2840 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2841 *
2842 * If neither of those is true, then it means the touch can be allowed.
2843 */
2844InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002845 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2846 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002847 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002848 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002849 TouchOcclusionInfo info;
2850 info.hasBlockingOcclusion = false;
2851 info.obscuringOpacity = 0;
2852 info.obscuringUid = -1;
2853 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002854 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002855 if (windowHandle == otherHandle) {
2856 break; // All future windows are below us. Exit early.
2857 }
chaviw98318de2021-05-19 16:45:23 -05002858 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002859 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2860 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002861 if (DEBUG_TOUCH_OCCLUSION) {
2862 info.debugInfo.push_back(
2863 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2864 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002865 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2866 // we perform the checks below to see if the touch can be propagated or not based on the
2867 // window's touch occlusion mode
2868 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2869 info.hasBlockingOcclusion = true;
2870 info.obscuringUid = otherInfo->ownerUid;
2871 info.obscuringPackage = otherInfo->packageName;
2872 break;
2873 }
2874 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2875 uint32_t uid = otherInfo->ownerUid;
2876 float opacity =
2877 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2878 // Given windows A and B:
2879 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2880 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2881 opacityByUid[uid] = opacity;
2882 if (opacity > info.obscuringOpacity) {
2883 info.obscuringOpacity = opacity;
2884 info.obscuringUid = uid;
2885 info.obscuringPackage = otherInfo->packageName;
2886 }
2887 }
2888 }
2889 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002890 if (DEBUG_TOUCH_OCCLUSION) {
2891 info.debugInfo.push_back(
2892 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2893 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002894 return info;
2895}
2896
chaviw98318de2021-05-19 16:45:23 -05002897std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002898 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002899 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2900 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2901 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2902 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002903 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2904 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2905 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2906 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2907 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002908 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07002909 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002910}
2911
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002912bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2913 if (occlusionInfo.hasBlockingOcclusion) {
2914 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2915 occlusionInfo.obscuringUid);
2916 return false;
2917 }
2918 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2919 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2920 "%.2f, maximum allowed = %.2f)",
2921 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2922 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2923 return false;
2924 }
2925 return true;
2926}
2927
chaviw98318de2021-05-19 16:45:23 -05002928bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002931 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2932 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002933 if (windowHandle == otherHandle) {
2934 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002935 }
chaviw98318de2021-05-19 16:45:23 -05002936 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002937 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002938 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002939 return true;
2940 }
2941 }
2942 return false;
2943}
2944
chaviw98318de2021-05-19 16:45:23 -05002945bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002946 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002947 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2948 const WindowInfo* windowInfo = windowHandle->getInfo();
2949 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002950 if (windowHandle == otherHandle) {
2951 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002952 }
chaviw98318de2021-05-19 16:45:23 -05002953 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002954 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002955 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002956 return true;
2957 }
2958 }
2959 return false;
2960}
2961
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002962std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002963 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002964 if (applicationHandle != nullptr) {
2965 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002966 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002967 } else {
2968 return applicationHandle->getName();
2969 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002970 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002971 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002973 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002974 }
2975}
2976
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002977void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002978 if (!isUserActivityEvent(eventEntry)) {
2979 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002980 return;
2981 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002982 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002983 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002984 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002985 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002986 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002987 if (DEBUG_DISPATCH_CYCLE) {
2988 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2989 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002990 return;
2991 }
2992 }
2993
2994 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002995 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002996 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002997 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2998 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002999 return;
3000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003001
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003002 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003003 eventType = USER_ACTIVITY_EVENT_TOUCH;
3004 }
3005 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003006 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003007 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003008 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3009 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003010 return;
3011 }
3012 eventType = USER_ACTIVITY_EVENT_BUTTON;
3013 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003015 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003016 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003017 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003018 break;
3019 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003020 }
3021
Prabir Pradhancef936d2021-07-21 16:17:52 +00003022 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3023 REQUIRES(mLock) {
3024 scoped_unlock unlock(mLock);
3025 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
3026 };
3027 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003028}
3029
3030void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003031 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003032 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003033 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003034 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003035 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003036 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003037 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003038 ATRACE_NAME(message.c_str());
3039 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003040 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003041 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003042 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003043 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003044 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003045 inputTarget.getPointerInfoString().c_str());
3046 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047
3048 // Skip this event if the connection status is not normal.
3049 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003050 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003051 if (DEBUG_DISPATCH_CYCLE) {
3052 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003053 connection->getInputChannelName().c_str(),
3054 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056 return;
3057 }
3058
3059 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003060 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003061 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003062 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003063 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003064
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003065 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003066 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003067 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3068 logDispatchStateLocked();
3069 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3070 "target on connection "
3071 << connection->getInputChannelName() << " for "
3072 << originalMotionEntry.getDescription();
3073 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003074 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003075 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3076 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003077 if (!splitMotionEntry) {
3078 return; // split event was dropped
3079 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003080 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3081 std::string reason = std::string("reason=pointer cancel on split window");
3082 android_log_event_list(LOGTAG_INPUT_CANCEL)
3083 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3084 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003085 if (DEBUG_FOCUS) {
3086 ALOGD("channel '%s' ~ Split motion event.",
3087 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003088 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003089 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003090 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3091 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003092 return;
3093 }
3094 }
3095
3096 // Not splitting. Enqueue dispatch entries for the event as is.
3097 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3098}
3099
3100void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003101 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003102 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003103 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003104 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003105 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003106 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003107 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003108 ATRACE_NAME(message.c_str());
3109 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003110 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3111 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003112
hongzuo liu95785e22022-09-06 02:51:35 +00003113 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003114
3115 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003116 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003117 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003118 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003119 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003120 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003121 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003122 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003123 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003124 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003125 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003126 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003127 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128
3129 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003130 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003131 startDispatchCycleLocked(currentTime, connection);
3132 }
3133}
3134
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003135void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003136 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003137 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003138 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003139 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003140 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3141 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003142 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003143 ATRACE_NAME(message.c_str());
3144 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003145 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3146 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 return;
3148 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003149
3150 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3151 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152
3153 // This is a new event.
3154 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003155 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003156 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003158 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3159 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003160 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003162 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003163 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003164 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003165 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003166 dispatchEntry->resolvedAction = keyEntry.action;
3167 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003169 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3170 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003171 if (DEBUG_DISPATCH_CYCLE) {
3172 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3173 "event",
3174 connection->getInputChannelName().c_str());
3175 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003176 return; // skip the inconsistent event
3177 }
3178 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003181 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003182 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003183 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3184 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3185 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3186 static_cast<int32_t>(IdGenerator::Source::OTHER);
3187 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003188 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003189 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003190 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003191 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003192 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003193 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003194 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003195 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003196 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003197 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3198 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003199 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003200 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003201 }
3202 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003203 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3204 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003205 if (DEBUG_DISPATCH_CYCLE) {
3206 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3207 "enter event",
3208 connection->getInputChannelName().c_str());
3209 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003210 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3211 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003212 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3213 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003215 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003216 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3217 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3218 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003219 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003220 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3221 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003222 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003223 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3224 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003226 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3227 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003228 if (DEBUG_DISPATCH_CYCLE) {
3229 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3230 "event",
3231 connection->getInputChannelName().c_str());
3232 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003233 return; // skip the inconsistent event
3234 }
3235
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003236 dispatchEntry->resolvedEventId =
3237 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3238 ? mIdGenerator.nextId()
3239 : motionEntry.id;
3240 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3241 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3242 ") to MotionEvent(id=0x%" PRIx32 ").",
3243 motionEntry.id, dispatchEntry->resolvedEventId);
3244 ATRACE_NAME(message.c_str());
3245 }
3246
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003247 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3248 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3249 // Skip reporting pointer down outside focus to the policy.
3250 break;
3251 }
3252
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003253 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003254 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003255
3256 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003258 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003259 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003260 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3261 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003262 break;
3263 }
Chris Yef59a2f42020-10-16 12:55:26 -07003264 case EventEntry::Type::SENSOR: {
3265 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3266 break;
3267 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003268 case EventEntry::Type::CONFIGURATION_CHANGED:
3269 case EventEntry::Type::DEVICE_RESET: {
3270 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003271 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003272 break;
3273 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003274 }
3275
3276 // Remember that we are waiting for this dispatch to complete.
3277 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003278 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003279 }
3280
3281 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003282 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003283 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003284}
3285
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003286/**
3287 * This function is purely for debugging. It helps us understand where the user interaction
3288 * was taking place. For example, if user is touching launcher, we will see a log that user
3289 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3290 * We will see both launcher and wallpaper in that list.
3291 * Once the interaction with a particular set of connections starts, no new logs will be printed
3292 * until the set of interacted connections changes.
3293 *
3294 * The following items are skipped, to reduce the logspam:
3295 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3296 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3297 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3298 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3299 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003300 */
3301void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3302 const std::vector<InputTarget>& targets) {
3303 // Skip ACTION_UP events, and all events other than keys and motions
3304 if (entry.type == EventEntry::Type::KEY) {
3305 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3306 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3307 return;
3308 }
3309 } else if (entry.type == EventEntry::Type::MOTION) {
3310 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3311 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3312 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3313 return;
3314 }
3315 } else {
3316 return; // Not a key or a motion
3317 }
3318
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003319 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003320 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003321 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003322 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003323 continue; // Skip windows that receive ACTION_OUTSIDE
3324 }
3325
3326 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003327 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003328 if (connection == nullptr) {
3329 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003330 }
3331 newConnectionTokens.insert(std::move(token));
3332 newConnections.emplace_back(connection);
3333 }
3334 if (newConnectionTokens == mInteractionConnectionTokens) {
3335 return; // no change
3336 }
3337 mInteractionConnectionTokens = newConnectionTokens;
3338
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003339 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003340 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003341 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003342 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003343 std::string message = "Interaction with: " + targetList;
3344 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003345 message += "<none>";
3346 }
3347 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3348}
3349
chaviwfd6d3512019-03-25 13:23:49 -07003350void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003351 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003352 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003353 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3354 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003355 return;
3356 }
3357
Vishnu Nairc519ff72021-01-21 08:23:08 -08003358 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003359 if (focusedToken == token) {
3360 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003361 return;
3362 }
3363
Prabir Pradhancef936d2021-07-21 16:17:52 +00003364 auto command = [this, token]() REQUIRES(mLock) {
3365 scoped_unlock unlock(mLock);
3366 mPolicy->onPointerDownOutsideFocus(token);
3367 };
3368 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369}
3370
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003371status_t InputDispatcher::publishMotionEvent(Connection& connection,
3372 DispatchEntry& dispatchEntry) const {
3373 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3374 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3375
3376 PointerCoords scaledCoords[MAX_POINTERS];
3377 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3378
3379 // Set the X and Y offset and X and Y scale depending on the input source.
3380 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003381 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003382 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3383 if (globalScaleFactor != 1.0f) {
3384 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3385 scaledCoords[i] = motionEntry.pointerCoords[i];
3386 // Don't apply window scale here since we don't want scale to affect raw
3387 // coordinates. The scale will be sent back to the client and applied
3388 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003389 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003390 }
3391 usingCoords = scaledCoords;
3392 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003393 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003394 // We don't want the dispatch target to know the coordinates
3395 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3396 scaledCoords[i].clear();
3397 }
3398 usingCoords = scaledCoords;
3399 }
3400
3401 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3402
3403 // Publish the motion event.
3404 return connection.inputPublisher
3405 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3406 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3407 std::move(hmac), dispatchEntry.resolvedAction,
3408 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3409 motionEntry.edgeFlags, motionEntry.metaState,
3410 motionEntry.buttonState, motionEntry.classification,
3411 dispatchEntry.transform, motionEntry.xPrecision,
3412 motionEntry.yPrecision, motionEntry.xCursorPosition,
3413 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3414 motionEntry.downTime, motionEntry.eventTime,
3415 motionEntry.pointerCount, motionEntry.pointerProperties,
3416 usingCoords);
3417}
3418
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003420 const std::shared_ptr<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003421 if (ATRACE_ENABLED()) {
3422 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003423 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003424 ATRACE_NAME(message.c_str());
3425 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003426 if (DEBUG_DISPATCH_CYCLE) {
3427 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3428 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003429
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003430 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003431 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003433 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003434 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435
3436 // Publish the event.
3437 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003438 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3439 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003440 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003441 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3442 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003443 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3444 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3445 << connection->getInputChannelName();
3446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003447
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003448 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003449 status = connection->inputPublisher
3450 .publishKeyEvent(dispatchEntry->seq,
3451 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3452 keyEntry.source, keyEntry.displayId,
3453 std::move(hmac), dispatchEntry->resolvedAction,
3454 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3455 keyEntry.scanCode, keyEntry.metaState,
3456 keyEntry.repeatCount, keyEntry.downTime,
3457 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003458 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459 }
3460
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003461 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003462 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3463 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3464 << connection->getInputChannelName();
3465 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003466 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003467 break;
3468 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003469
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003470 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003471 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003472 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003473 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003474 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003475 break;
3476 }
3477
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003478 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3479 const TouchModeEntry& touchModeEntry =
3480 static_cast<const TouchModeEntry&>(eventEntry);
3481 status = connection->inputPublisher
3482 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3483 touchModeEntry.inTouchMode);
3484
3485 break;
3486 }
3487
Prabir Pradhan99987712020-11-10 18:43:05 -08003488 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3489 const auto& captureEntry =
3490 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3491 status = connection->inputPublisher
3492 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003493 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003494 break;
3495 }
3496
arthurhungb89ccb02020-12-30 16:19:01 +08003497 case EventEntry::Type::DRAG: {
3498 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3499 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3500 dragEntry.id, dragEntry.x,
3501 dragEntry.y,
3502 dragEntry.isExiting);
3503 break;
3504 }
3505
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003506 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003507 case EventEntry::Type::DEVICE_RESET:
3508 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003509 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003510 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003511 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003512 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513 }
3514
3515 // Check the result.
3516 if (status) {
3517 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003518 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003519 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003520 "This is unexpected because the wait queue is empty, so the pipe "
3521 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003522 "event to it, status=%s(%d)",
3523 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3524 status);
Harry Cutts33476232023-01-30 19:57:29 +00003525 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526 } else {
3527 // Pipe is full and we are waiting for the app to finish process some events
3528 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003529 if (DEBUG_DISPATCH_CYCLE) {
3530 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3531 "waiting for the application to catch up",
3532 connection->getInputChannelName().c_str());
3533 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534 }
3535 } else {
3536 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003537 "status=%s(%d)",
3538 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3539 status);
Harry Cutts33476232023-01-30 19:57:29 +00003540 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003541 }
3542 return;
3543 }
3544
3545 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003546 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3547 connection->outboundQueue.end(),
3548 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003549 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003550 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003551 if (connection->responsive) {
3552 mAnrTracker.insert(dispatchEntry->timeoutTime,
3553 connection->inputChannel->getConnectionToken());
3554 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003555 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003556 }
3557}
3558
chaviw09c8d2d2020-08-24 15:48:26 -07003559std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3560 size_t size;
3561 switch (event.type) {
3562 case VerifiedInputEvent::Type::KEY: {
3563 size = sizeof(VerifiedKeyEvent);
3564 break;
3565 }
3566 case VerifiedInputEvent::Type::MOTION: {
3567 size = sizeof(VerifiedMotionEvent);
3568 break;
3569 }
3570 }
3571 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3572 return mHmacKeyManager.sign(start, size);
3573}
3574
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003575const std::array<uint8_t, 32> InputDispatcher::getSignature(
3576 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003577 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3578 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003579 // Only sign events up and down events as the purely move events
3580 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003581 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003582 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003583
3584 VerifiedMotionEvent verifiedEvent =
3585 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3586 verifiedEvent.actionMasked = actionMasked;
3587 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3588 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003589}
3590
3591const std::array<uint8_t, 32> InputDispatcher::getSignature(
3592 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3593 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3594 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3595 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003596 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003597}
3598
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003600 const std::shared_ptr<Connection>& connection,
3601 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003602 if (DEBUG_DISPATCH_CYCLE) {
3603 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3604 connection->getInputChannelName().c_str(), seq, toString(handled));
3605 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003607 if (connection->status == Connection::Status::BROKEN ||
3608 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 return;
3610 }
3611
3612 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003613 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3614 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3615 };
3616 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617}
3618
3619void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003620 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003621 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003622 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003623 LOG(DEBUG) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3624 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003625 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626
3627 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003628 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003629 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003630 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003631 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632
3633 // The connection appears to be unrecoverably broken.
3634 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003635 if (connection->status == Connection::Status::NORMAL) {
3636 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637
3638 if (notify) {
3639 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003640 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3641 connection->getInputChannelName().c_str());
3642
3643 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003644 scoped_unlock unlock(mLock);
3645 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3646 };
3647 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648 }
3649 }
3650}
3651
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003652void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3653 while (!queue.empty()) {
3654 DispatchEntry* dispatchEntry = queue.front();
3655 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003656 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003657 }
3658}
3659
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003660void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003662 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003663 }
3664 delete dispatchEntry;
3665}
3666
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003667int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3668 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003669 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003670 if (connection == nullptr) {
3671 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3672 connectionToken.get(), events);
3673 return 0; // remove the callback
3674 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003675
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003676 bool notify;
3677 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3678 if (!(events & ALOOPER_EVENT_INPUT)) {
3679 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3680 "events=0x%x",
3681 connection->getInputChannelName().c_str(), events);
3682 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683 }
3684
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003685 nsecs_t currentTime = now();
3686 bool gotOne = false;
3687 status_t status = OK;
3688 for (;;) {
3689 Result<InputPublisher::ConsumerResponse> result =
3690 connection->inputPublisher.receiveConsumerResponse();
3691 if (!result.ok()) {
3692 status = result.error().code();
3693 break;
3694 }
3695
3696 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3697 const InputPublisher::Finished& finish =
3698 std::get<InputPublisher::Finished>(*result);
3699 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3700 finish.consumeTime);
3701 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003702 if (shouldReportMetricsForConnection(*connection)) {
3703 const InputPublisher::Timeline& timeline =
3704 std::get<InputPublisher::Timeline>(*result);
3705 mLatencyTracker
3706 .trackGraphicsLatency(timeline.inputEventId,
3707 connection->inputChannel->getConnectionToken(),
3708 std::move(timeline.graphicsTimeline));
3709 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003710 }
3711 gotOne = true;
3712 }
3713 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003714 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003715 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716 return 1;
3717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003718 }
3719
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003720 notify = status != DEAD_OBJECT || !connection->monitor;
3721 if (notify) {
3722 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3723 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3724 status);
3725 }
3726 } else {
3727 // Monitor channels are never explicitly unregistered.
3728 // We do it automatically when the remote endpoint is closed so don't warn about them.
3729 const bool stillHaveWindowHandle =
3730 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3731 notify = !connection->monitor && stillHaveWindowHandle;
3732 if (notify) {
3733 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3734 connection->getInputChannelName().c_str(), events);
3735 }
3736 }
3737
3738 // Remove the channel.
3739 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3740 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003741}
3742
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003743void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003745 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003746 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003747 }
3748}
3749
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003750void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003751 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003752 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003753 for (const Monitor& monitor : monitors) {
3754 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003755 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003756 }
3757}
3758
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003760 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003761 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003762 if (connection == nullptr) {
3763 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003765
3766 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767}
3768
3769void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003770 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003771 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772 return;
3773 }
3774
3775 nsecs_t currentTime = now();
3776
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003777 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003778 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003780 if (cancelationEvents.empty()) {
3781 return;
3782 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003783 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3784 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003785 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003786 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003787 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003788 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003789
Arthur Hungb3307ee2021-10-14 10:57:37 +00003790 std::string reason = std::string("reason=").append(options.reason);
3791 android_log_event_list(LOGTAG_INPUT_CANCEL)
3792 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3793
Svet Ganov5d3bc372020-01-26 23:11:07 -08003794 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003795 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003796 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3797 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003798 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003799 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003800 target.globalScaleFactor = windowInfo->globalScaleFactor;
3801 }
3802 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003803 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003804
hongzuo liu95785e22022-09-06 02:51:35 +00003805 const bool wasEmpty = connection->outboundQueue.empty();
3806
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003807 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003808 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003809 switch (cancelationEventEntry->type) {
3810 case EventEntry::Type::KEY: {
3811 logOutboundKeyDetails("cancel - ",
3812 static_cast<const KeyEntry&>(*cancelationEventEntry));
3813 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003815 case EventEntry::Type::MOTION: {
3816 logOutboundMotionDetails("cancel - ",
3817 static_cast<const MotionEntry&>(*cancelationEventEntry));
3818 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003820 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003821 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003822 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3823 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003824 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003825 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003826 break;
3827 }
3828 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003829 case EventEntry::Type::DEVICE_RESET:
3830 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003831 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003832 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003833 break;
3834 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835 }
3836
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003837 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003838 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003840
hongzuo liu95785e22022-09-06 02:51:35 +00003841 // If the outbound queue was previously empty, start the dispatch cycle going.
3842 if (wasEmpty && !connection->outboundQueue.empty()) {
3843 startDispatchCycleLocked(currentTime, connection);
3844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003845}
3846
Svet Ganov5d3bc372020-01-26 23:11:07 -08003847void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003848 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00003849 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003850 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003851 return;
3852 }
3853
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003854 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003855 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003856
3857 if (downEvents.empty()) {
3858 return;
3859 }
3860
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003861 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003862 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3863 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003864 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003865
3866 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003867 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003868 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3869 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003870 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003871 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003872 target.globalScaleFactor = windowInfo->globalScaleFactor;
3873 }
3874 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00003875 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003876
hongzuo liu95785e22022-09-06 02:51:35 +00003877 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003878 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003879 switch (downEventEntry->type) {
3880 case EventEntry::Type::MOTION: {
3881 logOutboundMotionDetails("down - ",
3882 static_cast<const MotionEntry&>(*downEventEntry));
3883 break;
3884 }
3885
3886 case EventEntry::Type::KEY:
3887 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003888 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003889 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003890 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003891 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003892 case EventEntry::Type::SENSOR:
3893 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003894 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003895 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003896 break;
3897 }
3898 }
3899
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003900 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003901 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003902 }
3903
hongzuo liu95785e22022-09-06 02:51:35 +00003904 // If the outbound queue was previously empty, start the dispatch cycle going.
3905 if (wasEmpty && !connection->outboundQueue.empty()) {
3906 startDispatchCycleLocked(downTime, connection);
3907 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003908}
3909
Arthur Hungc539dbb2022-12-08 07:45:36 +00003910void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
3911 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
3912 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003913 std::shared_ptr<Connection> wallpaperConnection =
3914 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00003915 if (wallpaperConnection != nullptr) {
3916 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
3917 }
3918 }
3919}
3920
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003921std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003922 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
3923 nsecs_t splitDownTime) {
3924 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925
3926 uint32_t splitPointerIndexMap[MAX_POINTERS];
3927 PointerProperties splitPointerProperties[MAX_POINTERS];
3928 PointerCoords splitPointerCoords[MAX_POINTERS];
3929
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003930 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931 uint32_t splitPointerCount = 0;
3932
3933 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003934 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003936 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003938 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3940 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3941 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003942 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943 splitPointerCount += 1;
3944 }
3945 }
3946
3947 if (splitPointerCount != pointerIds.count()) {
3948 // This is bad. We are missing some of the pointers that we expected to deliver.
3949 // Most likely this indicates that we received an ACTION_MOVE events that has
3950 // different pointer ids than we expected based on the previous ACTION_DOWN
3951 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3952 // in this way.
3953 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003954 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003955 "a broken sequence of pointer ids from the input device: %s",
3956 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07003957 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003958 }
3959
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003960 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003962 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3963 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3965 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003966 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003968 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 if (pointerIds.count() == 1) {
3970 // The first/last pointer went down/up.
3971 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003972 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003973 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3974 ? AMOTION_EVENT_ACTION_CANCEL
3975 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976 } else {
3977 // A secondary pointer went down/up.
3978 uint32_t splitPointerIndex = 0;
3979 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3980 splitPointerIndex += 1;
3981 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003982 action = maskedAction |
3983 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984 }
3985 } else {
3986 // An unrelated pointer changed.
3987 action = AMOTION_EVENT_ACTION_MOVE;
3988 }
3989 }
3990
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003991 if (action == AMOTION_EVENT_ACTION_DOWN) {
3992 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3993 "Split motion event has mismatching downTime and eventTime for "
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08003994 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
3995 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003996 }
3997
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003998 int32_t newId = mIdGenerator.nextId();
3999 if (ATRACE_ENABLED()) {
4000 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
4001 ") to MotionEvent(id=0x%" PRIx32 ").",
4002 originalMotionEntry.id, newId);
4003 ATRACE_NAME(message.c_str());
4004 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004005 std::unique_ptr<MotionEntry> splitMotionEntry =
4006 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4007 originalMotionEntry.deviceId, originalMotionEntry.source,
4008 originalMotionEntry.displayId,
4009 originalMotionEntry.policyFlags, action,
4010 originalMotionEntry.actionButton,
4011 originalMotionEntry.flags, originalMotionEntry.metaState,
4012 originalMotionEntry.buttonState,
4013 originalMotionEntry.classification,
4014 originalMotionEntry.edgeFlags,
4015 originalMotionEntry.xPrecision,
4016 originalMotionEntry.yPrecision,
4017 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004018 originalMotionEntry.yCursorPosition, splitDownTime,
4019 splitPointerCount, splitPointerProperties,
4020 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004022 if (originalMotionEntry.injectionState) {
4023 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004024 splitMotionEntry->injectionState->refCount += 1;
4025 }
4026
4027 return splitMotionEntry;
4028}
4029
Prabir Pradhan678438e2023-04-13 19:32:51 +00004030void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004031 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004032 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004033 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004034
Antonio Kantekf16f2832021-09-28 04:39:20 +00004035 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004036 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004037 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004038
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004039 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004040 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004041 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004042 } // release lock
4043
4044 if (needWake) {
4045 mLooper->wake();
4046 }
4047}
4048
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004049/**
4050 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004051 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4052 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4053 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4054 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4055 * potentially handle the back key presses.
4056 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4057 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004058 */
4059void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004060 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004061 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4062 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004063 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004064 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004065 }
4066 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004067 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004068 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004069 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004070 keyCode = newKeyCode;
4071 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4072 }
4073 } else if (action == AKEY_EVENT_ACTION_UP) {
4074 // In order to maintain a consistent stream of up and down events, check to see if the key
4075 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4076 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004077 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004078 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004079 auto replacementIt = mReplacedKeys.find(replacement);
4080 if (replacementIt != mReplacedKeys.end()) {
4081 keyCode = replacementIt->second;
4082 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004083 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4084 }
4085 }
4086}
4087
Prabir Pradhan678438e2023-04-13 19:32:51 +00004088void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004089 ALOGD_IF(debugInboundEventDetails(),
4090 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4091 ", deviceId=%d, source=%s, displayId=%" PRId32
4092 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4093 "downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004094 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4095 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4096 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
4097 if (!validateKeyEvent(args.action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098 return;
4099 }
4100
Prabir Pradhan678438e2023-04-13 19:32:51 +00004101 uint32_t policyFlags = args.policyFlags;
4102 int32_t flags = args.flags;
4103 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004104 // InputDispatcher tracks and generates key repeats on behalf of
4105 // whatever notifies it, so repeatCount should always be set to 0
4106 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4108 policyFlags |= POLICY_FLAG_VIRTUAL;
4109 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4110 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111 if (policyFlags & POLICY_FLAG_FUNCTION) {
4112 metaState |= AMETA_FUNCTION_ON;
4113 }
4114
4115 policyFlags |= POLICY_FLAG_TRUSTED;
4116
Prabir Pradhan678438e2023-04-13 19:32:51 +00004117 int32_t keyCode = args.keyCode;
4118 accelerateMetaShortcuts(args.deviceId, args.action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004119
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120 KeyEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004121 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4122 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4123 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124
Michael Wright2b3c3302018-03-02 17:19:13 +00004125 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004127 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4128 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004129 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004130 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131
Antonio Kantekf16f2832021-09-28 04:39:20 +00004132 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133 { // acquire lock
4134 mLock.lock();
4135
4136 if (shouldSendKeyToInputFilterLocked(args)) {
4137 mLock.unlock();
4138
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004139 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4141 return; // event was consumed by the filter
4142 }
4143
4144 mLock.lock();
4145 }
4146
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004147 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004148 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4149 args.displayId, policyFlags, args.action, flags, keyCode,
4150 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004151
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004152 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153 mLock.unlock();
4154 } // release lock
4155
4156 if (needWake) {
4157 mLooper->wake();
4158 }
4159}
4160
Prabir Pradhan678438e2023-04-13 19:32:51 +00004161bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 return mInputFilterEnabled;
4163}
4164
Prabir Pradhan678438e2023-04-13 19:32:51 +00004165void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004166 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004167 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004168 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004169 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004170 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4171 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004172 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4173 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4174 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4175 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4176 args.downTime);
4177 for (uint32_t i = 0; i < args.pointerCount; i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004178 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4179 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004180 i, args.pointerProperties[i].id,
4181 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4182 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4183 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4184 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4185 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4186 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4187 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4188 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4189 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4190 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004191 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 }
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004193
Prabir Pradhan678438e2023-04-13 19:32:51 +00004194 if (!validateMotionEvent(args.action, args.actionButton, args.pointerCount,
4195 args.pointerProperties)) {
4196 LOG(ERROR) << "Invalid event: " << args.dump();
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004197 return;
4198 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199
Prabir Pradhan678438e2023-04-13 19:32:51 +00004200 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004202
4203 android::base::Timer t;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004204 mPolicy->interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004205 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4206 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004207 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004208 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004209
Antonio Kantekf16f2832021-09-28 04:39:20 +00004210 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211 { // acquire lock
4212 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004213 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4214 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4215 // complete the processing of the current stroke.
Prabir Pradhan678438e2023-04-13 19:32:51 +00004216 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004217 if (touchStateIt != mTouchStatesByDisplay.end()) {
4218 const TouchState& touchState = touchStateIt->second;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004219 if (touchState.deviceId == args.deviceId && touchState.isDown()) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004220 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4221 }
4222 }
4223 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224
4225 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004226 ui::Transform displayTransform;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004227 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004228 displayTransform = it->second.transform;
4229 }
4230
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231 mLock.unlock();
4232
4233 MotionEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004234 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4235 args.action, args.actionButton, args.flags, args.edgeFlags,
4236 args.metaState, args.buttonState, args.classification,
4237 displayTransform, args.xPrecision, args.yPrecision,
4238 args.xCursorPosition, args.yCursorPosition, displayTransform,
4239 args.downTime, args.eventTime, args.pointerCount,
4240 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241
4242 policyFlags |= POLICY_FLAG_FILTERED;
4243 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4244 return; // event was consumed by the filter
4245 }
4246
4247 mLock.lock();
4248 }
4249
4250 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004251 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004252 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4253 args.displayId, policyFlags, args.action,
4254 args.actionButton, args.flags, args.metaState,
4255 args.buttonState, args.classification, args.edgeFlags,
4256 args.xPrecision, args.yPrecision,
4257 args.xCursorPosition, args.yCursorPosition,
4258 args.downTime, args.pointerCount,
4259 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260
Prabir Pradhan678438e2023-04-13 19:32:51 +00004261 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4262 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004263 !mInputFilterEnabled) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004264 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4265 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004266 }
4267
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004268 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 mLock.unlock();
4270 } // release lock
4271
4272 if (needWake) {
4273 mLooper->wake();
4274 }
4275}
4276
Prabir Pradhan678438e2023-04-13 19:32:51 +00004277void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004278 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004279 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4280 " sensorType=%s",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004281 args.id, args.eventTime, args.deviceId, args.source,
4282 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004283 }
Chris Yef59a2f42020-10-16 12:55:26 -07004284
Antonio Kantekf16f2832021-09-28 04:39:20 +00004285 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004286 { // acquire lock
4287 mLock.lock();
4288
4289 // Just enqueue a new sensor event.
4290 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004291 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4292 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4293 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004294
4295 needWake = enqueueInboundEventLocked(std::move(newEntry));
4296 mLock.unlock();
4297 } // release lock
4298
4299 if (needWake) {
4300 mLooper->wake();
4301 }
4302}
4303
Prabir Pradhan678438e2023-04-13 19:32:51 +00004304void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004305 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004306 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4307 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004308 }
Prabir Pradhan678438e2023-04-13 19:32:51 +00004309 mPolicy->notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004310}
4311
Prabir Pradhan678438e2023-04-13 19:32:51 +00004312bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004313 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314}
4315
Prabir Pradhan678438e2023-04-13 19:32:51 +00004316void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004317 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004318 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4319 "switchMask=0x%08x",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004320 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322
Prabir Pradhan678438e2023-04-13 19:32:51 +00004323 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004325 mPolicy->notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326}
4327
Prabir Pradhan678438e2023-04-13 19:32:51 +00004328void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004329 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004330 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4331 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004332 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333
Antonio Kantekf16f2832021-09-28 04:39:20 +00004334 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004336 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004337
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004338 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004339 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004340 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341 } // release lock
4342
4343 if (needWake) {
4344 mLooper->wake();
4345 }
4346}
4347
Prabir Pradhan678438e2023-04-13 19:32:51 +00004348void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004349 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004350 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4351 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004352 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004353
Antonio Kantekf16f2832021-09-28 04:39:20 +00004354 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004355 { // acquire lock
4356 std::scoped_lock _l(mLock);
Prabir Pradhan678438e2023-04-13 19:32:51 +00004357 auto entry =
4358 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004359 needWake = enqueueInboundEventLocked(std::move(entry));
4360 } // release lock
4361
4362 if (needWake) {
4363 mLooper->wake();
4364 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004365}
4366
Prabir Pradhan5735a322022-04-11 17:23:34 +00004367InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4368 std::optional<int32_t> targetUid,
4369 InputEventInjectionSync syncMode,
4370 std::chrono::milliseconds timeout,
4371 uint32_t policyFlags) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004372 if (debugInboundEventDetails()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004373 LOG(DEBUG) << __func__ << ": targetUid=" << toString(targetUid)
4374 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4375 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4376 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004377 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004378 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004379
Prabir Pradhan5735a322022-04-11 17:23:34 +00004380 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004382 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004383 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4384 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4385 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4386 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4387 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004388 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004389 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004390 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004391 }
4392
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004393 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004394 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004395 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004396 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4397 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004398 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004399 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004400 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004402 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004403 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4404 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4405 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004406 int32_t keyCode = incomingKey.getKeyCode();
4407 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004408 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004409 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004410 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004411 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004412 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4413 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4414 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004415
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004416 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4417 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004418 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004419
4420 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4421 android::base::Timer t;
4422 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4423 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4424 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4425 std::to_string(t.duration().count()).c_str());
4426 }
4427 }
4428
4429 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004430 std::unique_ptr<KeyEntry> injectedEntry =
4431 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004432 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004433 incomingKey.getDisplayId(), policyFlags, action,
4434 flags, keyCode, incomingKey.getScanCode(), metaState,
4435 incomingKey.getRepeatCount(),
4436 incomingKey.getDownTime());
4437 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004438 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439 }
4440
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004441 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004442 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004443 const int32_t action = motionEvent.getAction();
4444 const bool isPointerEvent =
4445 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4446 // If a pointer event has no displayId specified, inject it to the default display.
4447 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4448 ? ADISPLAY_ID_DEFAULT
4449 : event->getDisplayId();
4450 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004451 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004452 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004453 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004454 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004455 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004456 }
4457
4458 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004459 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004460 android::base::Timer t;
4461 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4462 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4463 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4464 std::to_string(t.duration().count()).c_str());
4465 }
4466 }
4467
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004468 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4469 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4470 }
4471
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004472 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004473 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4474 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004475 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004476 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4477 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004478 displayId, policyFlags, action, actionButton,
4479 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004480 motionEvent.getButtonState(),
4481 motionEvent.getClassification(),
4482 motionEvent.getEdgeFlags(),
4483 motionEvent.getXPrecision(),
4484 motionEvent.getYPrecision(),
4485 motionEvent.getRawXCursorPosition(),
4486 motionEvent.getRawYCursorPosition(),
4487 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004488 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004489 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004490 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004491 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004492 sampleEventTimes += 1;
4493 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004494 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004495 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4496 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004497 displayId, policyFlags, action, actionButton,
4498 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004499 motionEvent.getButtonState(),
4500 motionEvent.getClassification(),
4501 motionEvent.getEdgeFlags(),
4502 motionEvent.getXPrecision(),
4503 motionEvent.getYPrecision(),
4504 motionEvent.getRawXCursorPosition(),
4505 motionEvent.getRawYCursorPosition(),
4506 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004507 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004508 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004509 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4510 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004511 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004512 }
4513 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004514 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004515
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004516 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004517 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004518 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519 }
4520
Prabir Pradhan5735a322022-04-11 17:23:34 +00004521 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004522 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523 injectionState->injectionIsAsync = true;
4524 }
4525
4526 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004527 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004528
4529 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004530 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004531 if (DEBUG_INJECTION) {
4532 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4533 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004534 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004535 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004536 }
4537
4538 mLock.unlock();
4539
4540 if (needWake) {
4541 mLooper->wake();
4542 }
4543
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004544 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004545 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004546 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004547
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004548 if (syncMode == InputEventInjectionSync::NONE) {
4549 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004550 } else {
4551 for (;;) {
4552 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004553 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554 break;
4555 }
4556
4557 nsecs_t remainingTimeout = endTime - now();
4558 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004559 if (DEBUG_INJECTION) {
4560 ALOGD("injectInputEvent - Timed out waiting for injection result "
4561 "to become available.");
4562 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004563 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004564 break;
4565 }
4566
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004567 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004568 }
4569
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004570 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4571 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004573 if (DEBUG_INJECTION) {
4574 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4575 injectionState->pendingForegroundDispatches);
4576 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004577 nsecs_t remainingTimeout = endTime - now();
4578 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004579 if (DEBUG_INJECTION) {
4580 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4581 "dispatches to finish.");
4582 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004583 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004584 break;
4585 }
4586
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004587 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588 }
4589 }
4590 }
4591
4592 injectionState->release();
4593 } // release lock
4594
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004595 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004596 LOG(DEBUG) << "injectInputEvent - Finished with result "
4597 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004598 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004599
4600 return injectionResult;
4601}
4602
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004603std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004604 std::array<uint8_t, 32> calculatedHmac;
4605 std::unique_ptr<VerifiedInputEvent> result;
4606 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004607 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004608 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4609 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4610 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004611 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004612 break;
4613 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004614 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004615 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4616 VerifiedMotionEvent verifiedMotionEvent =
4617 verifiedMotionEventFromMotionEvent(motionEvent);
4618 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004619 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004620 break;
4621 }
4622 default: {
4623 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4624 return nullptr;
4625 }
4626 }
4627 if (calculatedHmac == INVALID_HMAC) {
4628 return nullptr;
4629 }
tyiu1573a672023-02-21 22:38:32 +00004630 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004631 return nullptr;
4632 }
4633 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004634}
4635
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004636void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004637 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004638 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004640 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004641 LOG(DEBUG) << "Setting input event injection result to "
4642 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004643 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004644
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004645 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004646 // Log the outcome since the injector did not wait for the injection result.
4647 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004648 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004649 ALOGV("Asynchronous input event injection succeeded.");
4650 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004651 case InputEventInjectionResult::TARGET_MISMATCH:
4652 ALOGV("Asynchronous input event injection target mismatch.");
4653 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004654 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004655 ALOGW("Asynchronous input event injection failed.");
4656 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004657 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004658 ALOGW("Asynchronous input event injection timed out.");
4659 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004660 case InputEventInjectionResult::PENDING:
4661 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4662 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663 }
4664 }
4665
4666 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004667 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004668 }
4669}
4670
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004671void InputDispatcher::transformMotionEntryForInjectionLocked(
4672 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004673 // Input injection works in the logical display coordinate space, but the input pipeline works
4674 // display space, so we need to transform the injected events accordingly.
4675 const auto it = mDisplayInfos.find(entry.displayId);
4676 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004677 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004678
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004679 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4680 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4681 const vec2 cursor =
4682 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4683 {entry.xCursorPosition, entry.yCursorPosition});
4684 entry.xCursorPosition = cursor.x;
4685 entry.yCursorPosition = cursor.y;
4686 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004687 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004688 entry.pointerCoords[i] =
4689 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4690 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004691 }
4692}
4693
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004694void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4695 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696 if (injectionState) {
4697 injectionState->pendingForegroundDispatches += 1;
4698 }
4699}
4700
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004701void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4702 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703 if (injectionState) {
4704 injectionState->pendingForegroundDispatches -= 1;
4705
4706 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004707 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004708 }
4709 }
4710}
4711
chaviw98318de2021-05-19 16:45:23 -05004712const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004713 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004714 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004715 auto it = mWindowHandlesByDisplay.find(displayId);
4716 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004717}
4718
chaviw98318de2021-05-19 16:45:23 -05004719sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004720 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004721 if (windowHandleToken == nullptr) {
4722 return nullptr;
4723 }
4724
Arthur Hungb92218b2018-08-14 12:00:21 +08004725 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004726 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4727 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004728 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004729 return windowHandle;
4730 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731 }
4732 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004733 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004734}
4735
chaviw98318de2021-05-19 16:45:23 -05004736sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4737 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004738 if (windowHandleToken == nullptr) {
4739 return nullptr;
4740 }
4741
chaviw98318de2021-05-19 16:45:23 -05004742 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004743 if (windowHandle->getToken() == windowHandleToken) {
4744 return windowHandle;
4745 }
4746 }
4747 return nullptr;
4748}
4749
chaviw98318de2021-05-19 16:45:23 -05004750sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4751 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004752 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004753 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4754 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004755 if (handle->getId() == windowHandle->getId() &&
4756 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004757 if (windowHandle->getInfo()->displayId != it.first) {
4758 ALOGE("Found window %s in display %" PRId32
4759 ", but it should belong to display %" PRId32,
4760 windowHandle->getName().c_str(), it.first,
4761 windowHandle->getInfo()->displayId);
4762 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004763 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004764 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004765 }
4766 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004767 return nullptr;
4768}
4769
chaviw98318de2021-05-19 16:45:23 -05004770sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004771 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4772 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004773}
4774
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004775ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4776 auto displayInfoIt = mDisplayInfos.find(displayId);
4777 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4778 : kIdentityTransform;
4779}
4780
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004781bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4782 const MotionEntry& motionEntry) const {
4783 const WindowInfo& info = *window->getInfo();
4784
4785 // Skip spy window targets that are not valid for targeted injection.
4786 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004787 return false;
4788 }
4789
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004790 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4791 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4792 return false;
4793 }
4794
4795 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4796 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4797 window->getName().c_str());
4798 return false;
4799 }
4800
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004801 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004802 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004803 ALOGW("Not sending touch to %s because there's no corresponding connection",
4804 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004805 return false;
4806 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004807
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004808 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004809 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004810 return false;
4811 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004812
4813 // Drop events that can't be trusted due to occlusion
4814 const auto [x, y] = resolveTouchedPosition(motionEntry);
4815 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4816 if (!isTouchTrustedLocked(occlusionInfo)) {
4817 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004818 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004819 for (const auto& log : occlusionInfo.debugInfo) {
4820 ALOGD("%s", log.c_str());
4821 }
4822 }
4823 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4824 occlusionInfo.obscuringUid);
4825 return false;
4826 }
4827
4828 // Drop touch events if requested by input feature
4829 if (shouldDropInput(motionEntry, window)) {
4830 return false;
4831 }
4832
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004833 return true;
4834}
4835
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004836std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4837 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004838 auto connectionIt = mConnectionsByToken.find(token);
4839 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004840 return nullptr;
4841 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004842 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004843}
4844
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004845void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004846 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4847 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004848 // Remove all handles on a display if there are no windows left.
4849 mWindowHandlesByDisplay.erase(displayId);
4850 return;
4851 }
4852
4853 // Since we compare the pointer of input window handles across window updates, we need
4854 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004855 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4856 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4857 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004858 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004859 }
4860
chaviw98318de2021-05-19 16:45:23 -05004861 std::vector<sp<WindowInfoHandle>> newHandles;
4862 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004863 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004864 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004865 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004866 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004867 const bool canReceiveInput =
4868 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4869 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004870 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004871 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004872 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004873 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004874 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004875 }
4876
4877 if (info->displayId != displayId) {
4878 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4879 handle->getName().c_str(), displayId, info->displayId);
4880 continue;
4881 }
4882
Robert Carredd13602020-04-13 17:24:34 -07004883 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4884 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004885 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004886 oldHandle->updateFrom(handle);
4887 newHandles.push_back(oldHandle);
4888 } else {
4889 newHandles.push_back(handle);
4890 }
4891 }
4892
4893 // Insert or replace
4894 mWindowHandlesByDisplay[displayId] = newHandles;
4895}
4896
Arthur Hung72d8dc32020-03-28 00:48:39 +00004897void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004898 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004899 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004900 { // acquire lock
4901 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004902 for (const auto& [displayId, handles] : handlesPerDisplay) {
4903 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004904 }
4905 }
4906 // Wake up poll loop since it may need to make new input dispatching choices.
4907 mLooper->wake();
4908}
4909
Arthur Hungb92218b2018-08-14 12:00:21 +08004910/**
4911 * Called from InputManagerService, update window handle list by displayId that can receive input.
4912 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4913 * If set an empty list, remove all handles from the specific display.
4914 * For focused handle, check if need to change and send a cancel event to previous one.
4915 * For removed handle, check if need to send a cancel event if already in touch.
4916 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004917void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004918 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004919 if (DEBUG_FOCUS) {
4920 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004921 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004922 windowList += iwh->getName() + " ";
4923 }
4924 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926
Prabir Pradhand65552b2021-10-07 11:23:50 -07004927 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004928 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004929 const WindowInfo& info = *window->getInfo();
4930
4931 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004932 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004933 if (noInputWindow && window->getToken() != nullptr) {
4934 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4935 window->getName().c_str());
4936 window->releaseChannel();
4937 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004938
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004939 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004940 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4941 !info.inputConfig.test(
4942 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004943 "%s has feature SPY, but is not a trusted overlay.",
4944 window->getName().c_str());
4945
Prabir Pradhand65552b2021-10-07 11:23:50 -07004946 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004947 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4948 !info.inputConfig.test(
4949 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004950 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4951 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004952 }
4953
Arthur Hung72d8dc32020-03-28 00:48:39 +00004954 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004955 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004956
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004957 // Save the old windows' orientation by ID before it gets updated.
4958 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004959 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004960 oldWindowOrientations.emplace(handle->getId(),
4961 handle->getInfo()->transform.getOrientation());
4962 }
4963
chaviw98318de2021-05-19 16:45:23 -05004964 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004965
chaviw98318de2021-05-19 16:45:23 -05004966 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004967
Vishnu Nairc519ff72021-01-21 08:23:08 -08004968 std::optional<FocusResolver::FocusChanges> changes =
4969 mFocusResolver.setInputWindows(displayId, windowHandles);
4970 if (changes) {
4971 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004972 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004973
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004974 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4975 mTouchStatesByDisplay.find(displayId);
4976 if (stateIt != mTouchStatesByDisplay.end()) {
4977 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004978 for (size_t i = 0; i < state.windows.size();) {
4979 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004980 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004981 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004982 ALOGD("Touched window was removed: %s in display %" PRId32,
4983 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004984 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004985 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004986 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4987 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004988 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00004989 "touched window was removed");
4990 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004991 // Since we are about to drop the touch, cancel the events for the wallpaper as
4992 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004993 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004994 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4995 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004996 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004997 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004998 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004999 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005000 state.windows.erase(state.windows.begin() + i);
5001 } else {
5002 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005003 }
5004 }
arthurhungb89ccb02020-12-30 16:19:01 +08005005
arthurhung6d4bed92021-03-17 11:59:33 +08005006 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005007 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005008 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005009 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005010 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005011 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5012 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005013 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005014 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005015 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005016
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005017 // Determine if the orientation of any of the input windows have changed, and cancel all
5018 // pointer events if necessary.
5019 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
5020 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
5021 if (newWindowHandle != nullptr &&
5022 newWindowHandle->getInfo()->transform.getOrientation() !=
5023 oldWindowOrientations[oldWindowHandle->getId()]) {
5024 std::shared_ptr<InputChannel> inputChannel =
5025 getInputChannelLocked(newWindowHandle->getToken());
5026 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005027 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005028 "touched window's orientation changed");
5029 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005030 }
5031 }
5032 }
5033
Arthur Hung72d8dc32020-03-28 00:48:39 +00005034 // Release information for windows that are no longer present.
5035 // This ensures that unused input channels are released promptly.
5036 // Otherwise, they might stick around until the window handle is destroyed
5037 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005038 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005039 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005040 if (DEBUG_FOCUS) {
5041 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005042 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005043 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005044 }
chaviw291d88a2019-02-14 10:33:58 -08005045 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005046}
5047
5048void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005049 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005050 if (DEBUG_FOCUS) {
5051 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5052 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5053 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005054 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005055 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005056 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005057 } // release lock
5058
5059 // Wake up poll loop since it may need to make new input dispatching choices.
5060 mLooper->wake();
5061}
5062
Vishnu Nair599f1412021-06-21 10:39:58 -07005063void InputDispatcher::setFocusedApplicationLocked(
5064 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5065 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5066 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5067
5068 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5069 return; // This application is already focused. No need to wake up or change anything.
5070 }
5071
5072 // Set the new application handle.
5073 if (inputApplicationHandle != nullptr) {
5074 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5075 } else {
5076 mFocusedApplicationHandlesByDisplay.erase(displayId);
5077 }
5078
5079 // No matter what the old focused application was, stop waiting on it because it is
5080 // no longer focused.
5081 resetNoFocusedWindowTimeoutLocked();
5082}
5083
Tiger Huang721e26f2018-07-24 22:26:19 +08005084/**
5085 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5086 * the display not specified.
5087 *
5088 * We track any unreleased events for each window. If a window loses the ability to receive the
5089 * released event, we will send a cancel event to it. So when the focused display is changed, we
5090 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5091 * display. The display-specified events won't be affected.
5092 */
5093void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005094 if (DEBUG_FOCUS) {
5095 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5096 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005097 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005098 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005099
5100 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005101 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005102 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005103 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005104 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005105 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005106 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005107 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005108 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005109 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005110 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005111 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5112 }
5113 }
5114 mFocusedDisplayId = displayId;
5115
Chris Ye3c2d6f52020-08-09 10:39:48 -07005116 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005117 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005118 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005119
Vishnu Nairad321cd2020-08-20 16:40:21 -07005120 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005121 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005122 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005123 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005124 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005125 }
5126 }
5127 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005128 } // release lock
5129
5130 // Wake up poll loop since it may need to make new input dispatching choices.
5131 mLooper->wake();
5132}
5133
Michael Wrightd02c5b62014-02-10 15:10:22 -08005134void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005135 if (DEBUG_FOCUS) {
5136 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5137 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005138
5139 bool changed;
5140 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005141 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005142
5143 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5144 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005145 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146 }
5147
5148 if (mDispatchEnabled && !enabled) {
5149 resetAndDropEverythingLocked("dispatcher is being disabled");
5150 }
5151
5152 mDispatchEnabled = enabled;
5153 mDispatchFrozen = frozen;
5154 changed = true;
5155 } else {
5156 changed = false;
5157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005158 } // release lock
5159
5160 if (changed) {
5161 // Wake up poll loop since it may need to make new input dispatching choices.
5162 mLooper->wake();
5163 }
5164}
5165
5166void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005167 if (DEBUG_FOCUS) {
5168 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5169 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170
5171 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005172 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173
5174 if (mInputFilterEnabled == enabled) {
5175 return;
5176 }
5177
5178 mInputFilterEnabled = enabled;
5179 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5180 } // release lock
5181
5182 // Wake up poll loop since there might be work to do to drop everything.
5183 mLooper->wake();
5184}
5185
Antonio Kanteka042c022022-07-06 16:51:07 -07005186bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5187 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005188 bool needWake = false;
5189 {
5190 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005191 ALOGD_IF(DEBUG_TOUCH_MODE,
5192 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5193 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5194 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5195 mTouchModePerDisplay.count(displayId) == 0
5196 ? "not set"
5197 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5198
Antonio Kantek15beb512022-06-13 22:35:41 +00005199 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5200 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005201 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005202 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005203 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005204 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5205 !recentWindowsAreOwnedByLocked(pid, uid)) {
5206 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5207 "window nor none of the previously interacted window",
5208 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005209 return false;
5210 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005211 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005212 mTouchModePerDisplay[displayId] = inTouchMode;
5213 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5214 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005215 needWake = enqueueInboundEventLocked(std::move(entry));
5216 } // release lock
5217
5218 if (needWake) {
5219 mLooper->wake();
5220 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005221 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005222}
5223
Antonio Kantek48710e42022-03-24 14:19:30 -07005224bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5225 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5226 if (focusedToken == nullptr) {
5227 return false;
5228 }
5229 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5230 return isWindowOwnedBy(windowHandle, pid, uid);
5231}
5232
5233bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5234 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5235 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5236 const sp<WindowInfoHandle> windowHandle =
5237 getWindowHandleLocked(connectionToken);
5238 return isWindowOwnedBy(windowHandle, pid, uid);
5239 }) != mInteractionConnectionTokens.end();
5240}
5241
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005242void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5243 if (opacity < 0 || opacity > 1) {
5244 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5245 return;
5246 }
5247
5248 std::scoped_lock lock(mLock);
5249 mMaximumObscuringOpacityForTouch = opacity;
5250}
5251
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005252std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5253InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005254 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5255 for (TouchedWindow& w : state.windows) {
5256 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005257 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005258 }
5259 }
5260 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005261 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005262}
5263
arthurhungb89ccb02020-12-30 16:19:01 +08005264bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5265 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005266 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005267 if (DEBUG_FOCUS) {
5268 ALOGD("Trivial transfer to same window.");
5269 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005270 return true;
5271 }
5272
Michael Wrightd02c5b62014-02-10 15:10:22 -08005273 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005274 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005275
Arthur Hungabbb9d82021-09-01 14:52:30 +00005276 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005277 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005278 if (state == nullptr || touchedWindow == nullptr) {
5279 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005280 return false;
5281 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005282
Arthur Hungabbb9d82021-09-01 14:52:30 +00005283 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5284 if (toWindowHandle == nullptr) {
5285 ALOGW("Cannot transfer focus because to window not found.");
5286 return false;
5287 }
5288
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005289 if (DEBUG_FOCUS) {
5290 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005291 touchedWindow->windowHandle->getName().c_str(),
5292 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005293 }
5294
Arthur Hungabbb9d82021-09-01 14:52:30 +00005295 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005296 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005297 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005298 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005299 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005300
Arthur Hungabbb9d82021-09-01 14:52:30 +00005301 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005302 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005303 ftl::Flags<InputTarget::Flags> newTargetFlags =
5304 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005305 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005306 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005307 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005308 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005309
Arthur Hungabbb9d82021-09-01 14:52:30 +00005310 // Store the dragging window.
5311 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005312 if (pointerIds.count() != 1) {
5313 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5314 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005315 return false;
5316 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005317 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005318 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005319 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005320 }
5321
Arthur Hungabbb9d82021-09-01 14:52:30 +00005322 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005323 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5324 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005325 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005326 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005327 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005328 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005329 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005330 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005331 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5332 newTargetFlags);
5333
5334 // Check if the wallpaper window should deliver the corresponding event.
5335 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5336 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005337 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005338 } // release lock
5339
5340 // Wake up poll loop since it may need to make new input dispatching choices.
5341 mLooper->wake();
5342 return true;
5343}
5344
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005345/**
5346 * Get the touched foreground window on the given display.
5347 * Return null if there are no windows touched on that display, or if more than one foreground
5348 * window is being touched.
5349 */
5350sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5351 auto stateIt = mTouchStatesByDisplay.find(displayId);
5352 if (stateIt == mTouchStatesByDisplay.end()) {
5353 ALOGI("No touch state on display %" PRId32, displayId);
5354 return nullptr;
5355 }
5356
5357 const TouchState& state = stateIt->second;
5358 sp<WindowInfoHandle> touchedForegroundWindow;
5359 // If multiple foreground windows are touched, return nullptr
5360 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005361 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005362 if (touchedForegroundWindow != nullptr) {
5363 ALOGI("Two or more foreground windows: %s and %s",
5364 touchedForegroundWindow->getName().c_str(),
5365 window.windowHandle->getName().c_str());
5366 return nullptr;
5367 }
5368 touchedForegroundWindow = window.windowHandle;
5369 }
5370 }
5371 return touchedForegroundWindow;
5372}
5373
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005374// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005375bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005376 sp<IBinder> fromToken;
5377 { // acquire lock
5378 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005379 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005380 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005381 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5382 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005383 return false;
5384 }
5385
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005386 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5387 if (from == nullptr) {
5388 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5389 return false;
5390 }
5391
5392 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005393 } // release lock
5394
5395 return transferTouchFocus(fromToken, destChannelToken);
5396}
5397
Michael Wrightd02c5b62014-02-10 15:10:22 -08005398void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005399 if (DEBUG_FOCUS) {
5400 ALOGD("Resetting and dropping all events (%s).", reason);
5401 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005402
Michael Wrightfb04fd52022-11-24 22:31:11 +00005403 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005404 synthesizeCancelationEventsForAllConnectionsLocked(options);
5405
5406 resetKeyRepeatLocked();
5407 releasePendingEventLocked();
5408 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005409 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005411 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005412 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005413 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005414}
5415
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005416void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005417 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005418 dumpDispatchStateLocked(dump);
5419
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005420 std::istringstream stream(dump);
5421 std::string line;
5422
5423 while (std::getline(stream, line, '\n')) {
5424 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005425 }
5426}
5427
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005428std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005429 std::string dump;
5430
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005431 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5432 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005433
5434 std::string windowName = "None";
5435 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005436 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005437 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5438 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5439 : "token has capture without window";
5440 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005441 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005442
5443 return dump;
5444}
5445
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005446void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005447 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5448 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5449 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005450 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005451
Tiger Huang721e26f2018-07-24 22:26:19 +08005452 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5453 dump += StringPrintf(INDENT "FocusedApplications:\n");
5454 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5455 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005456 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005457 const std::chrono::duration timeout =
5458 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005459 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005460 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005461 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005463 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005464 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005465 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005466
Vishnu Nairc519ff72021-01-21 08:23:08 -08005467 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005468 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005469
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005470 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005471 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005472 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005473 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5474 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005475 }
5476 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005477 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005478 }
5479
arthurhung6d4bed92021-03-17 11:59:33 +08005480 if (mDragState) {
5481 dump += StringPrintf(INDENT "DragState:\n");
5482 mDragState->dump(dump, INDENT2);
5483 }
5484
Arthur Hungb92218b2018-08-14 12:00:21 +08005485 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005486 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5487 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5488 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5489 const auto& displayInfo = it->second;
5490 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5491 displayInfo.logicalHeight);
5492 displayInfo.transform.dump(dump, "transform", INDENT4);
5493 } else {
5494 dump += INDENT2 "No DisplayInfo found!\n";
5495 }
5496
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005497 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005498 dump += INDENT2 "Windows:\n";
5499 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005500 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5501 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005502
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005503 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005504 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005505 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005506 "applicationInfo.name=%s, "
5507 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005508 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005509 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005510 windowInfo->displayId,
5511 windowInfo->inputConfig.string().c_str(),
5512 windowInfo->alpha, windowInfo->frameLeft,
5513 windowInfo->frameTop, windowInfo->frameRight,
5514 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005515 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005516 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005517 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005518 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005519 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005520 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005521 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005522 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005523 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005524 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005525 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005526 }
5527 } else {
5528 dump += INDENT2 "Windows: <none>\n";
5529 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005530 }
5531 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005532 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005533 }
5534
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005535 if (!mGlobalMonitorsByDisplay.empty()) {
5536 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5537 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005538 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005539 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005540 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005541 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005542 }
5543
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005544 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005545
5546 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005547 if (!mRecentQueue.empty()) {
5548 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005549 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005550 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005551 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005552 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005553 }
5554 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005555 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005556 }
5557
5558 // Dump event currently being dispatched.
5559 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005560 dump += INDENT "PendingEvent:\n";
5561 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005562 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005563 dump += StringPrintf(", age=%" PRId64 "ms\n",
5564 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005565 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005566 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005567 }
5568
5569 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005570 if (!mInboundQueue.empty()) {
5571 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005572 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005573 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005574 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005575 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005576 }
5577 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005578 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005579 }
5580
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005581 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005582 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005583 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005584 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005585 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005586 }
5587 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005588 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005589 }
5590
Prabir Pradhancef936d2021-07-21 16:17:52 +00005591 if (!mCommandQueue.empty()) {
5592 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5593 } else {
5594 dump += INDENT "CommandQueue: <empty>\n";
5595 }
5596
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005597 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005598 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005599 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005600 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005601 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005602 connection->inputChannel->getFd().get(),
5603 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005604 connection->getWindowName().c_str(),
5605 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005606 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005608 if (!connection->outboundQueue.empty()) {
5609 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5610 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005611 dump += dumpQueue(connection->outboundQueue, currentTime);
5612
Michael Wrightd02c5b62014-02-10 15:10:22 -08005613 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005614 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005615 }
5616
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005617 if (!connection->waitQueue.empty()) {
5618 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5619 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005620 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005621 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005622 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005623 }
5624 }
5625 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005626 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005627 }
5628
5629 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005630 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5631 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005632 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005633 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005634 }
5635
Antonio Kantek15beb512022-06-13 22:35:41 +00005636 if (!mTouchModePerDisplay.empty()) {
5637 dump += INDENT "TouchModePerDisplay:\n";
5638 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5639 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5640 std::to_string(touchMode).c_str());
5641 }
5642 } else {
5643 dump += INDENT "TouchModePerDisplay: <none>\n";
5644 }
5645
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005646 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005647 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5648 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5649 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005650 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005651 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005652}
5653
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005654void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005655 const size_t numMonitors = monitors.size();
5656 for (size_t i = 0; i < numMonitors; i++) {
5657 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005658 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005659 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5660 dump += "\n";
5661 }
5662}
5663
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005664class LooperEventCallback : public LooperCallback {
5665public:
5666 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5667 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5668
5669private:
5670 std::function<int(int events)> mCallback;
5671};
5672
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005673Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005674 if (DEBUG_CHANNEL_CREATION) {
5675 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5676 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005677
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005678 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005679 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005680 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005681
5682 if (result) {
5683 return base::Error(result) << "Failed to open input channel pair with name " << name;
5684 }
5685
Michael Wrightd02c5b62014-02-10 15:10:22 -08005686 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005687 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005688 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005689 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005690 std::shared_ptr<Connection> connection =
5691 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5692 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005693
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005694 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5695 ALOGE("Created a new connection, but the token %p is already known", token.get());
5696 }
5697 mConnectionsByToken.emplace(token, connection);
5698
5699 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5700 this, std::placeholders::_1, token);
5701
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005702 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5703 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005704 } // release lock
5705
5706 // Wake the looper because some connections have changed.
5707 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005708 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005709}
5710
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005711Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005712 const std::string& name,
5713 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005714 std::shared_ptr<InputChannel> serverChannel;
5715 std::unique_ptr<InputChannel> clientChannel;
5716 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5717 if (result) {
5718 return base::Error(result) << "Failed to open input channel pair with name " << name;
5719 }
5720
Michael Wright3dd60e22019-03-27 22:06:44 +00005721 { // acquire lock
5722 std::scoped_lock _l(mLock);
5723
5724 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005725 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5726 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005727 }
5728
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005729 std::shared_ptr<Connection> connection =
5730 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005731 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005732 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005733
5734 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5735 ALOGE("Created a new connection, but the token %p is already known", token.get());
5736 }
5737 mConnectionsByToken.emplace(token, connection);
5738 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5739 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005740
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005741 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005742
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005743 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5744 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005745 }
Garfield Tan15601662020-09-22 15:32:38 -07005746
Michael Wright3dd60e22019-03-27 22:06:44 +00005747 // Wake the looper because some connections have changed.
5748 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005749 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005750}
5751
Garfield Tan15601662020-09-22 15:32:38 -07005752status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005753 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005754 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005755
Harry Cutts33476232023-01-30 19:57:29 +00005756 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005757 if (status) {
5758 return status;
5759 }
5760 } // release lock
5761
5762 // Wake the poll loop because removing the connection may have changed the current
5763 // synchronization state.
5764 mLooper->wake();
5765 return OK;
5766}
5767
Garfield Tan15601662020-09-22 15:32:38 -07005768status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5769 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005770 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005771 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005772 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005773 return BAD_VALUE;
5774 }
5775
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005776 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005777
Michael Wrightd02c5b62014-02-10 15:10:22 -08005778 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005779 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005780 }
5781
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005782 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783
5784 nsecs_t currentTime = now();
5785 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5786
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005787 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005788 return OK;
5789}
5790
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005791void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005792 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5793 auto& [displayId, monitors] = *it;
5794 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5795 return monitor.inputChannel->getConnectionToken() == connectionToken;
5796 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005797
Michael Wright3dd60e22019-03-27 22:06:44 +00005798 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005799 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005800 } else {
5801 ++it;
5802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005803 }
5804}
5805
Michael Wright3dd60e22019-03-27 22:06:44 +00005806status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005807 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005808 return pilferPointersLocked(token);
5809}
Michael Wright3dd60e22019-03-27 22:06:44 +00005810
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005811status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005812 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5813 if (!requestingChannel) {
5814 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5815 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005816 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005817
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005818 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005819 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.none()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005820 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5821 " Ignoring.");
5822 return BAD_VALUE;
5823 }
5824
5825 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005826 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005827 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005828 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005829 "input channel stole pointer stream");
5830 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005831 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005832 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005833 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005834 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005835 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005836 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005837 if (channel != nullptr && channel->getConnectionToken() != token) {
5838 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5839 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5840 canceledWindows += channel->getName();
5841 }
5842 }
5843 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5844 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5845 canceledWindows.c_str());
5846
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005847 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005848 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005849 window.pilferedPointerIds |= window.pointerIds;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005850
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005851 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005852 return OK;
5853}
5854
Prabir Pradhan99987712020-11-10 18:43:05 -08005855void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5856 { // acquire lock
5857 std::scoped_lock _l(mLock);
5858 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005859 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005860 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5861 windowHandle != nullptr ? windowHandle->getName().c_str()
5862 : "token without window");
5863 }
5864
Vishnu Nairc519ff72021-01-21 08:23:08 -08005865 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005866 if (focusedToken != windowToken) {
5867 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5868 enabled ? "enable" : "disable");
5869 return;
5870 }
5871
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005872 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005873 ALOGW("Ignoring request to %s Pointer Capture: "
5874 "window has %s requested pointer capture.",
5875 enabled ? "enable" : "disable", enabled ? "already" : "not");
5876 return;
5877 }
5878
Christine Franksb768bb42021-11-29 12:11:31 -08005879 if (enabled) {
5880 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5881 mIneligibleDisplaysForPointerCapture.end(),
5882 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5883 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5884 return;
5885 }
5886 }
5887
Prabir Pradhan99987712020-11-10 18:43:05 -08005888 setPointerCaptureLocked(enabled);
5889 } // release lock
5890
5891 // Wake the thread to process command entries.
5892 mLooper->wake();
5893}
5894
Christine Franksb768bb42021-11-29 12:11:31 -08005895void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5896 { // acquire lock
5897 std::scoped_lock _l(mLock);
5898 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5899 if (!isEligible) {
5900 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5901 }
5902 } // release lock
5903}
5904
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005905std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5906 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005907 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005908 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005909 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005910 }
5911 }
5912 }
5913 return std::nullopt;
5914}
5915
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005916std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
5917 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005918 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005919 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005920 }
5921
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005922 for (const auto& [token, connection] : mConnectionsByToken) {
5923 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005924 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005925 }
5926 }
Robert Carr4e670e52018-08-15 13:26:12 -07005927
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005928 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005929}
5930
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005931std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005932 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005933 if (connection == nullptr) {
5934 return "<nullptr>";
5935 }
5936 return connection->getInputChannelName();
5937}
5938
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005939void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005940 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005941 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005942}
5943
Prabir Pradhancef936d2021-07-21 16:17:52 +00005944void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005945 const std::shared_ptr<Connection>& connection,
5946 uint32_t seq, bool handled,
5947 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005948 // Handle post-event policy actions.
5949 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5950 if (dispatchEntryIt == connection->waitQueue.end()) {
5951 return;
5952 }
5953 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5954 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5955 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5956 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5957 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5958 }
5959 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5960 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5961 connection->inputChannel->getConnectionToken(),
5962 dispatchEntry->deliveryTime, consumeTime, finishTime);
5963 }
5964
5965 bool restartEvent;
5966 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5967 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5968 restartEvent =
5969 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5970 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5971 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5972 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5973 handled);
5974 } else {
5975 restartEvent = false;
5976 }
5977
5978 // Dequeue the event and start the next cycle.
5979 // Because the lock might have been released, it is possible that the
5980 // contents of the wait queue to have been drained, so we need to double-check
5981 // a few things.
5982 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5983 if (dispatchEntryIt != connection->waitQueue.end()) {
5984 dispatchEntry = *dispatchEntryIt;
5985 connection->waitQueue.erase(dispatchEntryIt);
5986 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5987 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5988 if (!connection->responsive) {
5989 connection->responsive = isConnectionResponsive(*connection);
5990 if (connection->responsive) {
5991 // The connection was unresponsive, and now it's responsive.
5992 processConnectionResponsiveLocked(*connection);
5993 }
5994 }
5995 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005996 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005997 connection->outboundQueue.push_front(dispatchEntry);
5998 traceOutboundQueueLength(*connection);
5999 } else {
6000 releaseDispatchEntry(dispatchEntry);
6001 }
6002 }
6003
6004 // Start the next dispatch cycle for this connection.
6005 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006006}
6007
Prabir Pradhancef936d2021-07-21 16:17:52 +00006008void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6009 const sp<IBinder>& newToken) {
6010 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6011 scoped_unlock unlock(mLock);
6012 mPolicy->notifyFocusChanged(oldToken, newToken);
6013 };
6014 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006015}
6016
Prabir Pradhancef936d2021-07-21 16:17:52 +00006017void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6018 auto command = [this, token, x, y]() REQUIRES(mLock) {
6019 scoped_unlock unlock(mLock);
6020 mPolicy->notifyDropWindow(token, x, y);
6021 };
6022 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006023}
6024
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006025void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006026 if (connection == nullptr) {
6027 LOG_ALWAYS_FATAL("Caller must check for nullness");
6028 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006029 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6030 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006031 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006032 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006033 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006034 return;
6035 }
6036 /**
6037 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6038 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6039 * has changed. This could cause newer entries to time out before the already dispatched
6040 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6041 * processes the events linearly. So providing information about the oldest entry seems to be
6042 * most useful.
6043 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006044 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006045 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6046 std::string reason =
6047 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006048 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006049 ns2ms(currentWait),
6050 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006051 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006052 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006053
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006054 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6055
6056 // Stop waking up for events on this connection, it is already unresponsive
6057 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006058}
6059
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006060void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6061 std::string reason =
6062 StringPrintf("%s does not have a focused window", application->getName().c_str());
6063 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006064
Prabir Pradhancef936d2021-07-21 16:17:52 +00006065 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
6066 scoped_unlock unlock(mLock);
6067 mPolicy->notifyNoFocusedWindowAnr(application);
6068 };
6069 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006070}
6071
chaviw98318de2021-05-19 16:45:23 -05006072void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006073 const std::string& reason) {
6074 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6075 updateLastAnrStateLocked(windowLabel, reason);
6076}
6077
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006078void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6079 const std::string& reason) {
6080 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006081 updateLastAnrStateLocked(windowLabel, reason);
6082}
6083
6084void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6085 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006086 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006087 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006088 struct tm tm;
6089 localtime_r(&t, &tm);
6090 char timestr[64];
6091 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006092 mLastAnrState.clear();
6093 mLastAnrState += INDENT "ANR:\n";
6094 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006095 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6096 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006097 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006098}
6099
Prabir Pradhancef936d2021-07-21 16:17:52 +00006100void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6101 KeyEntry& entry) {
6102 const KeyEvent event = createKeyEvent(entry);
6103 nsecs_t delay = 0;
6104 { // release lock
6105 scoped_unlock unlock(mLock);
6106 android::base::Timer t;
6107 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
6108 entry.policyFlags);
6109 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6110 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6111 std::to_string(t.duration().count()).c_str());
6112 }
6113 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006114
6115 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006116 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006117 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006118 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006119 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006120 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006121 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006122 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006123}
6124
Prabir Pradhancef936d2021-07-21 16:17:52 +00006125void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006126 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006127 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006128 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006129 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006130 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006131 };
6132 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006133}
6134
Prabir Pradhanedd96402022-02-15 01:46:16 -08006135void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6136 std::optional<int32_t> pid) {
6137 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006138 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006139 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006140 };
6141 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006142}
6143
6144/**
6145 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6146 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6147 * command entry to the command queue.
6148 */
6149void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6150 std::string reason) {
6151 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006152 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006153 if (connection.monitor) {
6154 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6155 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006156 pid = findMonitorPidByTokenLocked(connectionToken);
6157 } else {
6158 // The connection is a window
6159 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6160 reason.c_str());
6161 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6162 if (handle != nullptr) {
6163 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006164 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006165 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006166 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006167}
6168
6169/**
6170 * Tell the policy that a connection has become responsive so that it can stop ANR.
6171 */
6172void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6173 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006174 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006175 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006176 pid = findMonitorPidByTokenLocked(connectionToken);
6177 } else {
6178 // The connection is a window
6179 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6180 if (handle != nullptr) {
6181 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006182 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006183 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006184 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006185}
6186
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006187bool InputDispatcher::afterKeyEventLockedInterruptable(
6188 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6189 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006190 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006191 if (!handled) {
6192 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006193 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006194 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006195 return false;
6196 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006197
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006198 // Get the fallback key state.
6199 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006200 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006201 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006202 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006203 connection->inputState.removeFallbackKey(originalKeyCode);
6204 }
6205
6206 if (handled || !dispatchEntry->hasForegroundTarget()) {
6207 // If the application handles the original key for which we previously
6208 // generated a fallback or if the window is not a foreground window,
6209 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006210 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006211 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006212 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6213 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6214 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6215 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6216 keyEntry.policyFlags);
6217 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006218 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006219 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006220
6221 mLock.unlock();
6222
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006223 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006224 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006225
6226 mLock.lock();
6227
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006228 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006229 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006230 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006231 "application handled the original non-fallback key "
6232 "or is no longer a foreground target, "
6233 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006234 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006235 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006236 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006237 connection->inputState.removeFallbackKey(originalKeyCode);
6238 }
6239 } else {
6240 // If the application did not handle a non-fallback key, first check
6241 // that we are in a good state to perform unhandled key event processing
6242 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006243 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006244 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006245 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6246 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6247 "since this is not an initial down. "
6248 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6249 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6250 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006251 return false;
6252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006253
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006254 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006255 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6256 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6257 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6258 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6259 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006260 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006261
6262 mLock.unlock();
6263
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006264 bool fallback =
6265 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006266 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006267
6268 mLock.lock();
6269
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006270 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006271 connection->inputState.removeFallbackKey(originalKeyCode);
6272 return false;
6273 }
6274
6275 // Latch the fallback keycode for this key on an initial down.
6276 // The fallback keycode cannot change at any other point in the lifecycle.
6277 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006278 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006279 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006280 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006281 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006282 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006283 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006284 }
6285
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006286 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006287
6288 // Cancel the fallback key if the policy decides not to send it anymore.
6289 // We will continue to dispatch the key to the policy but we will no
6290 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006291 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6292 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006293 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6294 if (fallback) {
6295 ALOGD("Unhandled key event: Policy requested to send key %d"
6296 "as a fallback for %d, but on the DOWN it had requested "
6297 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006298 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006299 } else {
6300 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6301 "but on the DOWN it had requested to send %d. "
6302 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006303 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006304 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006305 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006306
Michael Wrightfb04fd52022-11-24 22:31:11 +00006307 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006308 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006309 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006310 synthesizeCancelationEventsForConnectionLocked(connection, options);
6311
6312 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006313 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006314 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006315 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006316 }
6317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006318
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006319 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6320 {
6321 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006322 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006323 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006324 for (const auto& [key, value] : fallbackKeys) {
6325 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006326 }
6327 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6328 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006329 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006330 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006331
6332 if (fallback) {
6333 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006334 keyEntry.eventTime = event.getEventTime();
6335 keyEntry.deviceId = event.getDeviceId();
6336 keyEntry.source = event.getSource();
6337 keyEntry.displayId = event.getDisplayId();
6338 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006339 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006340 keyEntry.scanCode = event.getScanCode();
6341 keyEntry.metaState = event.getMetaState();
6342 keyEntry.repeatCount = event.getRepeatCount();
6343 keyEntry.downTime = event.getDownTime();
6344 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006345
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006346 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6347 ALOGD("Unhandled key event: Dispatching fallback key. "
6348 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006349 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006350 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006351 return true; // restart the event
6352 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006353 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6354 ALOGD("Unhandled key event: No fallback key.");
6355 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006356
6357 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006358 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006359 }
6360 }
6361 return false;
6362}
6363
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006364bool InputDispatcher::afterMotionEventLockedInterruptable(
6365 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6366 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006367 return false;
6368}
6369
Michael Wrightd02c5b62014-02-10 15:10:22 -08006370void InputDispatcher::traceInboundQueueLengthLocked() {
6371 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006372 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006373 }
6374}
6375
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006376void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006377 if (ATRACE_ENABLED()) {
6378 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006379 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6380 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006381 }
6382}
6383
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006384void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006385 if (ATRACE_ENABLED()) {
6386 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006387 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6388 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006389 }
6390}
6391
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006392void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006393 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006394
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006395 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006396 dumpDispatchStateLocked(dump);
6397
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006398 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006399 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006400 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006401 }
6402}
6403
6404void InputDispatcher::monitor() {
6405 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006406 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006407 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006408 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006409}
6410
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006411/**
6412 * Wake up the dispatcher and wait until it processes all events and commands.
6413 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6414 * this method can be safely called from any thread, as long as you've ensured that
6415 * the work you are interested in completing has already been queued.
6416 */
6417bool InputDispatcher::waitForIdle() {
6418 /**
6419 * Timeout should represent the longest possible time that a device might spend processing
6420 * events and commands.
6421 */
6422 constexpr std::chrono::duration TIMEOUT = 100ms;
6423 std::unique_lock lock(mLock);
6424 mLooper->wake();
6425 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6426 return result == std::cv_status::no_timeout;
6427}
6428
Vishnu Naire798b472020-07-23 13:52:21 -07006429/**
6430 * Sets focus to the window identified by the token. This must be called
6431 * after updating any input window handles.
6432 *
6433 * Params:
6434 * request.token - input channel token used to identify the window that should gain focus.
6435 * request.focusedToken - the token that the caller expects currently to be focused. If the
6436 * specified token does not match the currently focused window, this request will be dropped.
6437 * If the specified focused token matches the currently focused window, the call will succeed.
6438 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6439 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6440 * when requesting the focus change. This determines which request gets
6441 * precedence if there is a focus change request from another source such as pointer down.
6442 */
Vishnu Nair958da932020-08-21 17:12:37 -07006443void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6444 { // acquire lock
6445 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006446 std::optional<FocusResolver::FocusChanges> changes =
6447 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6448 if (changes) {
6449 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006450 }
6451 } // release lock
6452 // Wake up poll loop since it may need to make new input dispatching choices.
6453 mLooper->wake();
6454}
6455
Vishnu Nairc519ff72021-01-21 08:23:08 -08006456void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6457 if (changes.oldFocus) {
6458 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006459 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006460 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006461 "focus left window");
6462 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006463 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006464 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006465 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006466 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006467 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006468 }
6469
Prabir Pradhan99987712020-11-10 18:43:05 -08006470 // If a window has pointer capture, then it must have focus. We need to ensure that this
6471 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6472 // If the window loses focus before it loses pointer capture, then the window can be in a state
6473 // where it has pointer capture but not focus, violating the contract. Therefore we must
6474 // dispatch the pointer capture event before the focus event. Since focus events are added to
6475 // the front of the queue (above), we add the pointer capture event to the front of the queue
6476 // after the focus events are added. This ensures the pointer capture event ends up at the
6477 // front.
6478 disablePointerCaptureForcedLocked();
6479
Vishnu Nairc519ff72021-01-21 08:23:08 -08006480 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006481 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006482 }
6483}
Vishnu Nair958da932020-08-21 17:12:37 -07006484
Prabir Pradhan99987712020-11-10 18:43:05 -08006485void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006486 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006487 return;
6488 }
6489
6490 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6491
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006492 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006493 setPointerCaptureLocked(false);
6494 }
6495
6496 if (!mWindowTokenWithPointerCapture) {
6497 // No need to send capture changes because no window has capture.
6498 return;
6499 }
6500
6501 if (mPendingEvent != nullptr) {
6502 // Move the pending event to the front of the queue. This will give the chance
6503 // for the pending event to be dropped if it is a captured event.
6504 mInboundQueue.push_front(mPendingEvent);
6505 mPendingEvent = nullptr;
6506 }
6507
6508 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006509 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006510 mInboundQueue.push_front(std::move(entry));
6511}
6512
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006513void InputDispatcher::setPointerCaptureLocked(bool enable) {
6514 mCurrentPointerCaptureRequest.enable = enable;
6515 mCurrentPointerCaptureRequest.seq++;
6516 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006517 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006518 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006519 };
6520 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006521}
6522
Vishnu Nair599f1412021-06-21 10:39:58 -07006523void InputDispatcher::displayRemoved(int32_t displayId) {
6524 { // acquire lock
6525 std::scoped_lock _l(mLock);
6526 // Set an empty list to remove all handles from the specific display.
6527 setInputWindowsLocked(/* window handles */ {}, displayId);
6528 setFocusedApplicationLocked(displayId, nullptr);
6529 // Call focus resolver to clean up stale requests. This must be called after input windows
6530 // have been removed for the removed display.
6531 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006532 // Reset pointer capture eligibility, regardless of previous state.
6533 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006534 // Remove the associated touch mode state.
6535 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006536 } // release lock
6537
6538 // Wake up poll loop since it may need to make new input dispatching choices.
6539 mLooper->wake();
6540}
6541
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006542void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6543 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006544 // The listener sends the windows as a flattened array. Separate the windows by display for
6545 // more convenient parsing.
6546 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006547 for (const auto& info : windowInfos) {
6548 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006549 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006550 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006551
6552 { // acquire lock
6553 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006554
6555 // Ensure that we have an entry created for all existing displays so that if a displayId has
6556 // no windows, we can tell that the windows were removed from the display.
6557 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6558 handlesPerDisplay[displayId];
6559 }
6560
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006561 mDisplayInfos.clear();
6562 for (const auto& displayInfo : displayInfos) {
6563 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6564 }
6565
6566 for (const auto& [displayId, handles] : handlesPerDisplay) {
6567 setInputWindowsLocked(handles, displayId);
6568 }
6569 }
6570 // Wake up poll loop since it may need to make new input dispatching choices.
6571 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006572}
6573
Vishnu Nair062a8672021-09-03 16:07:44 -07006574bool InputDispatcher::shouldDropInput(
6575 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006576 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6577 (windowHandle->getInfo()->inputConfig.test(
6578 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006579 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006580 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6581 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006582 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006583 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006584 windowHandle->getInfo()->displayId);
6585 return true;
6586 }
6587 return false;
6588}
6589
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006590void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6591 const std::vector<gui::WindowInfo>& windowInfos,
6592 const std::vector<DisplayInfo>& displayInfos) {
6593 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6594}
6595
Arthur Hungdfd528e2021-12-08 13:23:04 +00006596void InputDispatcher::cancelCurrentTouch() {
6597 {
6598 std::scoped_lock _l(mLock);
6599 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006600 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006601 "cancel current touch");
6602 synthesizeCancelationEventsForAllConnectionsLocked(options);
6603
6604 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006605 }
6606 // Wake up poll loop since there might be work to do.
6607 mLooper->wake();
6608}
6609
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006610void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6611 std::scoped_lock _l(mLock);
6612 mMonitorDispatchingTimeout = timeout;
6613}
6614
Arthur Hungc539dbb2022-12-08 07:45:36 +00006615void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6616 const sp<WindowInfoHandle>& oldWindowHandle,
6617 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006618 TouchState& state, int32_t pointerId,
6619 std::vector<InputTarget>& targets) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006620 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6621 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006622 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6623 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6624 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6625 newWindowHandle->getInfo()->inputConfig.test(
6626 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6627 const sp<WindowInfoHandle> oldWallpaper =
6628 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6629 const sp<WindowInfoHandle> newWallpaper =
6630 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6631 if (oldWallpaper == newWallpaper) {
6632 return;
6633 }
6634
6635 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006636 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6637 addWindowTargetLocked(oldWallpaper,
6638 oldTouchedWindow.targetFlags |
6639 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6640 pointerIds, oldTouchedWindow.firstDownTimeInTarget, targets);
6641 state.removeTouchedPointerFromWindow(pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006642 }
6643
6644 if (newWallpaper != nullptr) {
6645 state.addOrUpdateWindow(newWallpaper,
6646 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6647 InputTarget::Flags::WINDOW_IS_OBSCURED |
6648 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6649 pointerIds);
6650 }
6651}
6652
6653void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6654 ftl::Flags<InputTarget::Flags> newTargetFlags,
6655 const sp<WindowInfoHandle> fromWindowHandle,
6656 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006657 TouchState& state,
6658 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006659 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6660 fromWindowHandle->getInfo()->inputConfig.test(
6661 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6662 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6663 toWindowHandle->getInfo()->inputConfig.test(
6664 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6665
6666 const sp<WindowInfoHandle> oldWallpaper =
6667 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6668 const sp<WindowInfoHandle> newWallpaper =
6669 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6670 if (oldWallpaper == newWallpaper) {
6671 return;
6672 }
6673
6674 if (oldWallpaper != nullptr) {
6675 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6676 "transferring touch focus to another window");
6677 state.removeWindowByToken(oldWallpaper->getToken());
6678 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6679 }
6680
6681 if (newWallpaper != nullptr) {
6682 nsecs_t downTimeInTarget = now();
6683 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6684 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6685 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6686 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6687 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006688 std::shared_ptr<Connection> wallpaperConnection =
6689 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006690 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006691 std::shared_ptr<Connection> toConnection =
6692 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006693 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6694 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6695 wallpaperFlags);
6696 }
6697 }
6698}
6699
6700sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6701 const sp<WindowInfoHandle>& windowHandle) const {
6702 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6703 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6704 bool foundWindow = false;
6705 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6706 if (!foundWindow && otherHandle != windowHandle) {
6707 continue;
6708 }
6709 if (windowHandle == otherHandle) {
6710 foundWindow = true;
6711 continue;
6712 }
6713
6714 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6715 return otherHandle;
6716 }
6717 }
6718 return nullptr;
6719}
6720
Garfield Tane84e6f92019-08-29 17:28:41 -07006721} // namespace android::inputdispatcher