blob: af3819d607950c780d9ad40f20ada4749c628e6d [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}
680
681InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000682 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800683
Prabir Pradhancef936d2021-07-21 16:17:52 +0000684 resetKeyRepeatLocked();
685 releasePendingEventLocked();
686 drainInboundQueueLocked();
687 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000689 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700690 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000691 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 }
693}
694
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700695status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700696 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700697 return ALREADY_EXISTS;
698 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700699 mThread = std::make_unique<InputThread>(
700 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
701 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700702}
703
704status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700705 if (mThread && mThread->isCallingThread()) {
706 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700707 return INVALID_OPERATION;
708 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700709 mThread.reset();
710 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700711}
712
Michael Wrightd02c5b62014-02-10 15:10:22 -0800713void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700714 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800715 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800716 std::scoped_lock _l(mLock);
717 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718
719 // Run a dispatch loop if there are no pending commands.
720 // The dispatch loop might enqueue commands to run afterwards.
721 if (!haveCommandsLocked()) {
722 dispatchOnceInnerLocked(&nextWakeupTime);
723 }
724
725 // Run all pending commands if there are any.
726 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000727 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700728 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800729 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800730
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700731 // If we are still waiting for ack on some events,
732 // we might have to wake up earlier to check if an app is anr'ing.
733 const nsecs_t nextAnrCheck = processAnrsLocked();
734 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
735
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800736 // We are about to enter an infinitely long sleep, because we have no commands or
737 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700738 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800739 mDispatcherEnteredIdle.notify_all();
740 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800741 } // release lock
742
743 // Wait for callback or timeout or wake. (make sure we round up, not down)
744 nsecs_t currentTime = now();
745 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
746 mLooper->pollOnce(timeoutMillis);
747}
748
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700749/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500750 * Raise ANR if there is no focused window.
751 * Before the ANR is raised, do a final state check:
752 * 1. The currently focused application must be the same one we are waiting for.
753 * 2. Ensure we still don't have a focused window.
754 */
755void InputDispatcher::processNoFocusedWindowAnrLocked() {
756 // Check if the application that we are waiting for is still focused.
757 std::shared_ptr<InputApplicationHandle> focusedApplication =
758 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
759 if (focusedApplication == nullptr ||
760 focusedApplication->getApplicationToken() !=
761 mAwaitedFocusedApplication->getApplicationToken()) {
762 // Unexpected because we should have reset the ANR timer when focused application changed
763 ALOGE("Waited for a focused window, but focused application has already changed to %s",
764 focusedApplication->getName().c_str());
765 return; // The focused application has changed.
766 }
767
chaviw98318de2021-05-19 16:45:23 -0500768 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500769 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
770 if (focusedWindowHandle != nullptr) {
771 return; // We now have a focused window. No need for ANR.
772 }
773 onAnrLocked(mAwaitedFocusedApplication);
774}
775
776/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700777 * Check if any of the connections' wait queues have events that are too old.
778 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
779 * Return the time at which we should wake up next.
780 */
781nsecs_t InputDispatcher::processAnrsLocked() {
782 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700783 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700784 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
785 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
786 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500787 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700788 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500789 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700790 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700791 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500792 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700793 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
794 }
795 }
796
797 // Check if any connection ANRs are due
798 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
799 if (currentTime < nextAnrCheck) { // most likely scenario
800 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
801 }
802
803 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700804 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700805 if (connection == nullptr) {
806 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
807 return nextAnrCheck;
808 }
809 connection->responsive = false;
810 // Stop waking up for this unresponsive connection
811 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000812 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700813 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700814}
815
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800816std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700817 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800818 if (connection->monitor) {
819 return mMonitorDispatchingTimeout;
820 }
821 const sp<WindowInfoHandle> window =
822 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700823 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500824 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700825 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500826 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700827}
828
Michael Wrightd02c5b62014-02-10 15:10:22 -0800829void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
830 nsecs_t currentTime = now();
831
Jeff Browndc5992e2014-04-11 01:27:26 -0700832 // Reset the key repeat timer whenever normal dispatch is suspended while the
833 // device is in a non-interactive state. This is to ensure that we abort a key
834 // repeat if the device is just coming out of sleep.
835 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800836 resetKeyRepeatLocked();
837 }
838
839 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
840 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100841 if (DEBUG_FOCUS) {
842 ALOGD("Dispatch frozen. Waiting some more.");
843 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800844 return;
845 }
846
847 // Optimize latency of app switches.
848 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
849 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
850 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
851 if (mAppSwitchDueTime < *nextWakeupTime) {
852 *nextWakeupTime = mAppSwitchDueTime;
853 }
854
855 // Ready to start a new event.
856 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700857 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700858 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800859 if (isAppSwitchDue) {
860 // The inbound queue is empty so the app switch key we were waiting
861 // for will never arrive. Stop waiting for it.
862 resetPendingAppSwitchLocked(false);
863 isAppSwitchDue = false;
864 }
865
866 // Synthesize a key repeat if appropriate.
867 if (mKeyRepeatState.lastKeyEntry) {
868 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
869 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
870 } else {
871 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
872 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
873 }
874 }
875 }
876
877 // Nothing to do if there is no pending event.
878 if (!mPendingEvent) {
879 return;
880 }
881 } else {
882 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700883 mPendingEvent = mInboundQueue.front();
884 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800885 traceInboundQueueLengthLocked();
886 }
887
888 // Poke user activity for this event.
889 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700890 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892 }
893
894 // Now we have an event to dispatch.
895 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700896 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700898 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700900 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700902 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800903 }
904
905 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700906 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907 }
908
909 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700910 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700911 const ConfigurationChangedEntry& typedEntry =
912 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700913 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700914 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700915 break;
916 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800917
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700918 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700919 const DeviceResetEntry& typedEntry =
920 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700921 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700922 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700923 break;
924 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100926 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700927 std::shared_ptr<FocusEntry> typedEntry =
928 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100929 dispatchFocusLocked(currentTime, typedEntry);
930 done = true;
931 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
932 break;
933 }
934
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700935 case EventEntry::Type::TOUCH_MODE_CHANGED: {
936 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
937 dispatchTouchModeChangeLocked(currentTime, typedEntry);
938 done = true;
939 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
940 break;
941 }
942
Prabir Pradhan99987712020-11-10 18:43:05 -0800943 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
944 const auto typedEntry =
945 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
946 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
947 done = true;
948 break;
949 }
950
arthurhungb89ccb02020-12-30 16:19:01 +0800951 case EventEntry::Type::DRAG: {
952 std::shared_ptr<DragEntry> typedEntry =
953 std::static_pointer_cast<DragEntry>(mPendingEvent);
954 dispatchDragLocked(currentTime, typedEntry);
955 done = true;
956 break;
957 }
958
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700959 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700960 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700961 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700962 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700963 resetPendingAppSwitchLocked(true);
964 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700965 } else if (dropReason == DropReason::NOT_DROPPED) {
966 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700967 }
968 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700969 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700970 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700971 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700972 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
973 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700974 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700975 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700976 break;
977 }
978
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700979 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700980 std::shared_ptr<MotionEntry> motionEntry =
981 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700982 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
983 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700985 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700986 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700987 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700988 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
989 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700990 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700991 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700992 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993 }
Chris Yef59a2f42020-10-16 12:55:26 -0700994
995 case EventEntry::Type::SENSOR: {
996 std::shared_ptr<SensorEntry> sensorEntry =
997 std::static_pointer_cast<SensorEntry>(mPendingEvent);
998 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
999 dropReason = DropReason::APP_SWITCH;
1000 }
1001 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1002 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1003 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1004 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1005 dropReason = DropReason::STALE;
1006 }
1007 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1008 done = true;
1009 break;
1010 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011 }
1012
1013 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001014 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001015 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016 }
Michael Wright3a981722015-06-10 15:26:13 +01001017 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018
1019 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001020 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021 }
1022}
1023
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001024bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1025 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1026}
1027
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001028/**
1029 * Return true if the events preceding this incoming motion event should be dropped
1030 * Return false otherwise (the default behaviour)
1031 */
1032bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001033 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001034 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001035
1036 // Optimize case where the current application is unresponsive and the user
1037 // decides to touch a window in a different application.
1038 // If the application takes too long to catch up then we drop all events preceding
1039 // the touch into the other window.
1040 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001041 const int32_t displayId = motionEntry.displayId;
1042 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001043 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001044
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001045 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001046 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001047 touchedWindowHandle->getApplicationToken() !=
1048 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001049 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001050 ALOGI("Pruning input queue because user touched a different application while waiting "
1051 "for %s",
1052 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001053 return true;
1054 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001055
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001056 // Alternatively, maybe there's a spy window that could handle this event.
1057 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1058 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1059 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001060 const std::shared_ptr<Connection> connection =
1061 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001062 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001063 // This spy window could take more input. Drop all events preceding this
1064 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001065 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001066 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001067 mAwaitedFocusedApplication->getName().c_str());
1068 return true;
1069 }
1070 }
1071 }
1072
1073 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1074 // yet been processed by some connections, the dispatcher will wait for these motion
1075 // events to be processed before dispatching the key event. This is because these motion events
1076 // may cause a new window to be launched, which the user might expect to receive focus.
1077 // To prevent waiting forever for such events, just send the key to the currently focused window
1078 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1079 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1080 "just send the pending key event to the focused window.");
1081 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001082 }
1083 return false;
1084}
1085
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001086bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001087 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001088 mInboundQueue.push_back(std::move(newEntry));
1089 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090 traceInboundQueueLengthLocked();
1091
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001092 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001093 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001094 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1095 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001096 // Optimize app switch latency.
1097 // If the application takes too long to catch up then we drop all events preceding
1098 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001099 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001100 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001101 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001102 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001103 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001104 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001105 if (DEBUG_APP_SWITCH) {
1106 ALOGD("App switch is pending!");
1107 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001108 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001109 mAppSwitchSawKeyDown = false;
1110 needWake = true;
1111 }
1112 }
1113 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001114
1115 // If a new up event comes in, and the pending event with same key code has been asked
1116 // to try again later because of the policy. We have to reset the intercept key wake up
1117 // time for it may have been handled in the policy and could be dropped.
1118 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1119 mPendingEvent->type == EventEntry::Type::KEY) {
1120 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1121 if (pendingKey.keyCode == keyEntry.keyCode &&
1122 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001123 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1124 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001125 pendingKey.interceptKeyWakeupTime = 0;
1126 needWake = true;
1127 }
1128 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001129 break;
1130 }
1131
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001132 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001133 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1134 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001135 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1136 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001137 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001138 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001139 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001141 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001142 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1143 break;
1144 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001145 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001146 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001147 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001148 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001149 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1150 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001151 // nothing to do
1152 break;
1153 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 }
1155
1156 return needWake;
1157}
1158
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001159void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001160 // Do not store sensor event in recent queue to avoid flooding the queue.
1161 if (entry->type != EventEntry::Type::SENSOR) {
1162 mRecentQueue.push_back(entry);
1163 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001164 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001165 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001166 }
1167}
1168
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001169std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001170InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001171 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001172 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001173 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001174 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001175 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001176 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001177 continue;
1178 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001180 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001181 if (!info.isSpy() &&
1182 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001183 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001184 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001185
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001186 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1187 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001188 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001189 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 }
1191 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001192 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193}
1194
Prabir Pradhand65552b2021-10-07 11:23:50 -07001195std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001196 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001197 // Traverse windows from front to back and gather the touched spy windows.
1198 std::vector<sp<WindowInfoHandle>> spyWindows;
1199 const auto& windowHandles = getWindowHandlesLocked(displayId);
1200 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1201 const WindowInfo& info = *windowHandle->getInfo();
1202
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001203 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001204 continue;
1205 }
1206 if (!info.isSpy()) {
1207 // The first touched non-spy window was found, so return the spy windows touched so far.
1208 return spyWindows;
1209 }
1210 spyWindows.push_back(windowHandle);
1211 }
1212 return spyWindows;
1213}
1214
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001215void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216 const char* reason;
1217 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001218 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001219 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001220 ALOGD("Dropped event because policy consumed it.");
1221 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001222 reason = "inbound event was dropped because the policy consumed it";
1223 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001224 case DropReason::DISABLED:
1225 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001226 ALOGI("Dropped event because input dispatch is disabled.");
1227 }
1228 reason = "inbound event was dropped because input dispatch is disabled";
1229 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001230 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001231 ALOGI("Dropped event because of pending overdue app switch.");
1232 reason = "inbound event was dropped because of pending overdue app switch";
1233 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001234 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001235 ALOGI("Dropped event because the current application is not responding and the user "
1236 "has started interacting with a different application.");
1237 reason = "inbound event was dropped because the current application is not responding "
1238 "and the user has started interacting with a different application";
1239 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001240 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001241 ALOGI("Dropped event because it is stale.");
1242 reason = "inbound event was dropped because it is stale";
1243 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001244 case DropReason::NO_POINTER_CAPTURE:
1245 ALOGI("Dropped event because there is no window with Pointer Capture.");
1246 reason = "inbound event was dropped because there is no window with Pointer Capture";
1247 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001248 case DropReason::NOT_DROPPED: {
1249 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001250 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001251 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 }
1253
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001254 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001255 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001256 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001258 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001260 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001261 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1262 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001263 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001264 synthesizeCancelationEventsForAllConnectionsLocked(options);
1265 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001266 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1267 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001268 synthesizeCancelationEventsForAllConnectionsLocked(options);
1269 }
1270 break;
1271 }
Chris Yef59a2f42020-10-16 12:55:26 -07001272 case EventEntry::Type::SENSOR: {
1273 break;
1274 }
arthurhungb89ccb02020-12-30 16:19:01 +08001275 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1276 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001277 break;
1278 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001279 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001280 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001281 case EventEntry::Type::CONFIGURATION_CHANGED:
1282 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001283 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001284 break;
1285 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286 }
1287}
1288
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001289static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001290 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1291 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001292}
1293
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001294bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1295 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1296 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1297 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298}
1299
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001300bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001301 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302}
1303
1304void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001305 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001307 if (DEBUG_APP_SWITCH) {
1308 if (handled) {
1309 ALOGD("App switch has arrived.");
1310 } else {
1311 ALOGD("App switch was abandoned.");
1312 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001314}
1315
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001317 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318}
1319
Prabir Pradhancef936d2021-07-21 16:17:52 +00001320bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001321 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 return false;
1323 }
1324
1325 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001326 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001327 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001328 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1329 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001330 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331 return true;
1332}
1333
Prabir Pradhancef936d2021-07-21 16:17:52 +00001334void InputDispatcher::postCommandLocked(Command&& command) {
1335 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001336}
1337
1338void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001339 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001340 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001341 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001342 releaseInboundEventLocked(entry);
1343 }
1344 traceInboundQueueLengthLocked();
1345}
1346
1347void InputDispatcher::releasePendingEventLocked() {
1348 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001350 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001351 }
1352}
1353
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001354void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001356 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001357 if (DEBUG_DISPATCH_CYCLE) {
1358 ALOGD("Injected inbound event was dropped.");
1359 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001360 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001361 }
1362 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001363 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364 }
1365 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366}
1367
1368void InputDispatcher::resetKeyRepeatLocked() {
1369 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001370 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001371 }
1372}
1373
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001374std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1375 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376
Michael Wright2e732952014-09-24 13:26:59 -07001377 uint32_t policyFlags = entry->policyFlags &
1378 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001379
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001380 std::shared_ptr<KeyEntry> newEntry =
1381 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1382 entry->source, entry->displayId, policyFlags, entry->action,
1383 entry->flags, entry->keyCode, entry->scanCode,
1384 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001385
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001386 newEntry->syntheticRepeat = true;
1387 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001389 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390}
1391
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001392bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001393 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001394 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1395 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1396 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397
1398 // Reset key repeating in case a keyboard device was added or removed or something.
1399 resetKeyRepeatLocked();
1400
1401 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001402 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1403 scoped_unlock unlock(mLock);
1404 mPolicy->notifyConfigurationChanged(eventTime);
1405 };
1406 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001407 return true;
1408}
1409
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001410bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1411 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001412 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1413 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1414 entry.deviceId);
1415 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001416
liushenxiang42232912021-05-21 20:24:09 +08001417 // Reset key repeating in case a keyboard device was disabled or enabled.
1418 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1419 resetKeyRepeatLocked();
1420 }
1421
Michael Wrightfb04fd52022-11-24 22:31:11 +00001422 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001423 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424 synthesizeCancelationEventsForAllConnectionsLocked(options);
1425 return true;
1426}
1427
Vishnu Nairad321cd2020-08-20 16:40:21 -07001428void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001429 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001430 if (mPendingEvent != nullptr) {
1431 // Move the pending event to the front of the queue. This will give the chance
1432 // for the pending event to get dispatched to the newly focused window
1433 mInboundQueue.push_front(mPendingEvent);
1434 mPendingEvent = nullptr;
1435 }
1436
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001437 std::unique_ptr<FocusEntry> focusEntry =
1438 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1439 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001440
1441 // This event should go to the front of the queue, but behind all other focus events
1442 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001443 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001444 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001445 [](const std::shared_ptr<EventEntry>& event) {
1446 return event->type == EventEntry::Type::FOCUS;
1447 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001448
1449 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001450 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001451}
1452
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001453void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001454 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001455 if (channel == nullptr) {
1456 return; // Window has gone away
1457 }
1458 InputTarget target;
1459 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001460 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001461 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001462 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1463 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001464 std::string reason = std::string("reason=").append(entry->reason);
1465 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001466 dispatchEventLocked(currentTime, entry, {target});
1467}
1468
Prabir Pradhan99987712020-11-10 18:43:05 -08001469void InputDispatcher::dispatchPointerCaptureChangedLocked(
1470 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1471 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001472 dropReason = DropReason::NOT_DROPPED;
1473
Prabir Pradhan99987712020-11-10 18:43:05 -08001474 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001475 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001476
1477 if (entry->pointerCaptureRequest.enable) {
1478 // Enable Pointer Capture.
1479 if (haveWindowWithPointerCapture &&
1480 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001481 // This can happen if pointer capture is disabled and re-enabled before we notify the
1482 // app of the state change, so there is no need to notify the app.
1483 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1484 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001485 }
1486 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001487 // This can happen if a window requests capture and immediately releases capture.
1488 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001489 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001490 return;
1491 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001492 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1493 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1494 return;
1495 }
1496
Vishnu Nairc519ff72021-01-21 08:23:08 -08001497 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001498 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1499 mWindowTokenWithPointerCapture = token;
1500 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001501 // Disable Pointer Capture.
1502 // We do not check if the sequence number matches for requests to disable Pointer Capture
1503 // for two reasons:
1504 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1505 // to disable capture with the same sequence number: one generated by
1506 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1507 // Capture being disabled in InputReader.
1508 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1509 // actual Pointer Capture state that affects events being generated by input devices is
1510 // in InputReader.
1511 if (!haveWindowWithPointerCapture) {
1512 // Pointer capture was already forcefully disabled because of focus change.
1513 dropReason = DropReason::NOT_DROPPED;
1514 return;
1515 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001516 token = mWindowTokenWithPointerCapture;
1517 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001518 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001519 setPointerCaptureLocked(false);
1520 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001521 }
1522
1523 auto channel = getInputChannelLocked(token);
1524 if (channel == nullptr) {
1525 // Window has gone away, clean up Pointer Capture state.
1526 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001527 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001528 setPointerCaptureLocked(false);
1529 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001530 return;
1531 }
1532 InputTarget target;
1533 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001534 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001535 entry->dispatchInProgress = true;
1536 dispatchEventLocked(currentTime, entry, {target});
1537
1538 dropReason = DropReason::NOT_DROPPED;
1539}
1540
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001541void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1542 const std::shared_ptr<TouchModeEntry>& entry) {
1543 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001544 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001545 if (windowHandles.empty()) {
1546 return;
1547 }
1548 const std::vector<InputTarget> inputTargets =
1549 getInputTargetsFromWindowHandlesLocked(windowHandles);
1550 if (inputTargets.empty()) {
1551 return;
1552 }
1553 entry->dispatchInProgress = true;
1554 dispatchEventLocked(currentTime, entry, inputTargets);
1555}
1556
1557std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1558 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1559 std::vector<InputTarget> inputTargets;
1560 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001561 const sp<IBinder>& token = handle->getToken();
1562 if (token == nullptr) {
1563 continue;
1564 }
1565 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1566 if (channel == nullptr) {
1567 continue; // Window has gone away
1568 }
1569 InputTarget target;
1570 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001571 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001572 inputTargets.push_back(target);
1573 }
1574 return inputTargets;
1575}
1576
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001577bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001578 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001580 if (!entry->dispatchInProgress) {
1581 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1582 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1583 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1584 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001585 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586 // We have seen two identical key downs in a row which indicates that the device
1587 // driver is automatically generating key repeats itself. We take note of the
1588 // repeat here, but we disable our own next key repeat timer since it is clear that
1589 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001590 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1591 // Make sure we don't get key down from a different device. If a different
1592 // device Id has same key pressed down, the new device Id will replace the
1593 // current one to hold the key repeat with repeat count reset.
1594 // In the future when got a KEY_UP on the device id, drop it and do not
1595 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001596 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1597 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001598 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599 } else {
1600 // Not a repeat. Save key down state in case we do see a repeat later.
1601 resetKeyRepeatLocked();
1602 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1603 }
1604 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001605 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1606 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001607 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001608 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001609 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1610 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001611 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001612 resetKeyRepeatLocked();
1613 }
1614
1615 if (entry->repeatCount == 1) {
1616 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1617 } else {
1618 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1619 }
1620
1621 entry->dispatchInProgress = true;
1622
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001623 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001624 }
1625
1626 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001627 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628 if (currentTime < entry->interceptKeyWakeupTime) {
1629 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1630 *nextWakeupTime = entry->interceptKeyWakeupTime;
1631 }
1632 return false; // wait until next wakeup
1633 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001634 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635 entry->interceptKeyWakeupTime = 0;
1636 }
1637
1638 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001639 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001641 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001642 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001643
1644 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1645 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1646 };
1647 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001648 return false; // wait for the command to run
1649 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001650 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001651 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001652 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001653 if (*dropReason == DropReason::NOT_DROPPED) {
1654 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 }
1656 }
1657
1658 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001659 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001660 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001661 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1662 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001663 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 return true;
1665 }
1666
1667 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001668 InputEventInjectionResult injectionResult;
1669 sp<WindowInfoHandle> focusedWindow =
1670 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1671 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001672 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 return false;
1674 }
1675
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001676 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001677 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 return true;
1679 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001680 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1681
1682 std::vector<InputTarget> inputTargets;
1683 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001684 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001685 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001686
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001687 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001688 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689
1690 // Dispatch the key.
1691 dispatchEventLocked(currentTime, entry, inputTargets);
1692 return true;
1693}
1694
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001695void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001696 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1697 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1698 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1699 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1700 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1701 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1702 entry.metaState, entry.repeatCount, entry.downTime);
1703 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001704}
1705
Prabir Pradhancef936d2021-07-21 16:17:52 +00001706void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1707 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001708 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001709 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1710 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1711 "source=0x%x, sensorType=%s",
1712 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001713 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001714 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001715 auto command = [this, entry]() REQUIRES(mLock) {
1716 scoped_unlock unlock(mLock);
1717
1718 if (entry->accuracyChanged) {
1719 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1720 }
1721 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1722 entry->hwTimestamp, entry->values);
1723 };
1724 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001725}
1726
1727bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001728 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1729 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001730 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001731 }
Chris Yef59a2f42020-10-16 12:55:26 -07001732 { // acquire lock
1733 std::scoped_lock _l(mLock);
1734
1735 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1736 std::shared_ptr<EventEntry> entry = *it;
1737 if (entry->type == EventEntry::Type::SENSOR) {
1738 it = mInboundQueue.erase(it);
1739 releaseInboundEventLocked(entry);
1740 }
1741 }
1742 }
1743 return true;
1744}
1745
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001746bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001747 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001748 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001750 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 entry->dispatchInProgress = true;
1752
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001753 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754 }
1755
1756 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001757 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001758 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001759 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1760 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761 return true;
1762 }
1763
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001764 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765
1766 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001767 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001768
1769 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001770 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001771 if (isPointerEvent) {
1772 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001773
1774 if (mDragState &&
1775 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1776 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1777 pilferPointersLocked(mDragState->dragWindow->getToken());
1778 }
1779
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001780 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001781 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001782 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001783 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1784 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785 } else {
1786 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001787 sp<WindowInfoHandle> focusedWindow =
1788 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1789 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1790 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1791 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001792 InputTarget::Flags::FOREGROUND |
1793 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001794 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001795 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001797 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798 return false;
1799 }
1800
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001801 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001802 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001803 return true;
1804 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001805 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001806 CancelationOptions::Mode mode(
1807 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1808 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001809 CancelationOptions options(mode, "input event injection failed");
1810 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811 return true;
1812 }
1813
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001814 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001815 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816
1817 // Dispatch the motion.
1818 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001819 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001820 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 synthesizeCancelationEventsForAllConnectionsLocked(options);
1822 }
1823 dispatchEventLocked(currentTime, entry, inputTargets);
1824 return true;
1825}
1826
chaviw98318de2021-05-19 16:45:23 -05001827void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001828 bool isExiting, const int32_t rawX,
1829 const int32_t rawY) {
1830 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001831 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001832 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1833 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001834
1835 enqueueInboundEventLocked(std::move(dragEntry));
1836}
1837
1838void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1839 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1840 if (channel == nullptr) {
1841 return; // Window has gone away
1842 }
1843 InputTarget target;
1844 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001845 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001846 entry->dispatchInProgress = true;
1847 dispatchEventLocked(currentTime, entry, {target});
1848}
1849
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001850void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001851 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001852 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001853 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001854 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001855 "metaState=0x%x, buttonState=0x%x,"
1856 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001857 prefix, entry.eventTime, entry.deviceId,
1858 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1859 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1860 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1861 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001862
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001863 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07001864 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001865 "x=%f, y=%f, pressure=%f, size=%f, "
1866 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1867 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07001868 i, entry.pointerProperties[i].id,
1869 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001870 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1871 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1872 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1873 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1874 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1875 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1876 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1877 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1878 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1879 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001880 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881}
1882
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001883void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1884 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001885 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001886 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001887 if (DEBUG_DISPATCH_CYCLE) {
1888 ALOGD("dispatchEventToCurrentInputTargets");
1889 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001891 updateInteractionTokensLocked(*eventEntry, inputTargets);
1892
Michael Wrightd02c5b62014-02-10 15:10:22 -08001893 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1894
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001895 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001896
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001897 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001898 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001899 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001900 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001901 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001902 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001903 if (DEBUG_FOCUS) {
1904 ALOGD("Dropping event delivery to target with channel '%s' because it "
1905 "is no longer registered with the input dispatcher.",
1906 inputTarget.inputChannel->getName().c_str());
1907 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908 }
1909 }
1910}
1911
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001912void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001913 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1914 // If the policy decides to close the app, we will get a channel removal event via
1915 // unregisterInputChannel, and will clean up the connection that way. We are already not
1916 // sending new pointers to the connection when it blocked, but focused events will continue to
1917 // pile up.
1918 ALOGW("Canceling events for %s because it is unresponsive",
1919 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001920 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001921 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001922 "application not responding");
1923 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001924 }
1925}
1926
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001927void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001928 if (DEBUG_FOCUS) {
1929 ALOGD("Resetting ANR timeouts.");
1930 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931
1932 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001933 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001934 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935}
1936
Tiger Huang721e26f2018-07-24 22:26:19 +08001937/**
1938 * Get the display id that the given event should go to. If this event specifies a valid display id,
1939 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1940 * Focused display is the display that the user most recently interacted with.
1941 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001942int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001943 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001944 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001945 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001946 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1947 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001948 break;
1949 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001950 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001951 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1952 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001953 break;
1954 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001955 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001956 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001957 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001958 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001959 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001960 case EventEntry::Type::SENSOR:
1961 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001962 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001963 return ADISPLAY_ID_NONE;
1964 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001965 }
1966 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1967}
1968
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001969bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1970 const char* focusedWindowName) {
1971 if (mAnrTracker.empty()) {
1972 // already processed all events that we waited for
1973 mKeyIsWaitingForEventsTimeout = std::nullopt;
1974 return false;
1975 }
1976
1977 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1978 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001979 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001980 mKeyIsWaitingForEventsTimeout = currentTime +
1981 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1982 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001983 return true;
1984 }
1985
1986 // We still have pending events, and already started the timer
1987 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1988 return true; // Still waiting
1989 }
1990
1991 // Waited too long, and some connection still hasn't processed all motions
1992 // Just send the key to the focused window
1993 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1994 focusedWindowName);
1995 mKeyIsWaitingForEventsTimeout = std::nullopt;
1996 return false;
1997}
1998
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001999sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2000 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2001 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002002 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002003 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004
Tiger Huang721e26f2018-07-24 22:26:19 +08002005 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002006 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002007 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002008 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2009
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010 // If there is no currently focused window and no focused application
2011 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002012 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2013 ALOGI("Dropping %s event because there is no focused window or focused application in "
2014 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002015 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002016 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017 }
2018
Vishnu Nair062a8672021-09-03 16:07:44 -07002019 // Drop key events if requested by input feature
2020 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002021 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002022 }
2023
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002024 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2025 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2026 // start interacting with another application via touch (app switch). This code can be removed
2027 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2028 // an app is expected to have a focused window.
2029 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2030 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2031 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002032 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2033 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2034 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002035 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002036 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002037 ALOGW("Waiting because no window has focus but %s may eventually add a "
2038 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002039 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002040 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002041 outInjectionResult = InputEventInjectionResult::PENDING;
2042 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002043 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2044 // Already raised ANR. Drop the event
2045 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002046 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002047 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002048 } else {
2049 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002050 outInjectionResult = InputEventInjectionResult::PENDING;
2051 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002052 }
2053 }
2054
2055 // we have a valid, non-null focused window
2056 resetNoFocusedWindowTimeoutLocked();
2057
Prabir Pradhan5735a322022-04-11 17:23:34 +00002058 // Verify targeted injection.
2059 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2060 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002061 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2062 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063 }
2064
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002065 if (focusedWindowHandle->getInfo()->inputConfig.test(
2066 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002067 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002068 outInjectionResult = InputEventInjectionResult::PENDING;
2069 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002070 }
2071
2072 // If the event is a key event, then we must wait for all previous events to
2073 // complete before delivering it because previous events may have the
2074 // side-effect of transferring focus to a different window and we want to
2075 // ensure that the following keys are sent to the new window.
2076 //
2077 // Suppose the user touches a button in a window then immediately presses "A".
2078 // If the button causes a pop-up window to appear then we want to ensure that
2079 // the "A" key is delivered to the new pop-up window. This is because users
2080 // often anticipate pending UI changes when typing on a keyboard.
2081 // To obtain this behavior, we must serialize key events with respect to all
2082 // prior input events.
2083 if (entry.type == EventEntry::Type::KEY) {
2084 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2085 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002086 outInjectionResult = InputEventInjectionResult::PENDING;
2087 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002088 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089 }
2090
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002091 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2092 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093}
2094
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002095/**
2096 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2097 * that are currently unresponsive.
2098 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002099std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2100 const std::vector<Monitor>& monitors) const {
2101 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002102 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002103 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002104 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002105 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002106 if (connection == nullptr) {
2107 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002108 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002109 return false;
2110 }
2111 if (!connection->responsive) {
2112 ALOGW("Unresponsive monitor %s will not get the new gesture",
2113 connection->inputChannel->getName().c_str());
2114 return false;
2115 }
2116 return true;
2117 });
2118 return responsiveMonitors;
2119}
2120
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002121/**
2122 * In general, touch should be always split between windows. Some exceptions:
2123 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2124 * from the same device, *and* the window that's receiving the current pointer does not support
2125 * split touch.
2126 * 2. Don't split mouse events
2127 */
2128bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2129 const MotionEntry& entry) const {
2130 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2131 // We should never split mouse events
2132 return false;
2133 }
2134 for (const TouchedWindow& touchedWindow : touchState.windows) {
2135 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2136 // Spy windows should not affect whether or not touch is split.
2137 continue;
2138 }
2139 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2140 continue;
2141 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002142 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2143 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2144 // Wallpaper window should not affect whether or not touch is split
2145 continue;
2146 }
2147
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002148 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2149 // being sent there. For now, use deviceId from touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002150 if (entry.deviceId == touchState.deviceId && touchedWindow.pointerIds.any()) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002151 return false;
2152 }
2153 }
2154 return true;
2155}
2156
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002157std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002158 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2159 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002160 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002162 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163 // For security reasons, we defer updating the touch state until we are sure that
2164 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002165 const int32_t displayId = entry.displayId;
2166 const int32_t action = entry.action;
2167 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002168
2169 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002170 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002172 // Copy current touch state into tempTouchState.
2173 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2174 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002175 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002176 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002177 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2178 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002179 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002180 }
2181
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002182 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002183 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002184 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002185
2186 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2187 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2188 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002189 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2190 // touchable windows.
2191 const bool wasDown = oldState != nullptr && oldState->isDown();
2192 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2193 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
2194 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002195 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002196
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002197 // If pointers are already down, let's finish the current gesture and ignore the new events
2198 // from another device. However, if the new event is a down event, let's cancel the current
2199 // touch and let the new one take over.
2200 if (switchedDevice && wasDown && !isDown) {
2201 LOG(INFO) << "Dropping event because a pointer for device " << oldState->deviceId
2202 << " is already down in display " << displayId << ": " << entry.getDescription();
2203 // TODO(b/211379801): test multiple simultaneous input streams.
2204 outInjectionResult = InputEventInjectionResult::FAILED;
2205 return {}; // wrong device
2206 }
2207
Michael Wrightd02c5b62014-02-10 15:10:22 -08002208 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002209 // If a new gesture is starting, clear the touch state completely.
2210 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002211 tempTouchState.deviceId = entry.deviceId;
2212 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002214 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002215 ALOGI("Dropping move event because a pointer for a different device is already active "
2216 "in display %" PRId32,
2217 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002218 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002219 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002220 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221 }
2222
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002223 if (isHoverAction) {
2224 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2225 // all of the existing hovering pointers and recompute.
2226 tempTouchState.clearHoveringPointers();
2227 }
2228
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2230 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002231 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002232 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002233 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2234 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002235 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002236 auto [newTouchedWindowHandle, outsideTargets] =
2237 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002238
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002239 if (isDown) {
2240 targets += outsideTargets;
2241 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002243 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002244 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002246 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002247 }
2248
Prabir Pradhan5735a322022-04-11 17:23:34 +00002249 // Verify targeted injection.
2250 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2251 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002252 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002253 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002254 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002255 }
2256
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002257 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002258 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002259 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2260 // New window supports splitting, but we should never split mouse events.
2261 isSplit = !isFromMouse;
2262 } else if (isSplit) {
2263 // New window does not support splitting but we have already split events.
2264 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002265 newTouchedWindowHandle = nullptr;
2266 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002267 } else {
2268 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002269 // be delivered to a new window which supports split touch. Pointers from a mouse device
2270 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002271 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002272 }
2273
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002274 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002275 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002276 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002277 // Process the foreground window first so that it is the first to receive the event.
2278 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002279 }
2280
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002281 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002282 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2283 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002284 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002285 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002286 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002287 }
2288
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002289 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002290 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002291 continue;
2292 }
2293
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002294 if (isHoverAction) {
2295 const int32_t pointerId = entry.pointerProperties[0].id;
2296 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2297 // Pointer left. Remove it
2298 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2299 } else {
2300 // The "windowHandle" is the target of this hovering pointer.
2301 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId,
2302 pointerId);
2303 }
2304 }
2305
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002306 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002307 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002308
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002309 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2310 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002311 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002312 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002313
2314 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002315 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002316 }
2317 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002318 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002319 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002320 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002321 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002322
2323 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002324 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002325 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002326 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002327 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002328
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002329 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2330 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2331
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002332 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2333 // still add a window to the touch state. We should avoid doing that, but some of the
2334 // later checks ("at least one foreground window") rely on this in order to dispatch
2335 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002336 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002337 isDownOrPointerDown
2338 ? std::make_optional(entry.eventTime)
2339 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002340
2341 // If this is the pointer going down and the touched window has a wallpaper
2342 // then also add the touched wallpaper windows so they are locked in for the duration
2343 // of the touch gesture.
2344 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2345 // engine only supports touch events. We would need to add a mechanism similar
2346 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002347 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002348 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2349 windowHandle->getInfo()->inputConfig.test(
2350 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2351 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2352 if (wallpaper != nullptr) {
2353 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2354 InputTarget::Flags::WINDOW_IS_OBSCURED |
2355 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2356 InputTarget::Flags::DISPATCH_AS_IS;
2357 if (isSplit) {
2358 wallpaperFlags |= InputTarget::Flags::SPLIT;
2359 }
2360 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2361 entry.eventTime);
2362 }
2363 }
2364 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002365 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002366
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002367 // If a window is already pilfering some pointers, give it this new pointer as well and
2368 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2369 // which is a specific behaviour that we want.
2370 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2371 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002372 if (touchedWindow.pointerIds.test(pointerId) &&
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002373 touchedWindow.pilferedPointerIds.count() > 0) {
2374 // This window is already pilfering some pointers, and this new pointer is also
2375 // going to it. Therefore, take over this pointer and don't give it to anyone
2376 // else.
2377 touchedWindow.pilferedPointerIds.set(pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002378 }
2379 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002380
2381 // Restrict all pilfered pointers to the pilfering windows.
2382 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002383 } else {
2384 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2385
2386 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002387 if (!tempTouchState.isDown()) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002388 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2389 "dropped the pointer down event in display "
2390 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002391 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002392 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393 }
2394
arthurhung6d4bed92021-03-17 11:59:33 +08002395 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002396
Michael Wrightd02c5b62014-02-10 15:10:22 -08002397 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002398 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002399 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002400 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002401 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002402 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002403 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002404 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
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
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002420 if (!haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
2421 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2422 oldTouchedWindowHandle->getName().c_str(),
2423 newTouchedWindowHandle->getName().c_str(), displayId);
2424
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002426 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002427 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002428 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002429
2430 const TouchedWindow& touchedWindow =
2431 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2432 addWindowTargetLocked(oldTouchedWindowHandle,
2433 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
2434 touchedWindow.firstDownTimeInTarget, targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002435
2436 // Make a slippery entrance into the new window.
2437 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002438 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002439 }
2440
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002441 ftl::Flags<InputTarget::Flags> targetFlags =
2442 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002443 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002444 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002445 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002446 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002447 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448 }
2449 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002450 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002451 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002452 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002453 }
2454
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002455 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2456 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002457
2458 // Check if the wallpaper window should deliver the corresponding event.
2459 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002460 tempTouchState, pointerId, targets);
2461 tempTouchState.removeTouchedPointerFromWindow(pointerId, oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462 }
2463 }
Arthur Hung96483742022-11-15 03:30:48 +00002464
2465 // Update the pointerIds for non-splittable when it received pointer down.
2466 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2467 // If no split, we suppose all touched windows should receive pointer down.
2468 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2469 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2470 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2471 // Ignore drag window for it should just track one pointer.
2472 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2473 continue;
2474 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002475 touchedWindow.pointerIds.set(entry.pointerProperties[pointerIndex].id);
Arthur Hung96483742022-11-15 03:30:48 +00002476 }
2477 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002478 }
2479
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002480 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002481 {
2482 std::vector<TouchedWindow> hoveringWindows =
2483 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2484 for (const TouchedWindow& touchedWindow : hoveringWindows) {
2485 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2486 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2487 targets);
2488 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489 }
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002490 // Ensure that we have at least one foreground window or at least one window that cannot be a
2491 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2492 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2493 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002494 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2495 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002496 return !canReceiveForegroundTouches(
2497 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002498 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002499 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002500 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2501 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002502 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002503 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 }
2505
Prabir Pradhan5735a322022-04-11 17:23:34 +00002506 // Ensure that all touched windows are valid for injection.
2507 if (entry.injectionState != nullptr) {
2508 std::string errs;
2509 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002510 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002511 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2512 // dispatched to any uid, since the coords will be zeroed out later.
2513 continue;
2514 }
2515 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2516 if (err) errs += "\n - " + *err;
2517 }
2518 if (!errs.empty()) {
2519 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2520 "%d:%s",
2521 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002522 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002523 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002524 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002525 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002526
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002527 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2528 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002529 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002530 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002531 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002532 if (foregroundWindowHandle) {
2533 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002534 for (InputTarget& target : targets) {
2535 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2536 sp<WindowInfoHandle> targetWindow =
2537 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2538 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2539 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002540 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541 }
2542 }
2543 }
2544 }
2545
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002546 // Success! Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002547 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002548 if (touchedWindow.pointerIds.none() && !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002549 // Windows with hovering pointers are getting persisted inside TouchState.
2550 // Do not send this event to those windows.
2551 continue;
2552 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002553 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2554 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2555 targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002556 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002557
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002558 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002559 // Drop the outside or hover touch windows since we will not care about them
2560 // in the next iteration.
2561 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002562
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002564 if (switchedDevice) {
2565 if (DEBUG_FOCUS) {
2566 ALOGD("Conflicting pointer actions: Switched to a different device.");
2567 }
2568 *outConflictingPointerActions = true;
2569 }
2570
2571 if (isHoverAction) {
2572 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002573 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002574 ALOGD_IF(DEBUG_FOCUS,
2575 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002576 *outConflictingPointerActions = true;
2577 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002578 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2579 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2580 tempTouchState.deviceId = entry.deviceId;
2581 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002582 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002583 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2584 // Pointer went up.
2585 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002586 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002587 // All pointers up or canceled.
2588 tempTouchState.reset();
2589 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2590 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002591 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2592 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002593 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002594 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002595 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2596 // One pointer went up.
2597 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2598 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002600 for (size_t i = 0; i < tempTouchState.windows.size();) {
2601 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002602 touchedWindow.pointerIds.reset(pointerId);
2603 if (touchedWindow.pointerIds.none()) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002604 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2605 continue;
2606 }
2607 i += 1;
2608 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609 }
2610
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002611 // Save changes unless the action was scroll in which case the temporary touch
2612 // state was only valid for this one action.
2613 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002614 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002615 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002616 mTouchStatesByDisplay[displayId] = tempTouchState;
2617 } else {
2618 mTouchStatesByDisplay.erase(displayId);
2619 }
2620 }
2621
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002622 if (tempTouchState.windows.empty()) {
2623 mTouchStatesByDisplay.erase(displayId);
2624 }
2625
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002626 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002627}
2628
arthurhung6d4bed92021-03-17 11:59:33 +08002629void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002630 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2631 // have an explicit reason to support it.
2632 constexpr bool isStylus = false;
2633
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002634 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002635 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002636 if (dropWindow) {
2637 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002638 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002639 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002640 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002641 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002642 }
2643 mDragState.reset();
2644}
2645
2646void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002647 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002648 return;
2649 }
2650
arthurhung6d4bed92021-03-17 11:59:33 +08002651 if (!mDragState->isStartDrag) {
2652 mDragState->isStartDrag = true;
2653 mDragState->isStylusButtonDownAtStart =
2654 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2655 }
2656
Arthur Hung54745652022-04-20 07:17:41 +00002657 // Find the pointer index by id.
2658 int32_t pointerIndex = 0;
2659 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2660 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2661 if (pointerProperties.id == mDragState->pointerId) {
2662 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002663 }
Arthur Hung54745652022-04-20 07:17:41 +00002664 }
arthurhung6d4bed92021-03-17 11:59:33 +08002665
Arthur Hung54745652022-04-20 07:17:41 +00002666 if (uint32_t(pointerIndex) == entry.pointerCount) {
2667 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002668 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002669 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002670 return;
2671 }
2672
2673 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2674 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2675 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2676
2677 switch (maskedAction) {
2678 case AMOTION_EVENT_ACTION_MOVE: {
2679 // Handle the special case : stylus button no longer pressed.
2680 bool isStylusButtonDown =
2681 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2682 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2683 finishDragAndDrop(entry.displayId, x, y);
2684 return;
2685 }
2686
2687 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2688 // until we have an explicit reason to support it.
2689 constexpr bool isStylus = false;
2690
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002691 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002692 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002693 // enqueue drag exit if needed.
2694 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2695 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2696 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002697 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002698 y);
2699 }
2700 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2701 }
2702 // enqueue drag location if needed.
2703 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002704 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002705 }
2706 break;
2707 }
2708
2709 case AMOTION_EVENT_ACTION_POINTER_UP:
2710 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2711 break;
2712 }
2713 // The drag pointer is up.
2714 [[fallthrough]];
2715 case AMOTION_EVENT_ACTION_UP:
2716 finishDragAndDrop(entry.displayId, x, y);
2717 break;
2718 case AMOTION_EVENT_ACTION_CANCEL: {
2719 ALOGD("Receiving cancel when drag and drop.");
2720 sendDropWindowCommandLocked(nullptr, 0, 0);
2721 mDragState.reset();
2722 break;
2723 }
arthurhungb89ccb02020-12-30 16:19:01 +08002724 }
2725}
2726
chaviw98318de2021-05-19 16:45:23 -05002727void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002728 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002729 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002730 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002731 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002732 std::vector<InputTarget>::iterator it =
2733 std::find_if(inputTargets.begin(), inputTargets.end(),
2734 [&windowHandle](const InputTarget& inputTarget) {
2735 return inputTarget.inputChannel->getConnectionToken() ==
2736 windowHandle->getToken();
2737 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002738
chaviw98318de2021-05-19 16:45:23 -05002739 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002740
2741 if (it == inputTargets.end()) {
2742 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002743 std::shared_ptr<InputChannel> inputChannel =
2744 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002745 if (inputChannel == nullptr) {
2746 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2747 return;
2748 }
2749 inputTarget.inputChannel = inputChannel;
2750 inputTarget.flags = targetFlags;
2751 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002752 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002753 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2754 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002755 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002756 } else {
Siarhei Vishniakoua06bb552023-02-07 09:38:56 -08002757 // DisplayInfo not found for this window on display windowInfo->displayId.
2758 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002759 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002760 inputTargets.push_back(inputTarget);
2761 it = inputTargets.end() - 1;
2762 }
2763
2764 ALOG_ASSERT(it->flags == targetFlags);
2765 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2766
chaviw1ff3d1e2020-07-01 15:53:47 -07002767 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768}
2769
Michael Wright3dd60e22019-03-27 22:06:44 +00002770void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002771 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002772 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2773 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002774
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002775 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2776 InputTarget target;
2777 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002778 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002779 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2780 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002781 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2782 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002783 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002784 target.setDefaultPointerTransform(target.displayTransform);
2785 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002786 }
2787}
2788
Robert Carrc9bf1d32020-04-13 17:21:08 -07002789/**
2790 * Indicate whether one window handle should be considered as obscuring
2791 * another window handle. We only check a few preconditions. Actually
2792 * checking the bounds is left to the caller.
2793 */
chaviw98318de2021-05-19 16:45:23 -05002794static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2795 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002796 // Compare by token so cloned layers aren't counted
2797 if (haveSameToken(windowHandle, otherHandle)) {
2798 return false;
2799 }
2800 auto info = windowHandle->getInfo();
2801 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002802 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002803 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002804 } else if (otherInfo->alpha == 0 &&
2805 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002806 // Those act as if they were invisible, so we don't need to flag them.
2807 // We do want to potentially flag touchable windows even if they have 0
2808 // opacity, since they can consume touches and alter the effects of the
2809 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002810 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002811 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2812 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002813 } else if (info->ownerUid == otherInfo->ownerUid) {
2814 // If ownerUid is the same we don't generate occlusion events as there
2815 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002816 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002817 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002818 return false;
2819 } else if (otherInfo->displayId != info->displayId) {
2820 return false;
2821 }
2822 return true;
2823}
2824
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002825/**
2826 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2827 * untrusted, one should check:
2828 *
2829 * 1. If result.hasBlockingOcclusion is true.
2830 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2831 * BLOCK_UNTRUSTED.
2832 *
2833 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2834 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2835 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2836 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2837 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2838 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2839 *
2840 * If neither of those is true, then it means the touch can be allowed.
2841 */
2842InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002843 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2844 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002845 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002846 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002847 TouchOcclusionInfo info;
2848 info.hasBlockingOcclusion = false;
2849 info.obscuringOpacity = 0;
2850 info.obscuringUid = -1;
2851 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002852 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002853 if (windowHandle == otherHandle) {
2854 break; // All future windows are below us. Exit early.
2855 }
chaviw98318de2021-05-19 16:45:23 -05002856 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002857 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2858 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002859 if (DEBUG_TOUCH_OCCLUSION) {
2860 info.debugInfo.push_back(
2861 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2862 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002863 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2864 // we perform the checks below to see if the touch can be propagated or not based on the
2865 // window's touch occlusion mode
2866 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2867 info.hasBlockingOcclusion = true;
2868 info.obscuringUid = otherInfo->ownerUid;
2869 info.obscuringPackage = otherInfo->packageName;
2870 break;
2871 }
2872 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2873 uint32_t uid = otherInfo->ownerUid;
2874 float opacity =
2875 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2876 // Given windows A and B:
2877 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2878 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2879 opacityByUid[uid] = opacity;
2880 if (opacity > info.obscuringOpacity) {
2881 info.obscuringOpacity = opacity;
2882 info.obscuringUid = uid;
2883 info.obscuringPackage = otherInfo->packageName;
2884 }
2885 }
2886 }
2887 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002888 if (DEBUG_TOUCH_OCCLUSION) {
2889 info.debugInfo.push_back(
2890 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2891 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002892 return info;
2893}
2894
chaviw98318de2021-05-19 16:45:23 -05002895std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002896 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002897 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2898 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2899 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2900 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002901 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2902 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2903 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2904 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2905 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002906 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07002907 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002908}
2909
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002910bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2911 if (occlusionInfo.hasBlockingOcclusion) {
2912 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2913 occlusionInfo.obscuringUid);
2914 return false;
2915 }
2916 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2917 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2918 "%.2f, maximum allowed = %.2f)",
2919 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2920 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2921 return false;
2922 }
2923 return true;
2924}
2925
chaviw98318de2021-05-19 16:45:23 -05002926bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002927 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002929 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2930 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002931 if (windowHandle == otherHandle) {
2932 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933 }
chaviw98318de2021-05-19 16:45:23 -05002934 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002935 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002936 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002937 return true;
2938 }
2939 }
2940 return false;
2941}
2942
chaviw98318de2021-05-19 16:45:23 -05002943bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002944 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002945 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2946 const WindowInfo* windowInfo = windowHandle->getInfo();
2947 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002948 if (windowHandle == otherHandle) {
2949 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002950 }
chaviw98318de2021-05-19 16:45:23 -05002951 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002952 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002953 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002954 return true;
2955 }
2956 }
2957 return false;
2958}
2959
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002960std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002961 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002962 if (applicationHandle != nullptr) {
2963 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002964 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002965 } else {
2966 return applicationHandle->getName();
2967 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002968 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002969 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002970 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002971 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972 }
2973}
2974
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002975void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002976 if (!isUserActivityEvent(eventEntry)) {
2977 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002978 return;
2979 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002980 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002981 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002982 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002983 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002984 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002985 if (DEBUG_DISPATCH_CYCLE) {
2986 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2987 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002988 return;
2989 }
2990 }
2991
2992 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002993 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002994 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002995 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2996 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002997 return;
2998 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002999
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003000 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003001 eventType = USER_ACTIVITY_EVENT_TOUCH;
3002 }
3003 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003005 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003006 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3007 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003008 return;
3009 }
3010 eventType = USER_ACTIVITY_EVENT_BUTTON;
3011 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003012 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003013 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003014 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003015 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003016 break;
3017 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003018 }
3019
Prabir Pradhancef936d2021-07-21 16:17:52 +00003020 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3021 REQUIRES(mLock) {
3022 scoped_unlock unlock(mLock);
3023 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
3024 };
3025 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003026}
3027
3028void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003029 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003030 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003031 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003032 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003033 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003034 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003035 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003036 ATRACE_NAME(message.c_str());
3037 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003038 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003039 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003040 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003041 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003042 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003043 inputTarget.getPointerInfoString().c_str());
3044 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003045
3046 // Skip this event if the connection status is not normal.
3047 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003048 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003049 if (DEBUG_DISPATCH_CYCLE) {
3050 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003051 connection->getInputChannelName().c_str(),
3052 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003053 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054 return;
3055 }
3056
3057 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003058 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003059 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003060 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003061 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003063 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003064 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003065 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3066 logDispatchStateLocked();
3067 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3068 "target on connection "
3069 << connection->getInputChannelName() << " for "
3070 << originalMotionEntry.getDescription();
3071 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003072 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003073 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3074 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003075 if (!splitMotionEntry) {
3076 return; // split event was dropped
3077 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003078 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3079 std::string reason = std::string("reason=pointer cancel on split window");
3080 android_log_event_list(LOGTAG_INPUT_CANCEL)
3081 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3082 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003083 if (DEBUG_FOCUS) {
3084 ALOGD("channel '%s' ~ Split motion event.",
3085 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003086 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003087 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003088 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3089 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003090 return;
3091 }
3092 }
3093
3094 // Not splitting. Enqueue dispatch entries for the event as is.
3095 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3096}
3097
3098void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003099 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003100 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003101 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003102 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003103 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003104 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003105 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003106 ATRACE_NAME(message.c_str());
3107 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003108 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3109 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003110
hongzuo liu95785e22022-09-06 02:51:35 +00003111 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003112
3113 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003114 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003115 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003116 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003117 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003118 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003119 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003120 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003121 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003122 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003123 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003124 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003125 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003126
3127 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003128 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003129 startDispatchCycleLocked(currentTime, connection);
3130 }
3131}
3132
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003133void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003134 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003135 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003136 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003137 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003138 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3139 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003140 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003141 ATRACE_NAME(message.c_str());
3142 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003143 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3144 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003145 return;
3146 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003147
3148 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3149 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150
3151 // This is a new event.
3152 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003153 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003154 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003155
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003156 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3157 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003158 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003160 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003161 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003162 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003163 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003164 dispatchEntry->resolvedAction = keyEntry.action;
3165 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003167 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3168 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003169 if (DEBUG_DISPATCH_CYCLE) {
3170 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3171 "event",
3172 connection->getInputChannelName().c_str());
3173 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003174 return; // skip the inconsistent event
3175 }
3176 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003179 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003180 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003181 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3182 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3183 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3184 static_cast<int32_t>(IdGenerator::Source::OTHER);
3185 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003186 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003187 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003188 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003189 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003190 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003191 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003192 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003193 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003194 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003195 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3196 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003197 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003198 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003199 }
3200 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003201 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3202 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003203 if (DEBUG_DISPATCH_CYCLE) {
3204 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3205 "enter event",
3206 connection->getInputChannelName().c_str());
3207 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003208 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3209 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003210 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3211 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003212
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003213 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003214 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3215 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3216 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003217 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003218 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3219 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003220 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003221 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3222 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003223
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003224 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3225 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003226 if (DEBUG_DISPATCH_CYCLE) {
3227 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3228 "event",
3229 connection->getInputChannelName().c_str());
3230 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003231 return; // skip the inconsistent event
3232 }
3233
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003234 dispatchEntry->resolvedEventId =
3235 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3236 ? mIdGenerator.nextId()
3237 : motionEntry.id;
3238 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3239 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3240 ") to MotionEvent(id=0x%" PRIx32 ").",
3241 motionEntry.id, dispatchEntry->resolvedEventId);
3242 ATRACE_NAME(message.c_str());
3243 }
3244
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003245 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3246 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3247 // Skip reporting pointer down outside focus to the policy.
3248 break;
3249 }
3250
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003251 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003252 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003253
3254 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003256 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003257 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003258 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3259 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003260 break;
3261 }
Chris Yef59a2f42020-10-16 12:55:26 -07003262 case EventEntry::Type::SENSOR: {
3263 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3264 break;
3265 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003266 case EventEntry::Type::CONFIGURATION_CHANGED:
3267 case EventEntry::Type::DEVICE_RESET: {
3268 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003269 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003270 break;
3271 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003272 }
3273
3274 // Remember that we are waiting for this dispatch to complete.
3275 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003276 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003277 }
3278
3279 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003280 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003281 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003282}
3283
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003284/**
3285 * This function is purely for debugging. It helps us understand where the user interaction
3286 * was taking place. For example, if user is touching launcher, we will see a log that user
3287 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3288 * We will see both launcher and wallpaper in that list.
3289 * Once the interaction with a particular set of connections starts, no new logs will be printed
3290 * until the set of interacted connections changes.
3291 *
3292 * The following items are skipped, to reduce the logspam:
3293 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3294 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3295 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3296 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3297 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003298 */
3299void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3300 const std::vector<InputTarget>& targets) {
3301 // Skip ACTION_UP events, and all events other than keys and motions
3302 if (entry.type == EventEntry::Type::KEY) {
3303 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3304 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3305 return;
3306 }
3307 } else if (entry.type == EventEntry::Type::MOTION) {
3308 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3309 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3310 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3311 return;
3312 }
3313 } else {
3314 return; // Not a key or a motion
3315 }
3316
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003317 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003318 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003319 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003320 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003321 continue; // Skip windows that receive ACTION_OUTSIDE
3322 }
3323
3324 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003325 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003326 if (connection == nullptr) {
3327 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003328 }
3329 newConnectionTokens.insert(std::move(token));
3330 newConnections.emplace_back(connection);
3331 }
3332 if (newConnectionTokens == mInteractionConnectionTokens) {
3333 return; // no change
3334 }
3335 mInteractionConnectionTokens = newConnectionTokens;
3336
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003337 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003338 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003339 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003340 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003341 std::string message = "Interaction with: " + targetList;
3342 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003343 message += "<none>";
3344 }
3345 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3346}
3347
chaviwfd6d3512019-03-25 13:23:49 -07003348void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003349 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003350 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003351 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3352 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003353 return;
3354 }
3355
Vishnu Nairc519ff72021-01-21 08:23:08 -08003356 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003357 if (focusedToken == token) {
3358 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003359 return;
3360 }
3361
Prabir Pradhancef936d2021-07-21 16:17:52 +00003362 auto command = [this, token]() REQUIRES(mLock) {
3363 scoped_unlock unlock(mLock);
3364 mPolicy->onPointerDownOutsideFocus(token);
3365 };
3366 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003367}
3368
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003369status_t InputDispatcher::publishMotionEvent(Connection& connection,
3370 DispatchEntry& dispatchEntry) const {
3371 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3372 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3373
3374 PointerCoords scaledCoords[MAX_POINTERS];
3375 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3376
3377 // Set the X and Y offset and X and Y scale depending on the input source.
3378 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003379 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003380 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3381 if (globalScaleFactor != 1.0f) {
3382 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3383 scaledCoords[i] = motionEntry.pointerCoords[i];
3384 // Don't apply window scale here since we don't want scale to affect raw
3385 // coordinates. The scale will be sent back to the client and applied
3386 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003387 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003388 }
3389 usingCoords = scaledCoords;
3390 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003391 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003392 // We don't want the dispatch target to know the coordinates
3393 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3394 scaledCoords[i].clear();
3395 }
3396 usingCoords = scaledCoords;
3397 }
3398
3399 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3400
3401 // Publish the motion event.
3402 return connection.inputPublisher
3403 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3404 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3405 std::move(hmac), dispatchEntry.resolvedAction,
3406 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3407 motionEntry.edgeFlags, motionEntry.metaState,
3408 motionEntry.buttonState, motionEntry.classification,
3409 dispatchEntry.transform, motionEntry.xPrecision,
3410 motionEntry.yPrecision, motionEntry.xCursorPosition,
3411 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3412 motionEntry.downTime, motionEntry.eventTime,
3413 motionEntry.pointerCount, motionEntry.pointerProperties,
3414 usingCoords);
3415}
3416
Michael Wrightd02c5b62014-02-10 15:10:22 -08003417void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003418 const std::shared_ptr<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003419 if (ATRACE_ENABLED()) {
3420 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003421 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003422 ATRACE_NAME(message.c_str());
3423 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003424 if (DEBUG_DISPATCH_CYCLE) {
3425 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3426 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003427
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003428 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003429 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003431 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003432 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433
3434 // Publish the event.
3435 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003436 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3437 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003438 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003439 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3440 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003441 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3442 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3443 << connection->getInputChannelName();
3444 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003445
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003446 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003447 status = connection->inputPublisher
3448 .publishKeyEvent(dispatchEntry->seq,
3449 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3450 keyEntry.source, keyEntry.displayId,
3451 std::move(hmac), dispatchEntry->resolvedAction,
3452 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3453 keyEntry.scanCode, keyEntry.metaState,
3454 keyEntry.repeatCount, keyEntry.downTime,
3455 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003456 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003457 }
3458
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003459 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003460 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3461 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3462 << connection->getInputChannelName();
3463 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003464 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003465 break;
3466 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003467
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003468 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003469 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003470 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003471 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003472 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003473 break;
3474 }
3475
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003476 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3477 const TouchModeEntry& touchModeEntry =
3478 static_cast<const TouchModeEntry&>(eventEntry);
3479 status = connection->inputPublisher
3480 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3481 touchModeEntry.inTouchMode);
3482
3483 break;
3484 }
3485
Prabir Pradhan99987712020-11-10 18:43:05 -08003486 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3487 const auto& captureEntry =
3488 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3489 status = connection->inputPublisher
3490 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003491 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003492 break;
3493 }
3494
arthurhungb89ccb02020-12-30 16:19:01 +08003495 case EventEntry::Type::DRAG: {
3496 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3497 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3498 dragEntry.id, dragEntry.x,
3499 dragEntry.y,
3500 dragEntry.isExiting);
3501 break;
3502 }
3503
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003504 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003505 case EventEntry::Type::DEVICE_RESET:
3506 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003507 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003508 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003509 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003510 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511 }
3512
3513 // Check the result.
3514 if (status) {
3515 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003516 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003518 "This is unexpected because the wait queue is empty, so the pipe "
3519 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003520 "event to it, status=%s(%d)",
3521 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3522 status);
Harry Cutts33476232023-01-30 19:57:29 +00003523 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003524 } else {
3525 // Pipe is full and we are waiting for the app to finish process some events
3526 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003527 if (DEBUG_DISPATCH_CYCLE) {
3528 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3529 "waiting for the application to catch up",
3530 connection->getInputChannelName().c_str());
3531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 }
3533 } else {
3534 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003535 "status=%s(%d)",
3536 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3537 status);
Harry Cutts33476232023-01-30 19:57:29 +00003538 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003539 }
3540 return;
3541 }
3542
3543 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003544 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3545 connection->outboundQueue.end(),
3546 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003547 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003548 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003549 if (connection->responsive) {
3550 mAnrTracker.insert(dispatchEntry->timeoutTime,
3551 connection->inputChannel->getConnectionToken());
3552 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003553 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003554 }
3555}
3556
chaviw09c8d2d2020-08-24 15:48:26 -07003557std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3558 size_t size;
3559 switch (event.type) {
3560 case VerifiedInputEvent::Type::KEY: {
3561 size = sizeof(VerifiedKeyEvent);
3562 break;
3563 }
3564 case VerifiedInputEvent::Type::MOTION: {
3565 size = sizeof(VerifiedMotionEvent);
3566 break;
3567 }
3568 }
3569 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3570 return mHmacKeyManager.sign(start, size);
3571}
3572
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003573const std::array<uint8_t, 32> InputDispatcher::getSignature(
3574 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003575 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3576 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003577 // Only sign events up and down events as the purely move events
3578 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003579 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003580 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003581
3582 VerifiedMotionEvent verifiedEvent =
3583 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3584 verifiedEvent.actionMasked = actionMasked;
3585 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3586 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003587}
3588
3589const std::array<uint8_t, 32> InputDispatcher::getSignature(
3590 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3591 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3592 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3593 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003594 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003595}
3596
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003598 const std::shared_ptr<Connection>& connection,
3599 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003600 if (DEBUG_DISPATCH_CYCLE) {
3601 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3602 connection->getInputChannelName().c_str(), seq, toString(handled));
3603 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003605 if (connection->status == Connection::Status::BROKEN ||
3606 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003607 return;
3608 }
3609
3610 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003611 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3612 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3613 };
3614 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615}
3616
3617void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003618 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003619 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003620 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003621 LOG(DEBUG) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3622 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003623 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624
3625 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003626 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003627 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003628 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003629 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630
3631 // The connection appears to be unrecoverably broken.
3632 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003633 if (connection->status == Connection::Status::NORMAL) {
3634 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003635
3636 if (notify) {
3637 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003638 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3639 connection->getInputChannelName().c_str());
3640
3641 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003642 scoped_unlock unlock(mLock);
3643 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3644 };
3645 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646 }
3647 }
3648}
3649
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003650void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3651 while (!queue.empty()) {
3652 DispatchEntry* dispatchEntry = queue.front();
3653 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003654 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003655 }
3656}
3657
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003658void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003659 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003660 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661 }
3662 delete dispatchEntry;
3663}
3664
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003665int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3666 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003667 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003668 if (connection == nullptr) {
3669 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3670 connectionToken.get(), events);
3671 return 0; // remove the callback
3672 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003673
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003674 bool notify;
3675 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3676 if (!(events & ALOOPER_EVENT_INPUT)) {
3677 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3678 "events=0x%x",
3679 connection->getInputChannelName().c_str(), events);
3680 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681 }
3682
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003683 nsecs_t currentTime = now();
3684 bool gotOne = false;
3685 status_t status = OK;
3686 for (;;) {
3687 Result<InputPublisher::ConsumerResponse> result =
3688 connection->inputPublisher.receiveConsumerResponse();
3689 if (!result.ok()) {
3690 status = result.error().code();
3691 break;
3692 }
3693
3694 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3695 const InputPublisher::Finished& finish =
3696 std::get<InputPublisher::Finished>(*result);
3697 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3698 finish.consumeTime);
3699 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003700 if (shouldReportMetricsForConnection(*connection)) {
3701 const InputPublisher::Timeline& timeline =
3702 std::get<InputPublisher::Timeline>(*result);
3703 mLatencyTracker
3704 .trackGraphicsLatency(timeline.inputEventId,
3705 connection->inputChannel->getConnectionToken(),
3706 std::move(timeline.graphicsTimeline));
3707 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003708 }
3709 gotOne = true;
3710 }
3711 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003712 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003713 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714 return 1;
3715 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716 }
3717
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003718 notify = status != DEAD_OBJECT || !connection->monitor;
3719 if (notify) {
3720 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3721 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3722 status);
3723 }
3724 } else {
3725 // Monitor channels are never explicitly unregistered.
3726 // We do it automatically when the remote endpoint is closed so don't warn about them.
3727 const bool stillHaveWindowHandle =
3728 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3729 notify = !connection->monitor && stillHaveWindowHandle;
3730 if (notify) {
3731 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3732 connection->getInputChannelName().c_str(), events);
3733 }
3734 }
3735
3736 // Remove the channel.
3737 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3738 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739}
3740
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003741void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003743 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003744 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003745 }
3746}
3747
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003748void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003749 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003750 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003751 for (const Monitor& monitor : monitors) {
3752 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003753 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003754 }
3755}
3756
Michael Wrightd02c5b62014-02-10 15:10:22 -08003757void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003758 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003759 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003760 if (connection == nullptr) {
3761 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003763
3764 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765}
3766
3767void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003768 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003769 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770 return;
3771 }
3772
3773 nsecs_t currentTime = now();
3774
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003775 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003776 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003778 if (cancelationEvents.empty()) {
3779 return;
3780 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003781 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3782 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003783 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003784 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003785 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003786 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003787
Arthur Hungb3307ee2021-10-14 10:57:37 +00003788 std::string reason = std::string("reason=").append(options.reason);
3789 android_log_event_list(LOGTAG_INPUT_CANCEL)
3790 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3791
Svet Ganov5d3bc372020-01-26 23:11:07 -08003792 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003793 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003794 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3795 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003796 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003797 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003798 target.globalScaleFactor = windowInfo->globalScaleFactor;
3799 }
3800 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003801 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003802
hongzuo liu95785e22022-09-06 02:51:35 +00003803 const bool wasEmpty = connection->outboundQueue.empty();
3804
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003805 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003806 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003807 switch (cancelationEventEntry->type) {
3808 case EventEntry::Type::KEY: {
3809 logOutboundKeyDetails("cancel - ",
3810 static_cast<const KeyEntry&>(*cancelationEventEntry));
3811 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003812 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003813 case EventEntry::Type::MOTION: {
3814 logOutboundMotionDetails("cancel - ",
3815 static_cast<const MotionEntry&>(*cancelationEventEntry));
3816 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003818 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003819 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003820 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3821 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003822 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003823 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003824 break;
3825 }
3826 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003827 case EventEntry::Type::DEVICE_RESET:
3828 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003829 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003830 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003831 break;
3832 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833 }
3834
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003835 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003836 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003837 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003838
hongzuo liu95785e22022-09-06 02:51:35 +00003839 // If the outbound queue was previously empty, start the dispatch cycle going.
3840 if (wasEmpty && !connection->outboundQueue.empty()) {
3841 startDispatchCycleLocked(currentTime, connection);
3842 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003843}
3844
Svet Ganov5d3bc372020-01-26 23:11:07 -08003845void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003846 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00003847 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003848 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003849 return;
3850 }
3851
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003852 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003853 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003854
3855 if (downEvents.empty()) {
3856 return;
3857 }
3858
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003859 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003860 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3861 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003862 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003863
3864 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003865 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003866 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3867 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003868 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003869 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003870 target.globalScaleFactor = windowInfo->globalScaleFactor;
3871 }
3872 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00003873 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003874
hongzuo liu95785e22022-09-06 02:51:35 +00003875 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003876 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003877 switch (downEventEntry->type) {
3878 case EventEntry::Type::MOTION: {
3879 logOutboundMotionDetails("down - ",
3880 static_cast<const MotionEntry&>(*downEventEntry));
3881 break;
3882 }
3883
3884 case EventEntry::Type::KEY:
3885 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003886 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003887 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003888 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003889 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003890 case EventEntry::Type::SENSOR:
3891 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003892 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003893 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003894 break;
3895 }
3896 }
3897
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003898 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003899 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003900 }
3901
hongzuo liu95785e22022-09-06 02:51:35 +00003902 // If the outbound queue was previously empty, start the dispatch cycle going.
3903 if (wasEmpty && !connection->outboundQueue.empty()) {
3904 startDispatchCycleLocked(downTime, connection);
3905 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003906}
3907
Arthur Hungc539dbb2022-12-08 07:45:36 +00003908void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
3909 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
3910 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003911 std::shared_ptr<Connection> wallpaperConnection =
3912 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00003913 if (wallpaperConnection != nullptr) {
3914 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
3915 }
3916 }
3917}
3918
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003919std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003920 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
3921 nsecs_t splitDownTime) {
3922 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923
3924 uint32_t splitPointerIndexMap[MAX_POINTERS];
3925 PointerProperties splitPointerProperties[MAX_POINTERS];
3926 PointerCoords splitPointerCoords[MAX_POINTERS];
3927
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003928 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003929 uint32_t splitPointerCount = 0;
3930
3931 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003932 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003933 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003934 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003936 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3938 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3939 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003940 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003941 splitPointerCount += 1;
3942 }
3943 }
3944
3945 if (splitPointerCount != pointerIds.count()) {
3946 // This is bad. We are missing some of the pointers that we expected to deliver.
3947 // Most likely this indicates that we received an ACTION_MOVE events that has
3948 // different pointer ids than we expected based on the previous ACTION_DOWN
3949 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3950 // in this way.
3951 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003952 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003953 "a broken sequence of pointer ids from the input device: %s",
3954 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07003955 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956 }
3957
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003958 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003960 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3961 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3963 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003964 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003966 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967 if (pointerIds.count() == 1) {
3968 // The first/last pointer went down/up.
3969 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003970 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003971 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3972 ? AMOTION_EVENT_ACTION_CANCEL
3973 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 } else {
3975 // A secondary pointer went down/up.
3976 uint32_t splitPointerIndex = 0;
3977 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3978 splitPointerIndex += 1;
3979 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003980 action = maskedAction |
3981 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003982 }
3983 } else {
3984 // An unrelated pointer changed.
3985 action = AMOTION_EVENT_ACTION_MOVE;
3986 }
3987 }
3988
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003989 if (action == AMOTION_EVENT_ACTION_DOWN) {
3990 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3991 "Split motion event has mismatching downTime and eventTime for "
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08003992 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
3993 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003994 }
3995
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003996 int32_t newId = mIdGenerator.nextId();
3997 if (ATRACE_ENABLED()) {
3998 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3999 ") to MotionEvent(id=0x%" PRIx32 ").",
4000 originalMotionEntry.id, newId);
4001 ATRACE_NAME(message.c_str());
4002 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004003 std::unique_ptr<MotionEntry> splitMotionEntry =
4004 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4005 originalMotionEntry.deviceId, originalMotionEntry.source,
4006 originalMotionEntry.displayId,
4007 originalMotionEntry.policyFlags, action,
4008 originalMotionEntry.actionButton,
4009 originalMotionEntry.flags, originalMotionEntry.metaState,
4010 originalMotionEntry.buttonState,
4011 originalMotionEntry.classification,
4012 originalMotionEntry.edgeFlags,
4013 originalMotionEntry.xPrecision,
4014 originalMotionEntry.yPrecision,
4015 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004016 originalMotionEntry.yCursorPosition, splitDownTime,
4017 splitPointerCount, splitPointerProperties,
4018 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004020 if (originalMotionEntry.injectionState) {
4021 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004022 splitMotionEntry->injectionState->refCount += 1;
4023 }
4024
4025 return splitMotionEntry;
4026}
4027
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004028void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004029 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004030 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004031 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004032
Antonio Kantekf16f2832021-09-28 04:39:20 +00004033 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004034 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004035 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004036
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004037 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004038 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004039 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004040 } // release lock
4041
4042 if (needWake) {
4043 mLooper->wake();
4044 }
4045}
4046
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004047/**
4048 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004049 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4050 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4051 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4052 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4053 * potentially handle the back key presses.
4054 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4055 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004056 */
4057void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004058 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004059 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4060 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004061 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004062 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004063 }
4064 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004065 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004066 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004067 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004068 keyCode = newKeyCode;
4069 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4070 }
4071 } else if (action == AKEY_EVENT_ACTION_UP) {
4072 // In order to maintain a consistent stream of up and down events, check to see if the key
4073 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4074 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004075 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004076 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004077 auto replacementIt = mReplacedKeys.find(replacement);
4078 if (replacementIt != mReplacedKeys.end()) {
4079 keyCode = replacementIt->second;
4080 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004081 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4082 }
4083 }
4084}
4085
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004086void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004087 ALOGD_IF(debugInboundEventDetails(),
4088 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4089 ", deviceId=%d, source=%s, displayId=%" PRId32
4090 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4091 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004092 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4093 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4094 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
4095 if (!validateKeyEvent(args.action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004096 return;
4097 }
4098
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004099 uint32_t policyFlags = args.policyFlags;
4100 int32_t flags = args.flags;
4101 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004102 // InputDispatcher tracks and generates key repeats on behalf of
4103 // whatever notifies it, so repeatCount should always be set to 0
4104 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4106 policyFlags |= POLICY_FLAG_VIRTUAL;
4107 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4108 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109 if (policyFlags & POLICY_FLAG_FUNCTION) {
4110 metaState |= AMETA_FUNCTION_ON;
4111 }
4112
4113 policyFlags |= POLICY_FLAG_TRUSTED;
4114
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004115 int32_t keyCode = args.keyCode;
4116 accelerateMetaShortcuts(args.deviceId, args.action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004117
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004119 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4120 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4121 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122
Michael Wright2b3c3302018-03-02 17:19:13 +00004123 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004125 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4126 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004127 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004128 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129
Antonio Kantekf16f2832021-09-28 04:39:20 +00004130 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131 { // acquire lock
4132 mLock.lock();
4133
4134 if (shouldSendKeyToInputFilterLocked(args)) {
4135 mLock.unlock();
4136
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004137 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4139 return; // event was consumed by the filter
4140 }
4141
4142 mLock.lock();
4143 }
4144
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004145 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004146 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4147 args.displayId, policyFlags, args.action, flags, keyCode,
4148 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004150 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004151 mLock.unlock();
4152 } // release lock
4153
4154 if (needWake) {
4155 mLooper->wake();
4156 }
4157}
4158
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004159bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160 return mInputFilterEnabled;
4161}
4162
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004163void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004164 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004165 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004166 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004167 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004168 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4169 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004170 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4171 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4172 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4173 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4174 args.downTime);
4175 for (uint32_t i = 0; i < args.pointerCount; i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004176 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4177 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004178 i, args.pointerProperties[i].id,
4179 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4180 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4181 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4182 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4183 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4184 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4185 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4186 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4187 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4188 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004189 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190 }
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004191 LOG_ALWAYS_FATAL_IF(!validateMotionEvent(args.action, args.actionButton, args.pointerCount,
4192 args.pointerProperties),
4193 "Invalid event: %s", args.dump().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004195 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004197
4198 android::base::Timer t;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004199 mPolicy->interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004200 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4201 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004202 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004203 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204
Antonio Kantekf16f2832021-09-28 04:39:20 +00004205 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206 { // acquire lock
4207 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004208 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4209 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4210 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004211 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004212 if (touchStateIt != mTouchStatesByDisplay.end()) {
4213 const TouchState& touchState = touchStateIt->second;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004214 if (touchState.deviceId == args.deviceId && touchState.isDown()) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004215 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4216 }
4217 }
4218 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219
4220 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004221 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004222 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004223 displayTransform = it->second.transform;
4224 }
4225
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226 mLock.unlock();
4227
4228 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004229 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4230 args.action, args.actionButton, args.flags, args.edgeFlags,
4231 args.metaState, args.buttonState, args.classification,
4232 displayTransform, args.xPrecision, args.yPrecision,
4233 args.xCursorPosition, args.yCursorPosition, displayTransform,
4234 args.downTime, args.eventTime, args.pointerCount,
4235 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236
4237 policyFlags |= POLICY_FLAG_FILTERED;
4238 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4239 return; // event was consumed by the filter
4240 }
4241
4242 mLock.lock();
4243 }
4244
4245 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004246 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004247 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4248 args.displayId, policyFlags, args.action,
4249 args.actionButton, args.flags, args.metaState,
4250 args.buttonState, args.classification, args.edgeFlags,
4251 args.xPrecision, args.yPrecision,
4252 args.xCursorPosition, args.yCursorPosition,
4253 args.downTime, args.pointerCount,
4254 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004256 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4257 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004258 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004259 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4260 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004261 }
4262
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004263 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264 mLock.unlock();
4265 } // release lock
4266
4267 if (needWake) {
4268 mLooper->wake();
4269 }
4270}
4271
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004272void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004273 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004274 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4275 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004276 args.id, args.eventTime, args.deviceId, args.source,
4277 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004278 }
Chris Yef59a2f42020-10-16 12:55:26 -07004279
Antonio Kantekf16f2832021-09-28 04:39:20 +00004280 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004281 { // acquire lock
4282 mLock.lock();
4283
4284 // Just enqueue a new sensor event.
4285 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004286 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4287 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4288 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004289
4290 needWake = enqueueInboundEventLocked(std::move(newEntry));
4291 mLock.unlock();
4292 } // release lock
4293
4294 if (needWake) {
4295 mLooper->wake();
4296 }
4297}
4298
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004299void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004300 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004301 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4302 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004303 }
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004304 mPolicy->notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004305}
4306
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004307bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004308 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309}
4310
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004311void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004312 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004313 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4314 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004315 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004318 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004320 mPolicy->notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321}
4322
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004323void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004324 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004325 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4326 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004327 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328
Antonio Kantekf16f2832021-09-28 04:39:20 +00004329 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004331 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004333 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004334 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004335 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336 } // release lock
4337
4338 if (needWake) {
4339 mLooper->wake();
4340 }
4341}
4342
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004343void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004344 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004345 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4346 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004347 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004348
Antonio Kantekf16f2832021-09-28 04:39:20 +00004349 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004350 { // acquire lock
4351 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004352 auto entry =
4353 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004354 needWake = enqueueInboundEventLocked(std::move(entry));
4355 } // release lock
4356
4357 if (needWake) {
4358 mLooper->wake();
4359 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004360}
4361
Prabir Pradhan5735a322022-04-11 17:23:34 +00004362InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4363 std::optional<int32_t> targetUid,
4364 InputEventInjectionSync syncMode,
4365 std::chrono::milliseconds timeout,
4366 uint32_t policyFlags) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004367 if (debugInboundEventDetails()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004368 LOG(DEBUG) << __func__ << ": targetUid=" << toString(targetUid)
4369 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4370 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4371 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004372 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004373 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374
Prabir Pradhan5735a322022-04-11 17:23:34 +00004375 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004376
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004377 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004378 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4379 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4380 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4381 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4382 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004383 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004384 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004385 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004386 }
4387
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004388 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004390 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004391 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4392 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004393 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004394 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004395 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004397 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004398 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4399 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4400 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004401 int32_t keyCode = incomingKey.getKeyCode();
4402 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004403 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004404 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004405 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004406 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004407 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4408 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4409 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004410
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004411 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4412 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004413 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004414
4415 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4416 android::base::Timer t;
4417 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4418 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4419 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4420 std::to_string(t.duration().count()).c_str());
4421 }
4422 }
4423
4424 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004425 std::unique_ptr<KeyEntry> injectedEntry =
4426 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004427 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004428 incomingKey.getDisplayId(), policyFlags, action,
4429 flags, keyCode, incomingKey.getScanCode(), metaState,
4430 incomingKey.getRepeatCount(),
4431 incomingKey.getDownTime());
4432 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004433 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004434 }
4435
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004436 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004437 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004438 const int32_t action = motionEvent.getAction();
4439 const bool isPointerEvent =
4440 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4441 // If a pointer event has no displayId specified, inject it to the default display.
4442 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4443 ? ADISPLAY_ID_DEFAULT
4444 : event->getDisplayId();
4445 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004446 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004447 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004448 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004449 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004450 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004451 }
4452
4453 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004454 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004455 android::base::Timer t;
4456 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4457 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4458 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4459 std::to_string(t.duration().count()).c_str());
4460 }
4461 }
4462
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004463 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4464 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4465 }
4466
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004467 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004468 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4469 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004470 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004471 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4472 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004473 displayId, policyFlags, action, actionButton,
4474 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004475 motionEvent.getButtonState(),
4476 motionEvent.getClassification(),
4477 motionEvent.getEdgeFlags(),
4478 motionEvent.getXPrecision(),
4479 motionEvent.getYPrecision(),
4480 motionEvent.getRawXCursorPosition(),
4481 motionEvent.getRawYCursorPosition(),
4482 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004483 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004484 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004485 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004486 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004487 sampleEventTimes += 1;
4488 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004489 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004490 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4491 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004492 displayId, policyFlags, action, actionButton,
4493 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004494 motionEvent.getButtonState(),
4495 motionEvent.getClassification(),
4496 motionEvent.getEdgeFlags(),
4497 motionEvent.getXPrecision(),
4498 motionEvent.getYPrecision(),
4499 motionEvent.getRawXCursorPosition(),
4500 motionEvent.getRawYCursorPosition(),
4501 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004502 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004503 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004504 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4505 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004506 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004507 }
4508 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004511 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004512 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004513 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004514 }
4515
Prabir Pradhan5735a322022-04-11 17:23:34 +00004516 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004517 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004518 injectionState->injectionIsAsync = true;
4519 }
4520
4521 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004522 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523
4524 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004525 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004526 if (DEBUG_INJECTION) {
4527 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4528 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004529 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004530 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004531 }
4532
4533 mLock.unlock();
4534
4535 if (needWake) {
4536 mLooper->wake();
4537 }
4538
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004539 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004540 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004541 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004542
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004543 if (syncMode == InputEventInjectionSync::NONE) {
4544 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004545 } else {
4546 for (;;) {
4547 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004548 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549 break;
4550 }
4551
4552 nsecs_t remainingTimeout = endTime - now();
4553 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004554 if (DEBUG_INJECTION) {
4555 ALOGD("injectInputEvent - Timed out waiting for injection result "
4556 "to become available.");
4557 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004558 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559 break;
4560 }
4561
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004562 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563 }
4564
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004565 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4566 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004567 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004568 if (DEBUG_INJECTION) {
4569 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4570 injectionState->pendingForegroundDispatches);
4571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572 nsecs_t remainingTimeout = endTime - now();
4573 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004574 if (DEBUG_INJECTION) {
4575 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4576 "dispatches to finish.");
4577 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004578 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004579 break;
4580 }
4581
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004582 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004583 }
4584 }
4585 }
4586
4587 injectionState->release();
4588 } // release lock
4589
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004590 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004591 LOG(DEBUG) << "injectInputEvent - Finished with result "
4592 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004593 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004594
4595 return injectionResult;
4596}
4597
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004598std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004599 std::array<uint8_t, 32> calculatedHmac;
4600 std::unique_ptr<VerifiedInputEvent> result;
4601 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004602 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004603 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4604 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4605 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004606 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004607 break;
4608 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004609 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004610 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4611 VerifiedMotionEvent verifiedMotionEvent =
4612 verifiedMotionEventFromMotionEvent(motionEvent);
4613 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004614 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004615 break;
4616 }
4617 default: {
4618 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4619 return nullptr;
4620 }
4621 }
4622 if (calculatedHmac == INVALID_HMAC) {
4623 return nullptr;
4624 }
tyiu1573a672023-02-21 22:38:32 +00004625 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004626 return nullptr;
4627 }
4628 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004629}
4630
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004631void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004632 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004633 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004635 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004636 LOG(DEBUG) << "Setting input event injection result to "
4637 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004638 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004640 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004641 // Log the outcome since the injector did not wait for the injection result.
4642 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004643 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004644 ALOGV("Asynchronous input event injection succeeded.");
4645 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004646 case InputEventInjectionResult::TARGET_MISMATCH:
4647 ALOGV("Asynchronous input event injection target mismatch.");
4648 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004649 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004650 ALOGW("Asynchronous input event injection failed.");
4651 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004652 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004653 ALOGW("Asynchronous input event injection timed out.");
4654 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004655 case InputEventInjectionResult::PENDING:
4656 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4657 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004658 }
4659 }
4660
4661 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004662 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663 }
4664}
4665
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004666void InputDispatcher::transformMotionEntryForInjectionLocked(
4667 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004668 // Input injection works in the logical display coordinate space, but the input pipeline works
4669 // display space, so we need to transform the injected events accordingly.
4670 const auto it = mDisplayInfos.find(entry.displayId);
4671 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004672 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004673
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004674 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4675 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4676 const vec2 cursor =
4677 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4678 {entry.xCursorPosition, entry.yCursorPosition});
4679 entry.xCursorPosition = cursor.x;
4680 entry.yCursorPosition = cursor.y;
4681 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004682 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004683 entry.pointerCoords[i] =
4684 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4685 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004686 }
4687}
4688
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004689void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4690 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004691 if (injectionState) {
4692 injectionState->pendingForegroundDispatches += 1;
4693 }
4694}
4695
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004696void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4697 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004698 if (injectionState) {
4699 injectionState->pendingForegroundDispatches -= 1;
4700
4701 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004702 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703 }
4704 }
4705}
4706
chaviw98318de2021-05-19 16:45:23 -05004707const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004708 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004709 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004710 auto it = mWindowHandlesByDisplay.find(displayId);
4711 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004712}
4713
chaviw98318de2021-05-19 16:45:23 -05004714sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004715 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004716 if (windowHandleToken == nullptr) {
4717 return nullptr;
4718 }
4719
Arthur Hungb92218b2018-08-14 12:00:21 +08004720 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004721 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4722 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004723 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004724 return windowHandle;
4725 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726 }
4727 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004728 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004729}
4730
chaviw98318de2021-05-19 16:45:23 -05004731sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4732 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004733 if (windowHandleToken == nullptr) {
4734 return nullptr;
4735 }
4736
chaviw98318de2021-05-19 16:45:23 -05004737 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004738 if (windowHandle->getToken() == windowHandleToken) {
4739 return windowHandle;
4740 }
4741 }
4742 return nullptr;
4743}
4744
chaviw98318de2021-05-19 16:45:23 -05004745sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4746 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004747 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004748 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4749 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004750 if (handle->getId() == windowHandle->getId() &&
4751 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004752 if (windowHandle->getInfo()->displayId != it.first) {
4753 ALOGE("Found window %s in display %" PRId32
4754 ", but it should belong to display %" PRId32,
4755 windowHandle->getName().c_str(), it.first,
4756 windowHandle->getInfo()->displayId);
4757 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004758 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004759 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004760 }
4761 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004762 return nullptr;
4763}
4764
chaviw98318de2021-05-19 16:45:23 -05004765sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004766 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4767 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768}
4769
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004770ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4771 auto displayInfoIt = mDisplayInfos.find(displayId);
4772 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4773 : kIdentityTransform;
4774}
4775
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004776bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4777 const MotionEntry& motionEntry) const {
4778 const WindowInfo& info = *window->getInfo();
4779
4780 // Skip spy window targets that are not valid for targeted injection.
4781 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004782 return false;
4783 }
4784
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004785 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4786 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4787 return false;
4788 }
4789
4790 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4791 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4792 window->getName().c_str());
4793 return false;
4794 }
4795
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004796 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004797 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004798 ALOGW("Not sending touch to %s because there's no corresponding connection",
4799 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004800 return false;
4801 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004802
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004803 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004804 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004805 return false;
4806 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004807
4808 // Drop events that can't be trusted due to occlusion
4809 const auto [x, y] = resolveTouchedPosition(motionEntry);
4810 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4811 if (!isTouchTrustedLocked(occlusionInfo)) {
4812 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004813 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004814 for (const auto& log : occlusionInfo.debugInfo) {
4815 ALOGD("%s", log.c_str());
4816 }
4817 }
4818 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4819 occlusionInfo.obscuringUid);
4820 return false;
4821 }
4822
4823 // Drop touch events if requested by input feature
4824 if (shouldDropInput(motionEntry, window)) {
4825 return false;
4826 }
4827
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004828 return true;
4829}
4830
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004831std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4832 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004833 auto connectionIt = mConnectionsByToken.find(token);
4834 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004835 return nullptr;
4836 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004837 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004838}
4839
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004840void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004841 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4842 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004843 // Remove all handles on a display if there are no windows left.
4844 mWindowHandlesByDisplay.erase(displayId);
4845 return;
4846 }
4847
4848 // Since we compare the pointer of input window handles across window updates, we need
4849 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004850 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4851 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4852 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004853 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004854 }
4855
chaviw98318de2021-05-19 16:45:23 -05004856 std::vector<sp<WindowInfoHandle>> newHandles;
4857 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004858 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004859 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004860 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004861 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004862 const bool canReceiveInput =
4863 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4864 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004865 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004866 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004867 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004868 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004869 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004870 }
4871
4872 if (info->displayId != displayId) {
4873 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4874 handle->getName().c_str(), displayId, info->displayId);
4875 continue;
4876 }
4877
Robert Carredd13602020-04-13 17:24:34 -07004878 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4879 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004880 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004881 oldHandle->updateFrom(handle);
4882 newHandles.push_back(oldHandle);
4883 } else {
4884 newHandles.push_back(handle);
4885 }
4886 }
4887
4888 // Insert or replace
4889 mWindowHandlesByDisplay[displayId] = newHandles;
4890}
4891
Arthur Hung72d8dc32020-03-28 00:48:39 +00004892void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004893 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004894 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004895 { // acquire lock
4896 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004897 for (const auto& [displayId, handles] : handlesPerDisplay) {
4898 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004899 }
4900 }
4901 // Wake up poll loop since it may need to make new input dispatching choices.
4902 mLooper->wake();
4903}
4904
Arthur Hungb92218b2018-08-14 12:00:21 +08004905/**
4906 * Called from InputManagerService, update window handle list by displayId that can receive input.
4907 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4908 * If set an empty list, remove all handles from the specific display.
4909 * For focused handle, check if need to change and send a cancel event to previous one.
4910 * For removed handle, check if need to send a cancel event if already in touch.
4911 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004912void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004913 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004914 if (DEBUG_FOCUS) {
4915 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004916 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004917 windowList += iwh->getName() + " ";
4918 }
4919 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4920 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921
Prabir Pradhand65552b2021-10-07 11:23:50 -07004922 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004923 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004924 const WindowInfo& info = *window->getInfo();
4925
4926 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004927 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004928 if (noInputWindow && window->getToken() != nullptr) {
4929 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4930 window->getName().c_str());
4931 window->releaseChannel();
4932 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004933
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004934 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004935 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4936 !info.inputConfig.test(
4937 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004938 "%s has feature SPY, but is not a trusted overlay.",
4939 window->getName().c_str());
4940
Prabir Pradhand65552b2021-10-07 11:23:50 -07004941 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004942 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4943 !info.inputConfig.test(
4944 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004945 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4946 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004947 }
4948
Arthur Hung72d8dc32020-03-28 00:48:39 +00004949 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004950 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004951
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004952 // Save the old windows' orientation by ID before it gets updated.
4953 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004954 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004955 oldWindowOrientations.emplace(handle->getId(),
4956 handle->getInfo()->transform.getOrientation());
4957 }
4958
chaviw98318de2021-05-19 16:45:23 -05004959 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004960
chaviw98318de2021-05-19 16:45:23 -05004961 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004962
Vishnu Nairc519ff72021-01-21 08:23:08 -08004963 std::optional<FocusResolver::FocusChanges> changes =
4964 mFocusResolver.setInputWindows(displayId, windowHandles);
4965 if (changes) {
4966 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004967 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004968
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004969 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4970 mTouchStatesByDisplay.find(displayId);
4971 if (stateIt != mTouchStatesByDisplay.end()) {
4972 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004973 for (size_t i = 0; i < state.windows.size();) {
4974 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004975 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004976 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004977 ALOGD("Touched window was removed: %s in display %" PRId32,
4978 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004979 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004980 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004981 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4982 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004983 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00004984 "touched window was removed");
4985 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004986 // Since we are about to drop the touch, cancel the events for the wallpaper as
4987 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004988 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004989 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4990 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004991 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004992 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004993 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004994 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004995 state.windows.erase(state.windows.begin() + i);
4996 } else {
4997 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004998 }
4999 }
arthurhungb89ccb02020-12-30 16:19:01 +08005000
arthurhung6d4bed92021-03-17 11:59:33 +08005001 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005002 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005003 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005004 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005005 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005006 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5007 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005008 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005009 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005010 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005011
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005012 // Determine if the orientation of any of the input windows have changed, and cancel all
5013 // pointer events if necessary.
5014 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
5015 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
5016 if (newWindowHandle != nullptr &&
5017 newWindowHandle->getInfo()->transform.getOrientation() !=
5018 oldWindowOrientations[oldWindowHandle->getId()]) {
5019 std::shared_ptr<InputChannel> inputChannel =
5020 getInputChannelLocked(newWindowHandle->getToken());
5021 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005022 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005023 "touched window's orientation changed");
5024 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005025 }
5026 }
5027 }
5028
Arthur Hung72d8dc32020-03-28 00:48:39 +00005029 // Release information for windows that are no longer present.
5030 // This ensures that unused input channels are released promptly.
5031 // Otherwise, they might stick around until the window handle is destroyed
5032 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005033 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005034 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005035 if (DEBUG_FOCUS) {
5036 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005037 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005038 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005039 }
chaviw291d88a2019-02-14 10:33:58 -08005040 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005041}
5042
5043void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005044 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005045 if (DEBUG_FOCUS) {
5046 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5047 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5048 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005049 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005050 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005051 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005052 } // release lock
5053
5054 // Wake up poll loop since it may need to make new input dispatching choices.
5055 mLooper->wake();
5056}
5057
Vishnu Nair599f1412021-06-21 10:39:58 -07005058void InputDispatcher::setFocusedApplicationLocked(
5059 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5060 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5061 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5062
5063 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5064 return; // This application is already focused. No need to wake up or change anything.
5065 }
5066
5067 // Set the new application handle.
5068 if (inputApplicationHandle != nullptr) {
5069 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5070 } else {
5071 mFocusedApplicationHandlesByDisplay.erase(displayId);
5072 }
5073
5074 // No matter what the old focused application was, stop waiting on it because it is
5075 // no longer focused.
5076 resetNoFocusedWindowTimeoutLocked();
5077}
5078
Tiger Huang721e26f2018-07-24 22:26:19 +08005079/**
5080 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5081 * the display not specified.
5082 *
5083 * We track any unreleased events for each window. If a window loses the ability to receive the
5084 * released event, we will send a cancel event to it. So when the focused display is changed, we
5085 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5086 * display. The display-specified events won't be affected.
5087 */
5088void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005089 if (DEBUG_FOCUS) {
5090 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5091 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005092 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005093 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005094
5095 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005096 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005097 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005098 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005099 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005100 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005101 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005102 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005103 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005104 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005105 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005106 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5107 }
5108 }
5109 mFocusedDisplayId = displayId;
5110
Chris Ye3c2d6f52020-08-09 10:39:48 -07005111 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005112 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005113 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005114
Vishnu Nairad321cd2020-08-20 16:40:21 -07005115 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005116 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005117 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005118 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005119 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005120 }
5121 }
5122 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005123 } // release lock
5124
5125 // Wake up poll loop since it may need to make new input dispatching choices.
5126 mLooper->wake();
5127}
5128
Michael Wrightd02c5b62014-02-10 15:10:22 -08005129void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005130 if (DEBUG_FOCUS) {
5131 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5132 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005133
5134 bool changed;
5135 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005136 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005137
5138 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5139 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005140 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141 }
5142
5143 if (mDispatchEnabled && !enabled) {
5144 resetAndDropEverythingLocked("dispatcher is being disabled");
5145 }
5146
5147 mDispatchEnabled = enabled;
5148 mDispatchFrozen = frozen;
5149 changed = true;
5150 } else {
5151 changed = false;
5152 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153 } // release lock
5154
5155 if (changed) {
5156 // Wake up poll loop since it may need to make new input dispatching choices.
5157 mLooper->wake();
5158 }
5159}
5160
5161void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005162 if (DEBUG_FOCUS) {
5163 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5164 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005165
5166 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005167 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005168
5169 if (mInputFilterEnabled == enabled) {
5170 return;
5171 }
5172
5173 mInputFilterEnabled = enabled;
5174 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5175 } // release lock
5176
5177 // Wake up poll loop since there might be work to do to drop everything.
5178 mLooper->wake();
5179}
5180
Antonio Kanteka042c022022-07-06 16:51:07 -07005181bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5182 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005183 bool needWake = false;
5184 {
5185 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005186 ALOGD_IF(DEBUG_TOUCH_MODE,
5187 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5188 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5189 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5190 mTouchModePerDisplay.count(displayId) == 0
5191 ? "not set"
5192 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5193
Antonio Kantek15beb512022-06-13 22:35:41 +00005194 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5195 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005196 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005197 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005198 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005199 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5200 !recentWindowsAreOwnedByLocked(pid, uid)) {
5201 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5202 "window nor none of the previously interacted window",
5203 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005204 return false;
5205 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005206 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005207 mTouchModePerDisplay[displayId] = inTouchMode;
5208 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5209 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005210 needWake = enqueueInboundEventLocked(std::move(entry));
5211 } // release lock
5212
5213 if (needWake) {
5214 mLooper->wake();
5215 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005216 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005217}
5218
Antonio Kantek48710e42022-03-24 14:19:30 -07005219bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5220 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5221 if (focusedToken == nullptr) {
5222 return false;
5223 }
5224 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5225 return isWindowOwnedBy(windowHandle, pid, uid);
5226}
5227
5228bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5229 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5230 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5231 const sp<WindowInfoHandle> windowHandle =
5232 getWindowHandleLocked(connectionToken);
5233 return isWindowOwnedBy(windowHandle, pid, uid);
5234 }) != mInteractionConnectionTokens.end();
5235}
5236
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005237void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5238 if (opacity < 0 || opacity > 1) {
5239 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5240 return;
5241 }
5242
5243 std::scoped_lock lock(mLock);
5244 mMaximumObscuringOpacityForTouch = opacity;
5245}
5246
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005247std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5248InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005249 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5250 for (TouchedWindow& w : state.windows) {
5251 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005252 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005253 }
5254 }
5255 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005256 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005257}
5258
arthurhungb89ccb02020-12-30 16:19:01 +08005259bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5260 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005261 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005262 if (DEBUG_FOCUS) {
5263 ALOGD("Trivial transfer to same window.");
5264 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005265 return true;
5266 }
5267
Michael Wrightd02c5b62014-02-10 15:10:22 -08005268 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005269 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005270
Arthur Hungabbb9d82021-09-01 14:52:30 +00005271 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005272 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005273 if (state == nullptr || touchedWindow == nullptr) {
5274 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005275 return false;
5276 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005277
Arthur Hungabbb9d82021-09-01 14:52:30 +00005278 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5279 if (toWindowHandle == nullptr) {
5280 ALOGW("Cannot transfer focus because to window not found.");
5281 return false;
5282 }
5283
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005284 if (DEBUG_FOCUS) {
5285 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005286 touchedWindow->windowHandle->getName().c_str(),
5287 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005288 }
5289
Arthur Hungabbb9d82021-09-01 14:52:30 +00005290 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005291 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005292 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005293 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005294 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005295
Arthur Hungabbb9d82021-09-01 14:52:30 +00005296 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005297 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005298 ftl::Flags<InputTarget::Flags> newTargetFlags =
5299 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005300 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005301 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005302 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005303 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005304
Arthur Hungabbb9d82021-09-01 14:52:30 +00005305 // Store the dragging window.
5306 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005307 if (pointerIds.count() != 1) {
5308 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5309 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005310 return false;
5311 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005312 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005313 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005314 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005315 }
5316
Arthur Hungabbb9d82021-09-01 14:52:30 +00005317 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005318 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5319 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005320 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005321 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005322 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005323 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005324 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005325 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005326 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5327 newTargetFlags);
5328
5329 // Check if the wallpaper window should deliver the corresponding event.
5330 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5331 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005332 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005333 } // release lock
5334
5335 // Wake up poll loop since it may need to make new input dispatching choices.
5336 mLooper->wake();
5337 return true;
5338}
5339
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005340/**
5341 * Get the touched foreground window on the given display.
5342 * Return null if there are no windows touched on that display, or if more than one foreground
5343 * window is being touched.
5344 */
5345sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5346 auto stateIt = mTouchStatesByDisplay.find(displayId);
5347 if (stateIt == mTouchStatesByDisplay.end()) {
5348 ALOGI("No touch state on display %" PRId32, displayId);
5349 return nullptr;
5350 }
5351
5352 const TouchState& state = stateIt->second;
5353 sp<WindowInfoHandle> touchedForegroundWindow;
5354 // If multiple foreground windows are touched, return nullptr
5355 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005356 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005357 if (touchedForegroundWindow != nullptr) {
5358 ALOGI("Two or more foreground windows: %s and %s",
5359 touchedForegroundWindow->getName().c_str(),
5360 window.windowHandle->getName().c_str());
5361 return nullptr;
5362 }
5363 touchedForegroundWindow = window.windowHandle;
5364 }
5365 }
5366 return touchedForegroundWindow;
5367}
5368
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005369// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005370bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005371 sp<IBinder> fromToken;
5372 { // acquire lock
5373 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005374 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005375 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005376 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5377 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005378 return false;
5379 }
5380
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005381 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5382 if (from == nullptr) {
5383 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5384 return false;
5385 }
5386
5387 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005388 } // release lock
5389
5390 return transferTouchFocus(fromToken, destChannelToken);
5391}
5392
Michael Wrightd02c5b62014-02-10 15:10:22 -08005393void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005394 if (DEBUG_FOCUS) {
5395 ALOGD("Resetting and dropping all events (%s).", reason);
5396 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005397
Michael Wrightfb04fd52022-11-24 22:31:11 +00005398 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005399 synthesizeCancelationEventsForAllConnectionsLocked(options);
5400
5401 resetKeyRepeatLocked();
5402 releasePendingEventLocked();
5403 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005404 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005405
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005406 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005407 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005408 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005409}
5410
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005411void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005412 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005413 dumpDispatchStateLocked(dump);
5414
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005415 std::istringstream stream(dump);
5416 std::string line;
5417
5418 while (std::getline(stream, line, '\n')) {
5419 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005420 }
5421}
5422
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005423std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005424 std::string dump;
5425
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005426 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5427 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005428
5429 std::string windowName = "None";
5430 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005431 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005432 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5433 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5434 : "token has capture without window";
5435 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005436 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005437
5438 return dump;
5439}
5440
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005441void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005442 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5443 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5444 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005445 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005446
Tiger Huang721e26f2018-07-24 22:26:19 +08005447 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5448 dump += StringPrintf(INDENT "FocusedApplications:\n");
5449 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5450 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005451 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005452 const std::chrono::duration timeout =
5453 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005454 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005455 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005456 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005457 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005458 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005459 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005461
Vishnu Nairc519ff72021-01-21 08:23:08 -08005462 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005463 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005464
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005465 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005466 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005467 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005468 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5469 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005470 }
5471 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005472 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005473 }
5474
arthurhung6d4bed92021-03-17 11:59:33 +08005475 if (mDragState) {
5476 dump += StringPrintf(INDENT "DragState:\n");
5477 mDragState->dump(dump, INDENT2);
5478 }
5479
Arthur Hungb92218b2018-08-14 12:00:21 +08005480 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005481 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5482 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5483 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5484 const auto& displayInfo = it->second;
5485 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5486 displayInfo.logicalHeight);
5487 displayInfo.transform.dump(dump, "transform", INDENT4);
5488 } else {
5489 dump += INDENT2 "No DisplayInfo found!\n";
5490 }
5491
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005492 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005493 dump += INDENT2 "Windows:\n";
5494 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005495 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5496 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005498 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005499 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005500 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005501 "applicationInfo.name=%s, "
5502 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005503 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005504 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005505 windowInfo->displayId,
5506 windowInfo->inputConfig.string().c_str(),
5507 windowInfo->alpha, windowInfo->frameLeft,
5508 windowInfo->frameTop, windowInfo->frameRight,
5509 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005510 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005511 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005512 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005513 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005514 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005515 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005516 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005517 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005518 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005519 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005520 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005521 }
5522 } else {
5523 dump += INDENT2 "Windows: <none>\n";
5524 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005525 }
5526 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005527 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005528 }
5529
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005530 if (!mGlobalMonitorsByDisplay.empty()) {
5531 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5532 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005533 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005534 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005535 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005536 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005537 }
5538
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005539 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005540
5541 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005542 if (!mRecentQueue.empty()) {
5543 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005544 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005545 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005546 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005547 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005548 }
5549 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005550 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005551 }
5552
5553 // Dump event currently being dispatched.
5554 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005555 dump += INDENT "PendingEvent:\n";
5556 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005557 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005558 dump += StringPrintf(", age=%" PRId64 "ms\n",
5559 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005560 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005561 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562 }
5563
5564 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005565 if (!mInboundQueue.empty()) {
5566 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005567 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005568 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005569 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005570 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005571 }
5572 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005573 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005574 }
5575
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005576 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005577 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005578 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005579 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005580 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005581 }
5582 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005583 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005584 }
5585
Prabir Pradhancef936d2021-07-21 16:17:52 +00005586 if (!mCommandQueue.empty()) {
5587 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5588 } else {
5589 dump += INDENT "CommandQueue: <empty>\n";
5590 }
5591
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005592 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005593 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005594 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005595 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005596 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005597 connection->inputChannel->getFd().get(),
5598 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005599 connection->getWindowName().c_str(),
5600 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005601 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005602
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005603 if (!connection->outboundQueue.empty()) {
5604 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5605 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005606 dump += dumpQueue(connection->outboundQueue, currentTime);
5607
Michael Wrightd02c5b62014-02-10 15:10:22 -08005608 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005609 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005610 }
5611
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005612 if (!connection->waitQueue.empty()) {
5613 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5614 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005615 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005616 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005617 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005618 }
5619 }
5620 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005621 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005622 }
5623
5624 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005625 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5626 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005627 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005628 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005629 }
5630
Antonio Kantek15beb512022-06-13 22:35:41 +00005631 if (!mTouchModePerDisplay.empty()) {
5632 dump += INDENT "TouchModePerDisplay:\n";
5633 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5634 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5635 std::to_string(touchMode).c_str());
5636 }
5637 } else {
5638 dump += INDENT "TouchModePerDisplay: <none>\n";
5639 }
5640
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005641 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005642 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5643 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5644 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005645 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005646 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005647}
5648
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005649void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005650 const size_t numMonitors = monitors.size();
5651 for (size_t i = 0; i < numMonitors; i++) {
5652 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005653 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005654 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5655 dump += "\n";
5656 }
5657}
5658
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005659class LooperEventCallback : public LooperCallback {
5660public:
5661 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5662 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5663
5664private:
5665 std::function<int(int events)> mCallback;
5666};
5667
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005668Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005669 if (DEBUG_CHANNEL_CREATION) {
5670 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5671 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005672
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005673 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005674 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005675 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005676
5677 if (result) {
5678 return base::Error(result) << "Failed to open input channel pair with name " << name;
5679 }
5680
Michael Wrightd02c5b62014-02-10 15:10:22 -08005681 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005682 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005683 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005684 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005685 std::shared_ptr<Connection> connection =
5686 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5687 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005688
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005689 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5690 ALOGE("Created a new connection, but the token %p is already known", token.get());
5691 }
5692 mConnectionsByToken.emplace(token, connection);
5693
5694 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5695 this, std::placeholders::_1, token);
5696
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005697 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5698 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005699 } // release lock
5700
5701 // Wake the looper because some connections have changed.
5702 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005703 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005704}
5705
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005706Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005707 const std::string& name,
5708 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005709 std::shared_ptr<InputChannel> serverChannel;
5710 std::unique_ptr<InputChannel> clientChannel;
5711 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5712 if (result) {
5713 return base::Error(result) << "Failed to open input channel pair with name " << name;
5714 }
5715
Michael Wright3dd60e22019-03-27 22:06:44 +00005716 { // acquire lock
5717 std::scoped_lock _l(mLock);
5718
5719 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005720 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5721 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005722 }
5723
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005724 std::shared_ptr<Connection> connection =
5725 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005726 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005727 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005728
5729 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5730 ALOGE("Created a new connection, but the token %p is already known", token.get());
5731 }
5732 mConnectionsByToken.emplace(token, connection);
5733 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5734 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005735
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005736 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005737
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005738 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5739 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005740 }
Garfield Tan15601662020-09-22 15:32:38 -07005741
Michael Wright3dd60e22019-03-27 22:06:44 +00005742 // Wake the looper because some connections have changed.
5743 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005744 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005745}
5746
Garfield Tan15601662020-09-22 15:32:38 -07005747status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005748 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005749 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005750
Harry Cutts33476232023-01-30 19:57:29 +00005751 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005752 if (status) {
5753 return status;
5754 }
5755 } // release lock
5756
5757 // Wake the poll loop because removing the connection may have changed the current
5758 // synchronization state.
5759 mLooper->wake();
5760 return OK;
5761}
5762
Garfield Tan15601662020-09-22 15:32:38 -07005763status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5764 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005765 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005766 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005767 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005768 return BAD_VALUE;
5769 }
5770
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005771 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005772
Michael Wrightd02c5b62014-02-10 15:10:22 -08005773 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005774 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005775 }
5776
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005777 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005778
5779 nsecs_t currentTime = now();
5780 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5781
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005782 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783 return OK;
5784}
5785
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005786void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005787 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5788 auto& [displayId, monitors] = *it;
5789 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5790 return monitor.inputChannel->getConnectionToken() == connectionToken;
5791 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005792
Michael Wright3dd60e22019-03-27 22:06:44 +00005793 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005794 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005795 } else {
5796 ++it;
5797 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005798 }
5799}
5800
Michael Wright3dd60e22019-03-27 22:06:44 +00005801status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005802 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005803 return pilferPointersLocked(token);
5804}
Michael Wright3dd60e22019-03-27 22:06:44 +00005805
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005806status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005807 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5808 if (!requestingChannel) {
5809 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5810 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005811 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005812
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005813 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005814 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.none()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005815 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5816 " Ignoring.");
5817 return BAD_VALUE;
5818 }
5819
5820 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005821 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005822 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005823 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005824 "input channel stole pointer stream");
5825 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005826 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005827 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005828 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005829 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005830 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005831 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005832 if (channel != nullptr && channel->getConnectionToken() != token) {
5833 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5834 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5835 canceledWindows += channel->getName();
5836 }
5837 }
5838 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5839 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5840 canceledWindows.c_str());
5841
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005842 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005843 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005844 window.pilferedPointerIds |= window.pointerIds;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005845
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005846 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005847 return OK;
5848}
5849
Prabir Pradhan99987712020-11-10 18:43:05 -08005850void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5851 { // acquire lock
5852 std::scoped_lock _l(mLock);
5853 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005854 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005855 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5856 windowHandle != nullptr ? windowHandle->getName().c_str()
5857 : "token without window");
5858 }
5859
Vishnu Nairc519ff72021-01-21 08:23:08 -08005860 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005861 if (focusedToken != windowToken) {
5862 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5863 enabled ? "enable" : "disable");
5864 return;
5865 }
5866
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005867 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005868 ALOGW("Ignoring request to %s Pointer Capture: "
5869 "window has %s requested pointer capture.",
5870 enabled ? "enable" : "disable", enabled ? "already" : "not");
5871 return;
5872 }
5873
Christine Franksb768bb42021-11-29 12:11:31 -08005874 if (enabled) {
5875 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5876 mIneligibleDisplaysForPointerCapture.end(),
5877 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5878 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5879 return;
5880 }
5881 }
5882
Prabir Pradhan99987712020-11-10 18:43:05 -08005883 setPointerCaptureLocked(enabled);
5884 } // release lock
5885
5886 // Wake the thread to process command entries.
5887 mLooper->wake();
5888}
5889
Christine Franksb768bb42021-11-29 12:11:31 -08005890void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5891 { // acquire lock
5892 std::scoped_lock _l(mLock);
5893 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5894 if (!isEligible) {
5895 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5896 }
5897 } // release lock
5898}
5899
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005900std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5901 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005902 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005903 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005904 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005905 }
5906 }
5907 }
5908 return std::nullopt;
5909}
5910
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005911std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
5912 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005913 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005914 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005915 }
5916
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005917 for (const auto& [token, connection] : mConnectionsByToken) {
5918 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005919 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005920 }
5921 }
Robert Carr4e670e52018-08-15 13:26:12 -07005922
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005923 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005924}
5925
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005926std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005927 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005928 if (connection == nullptr) {
5929 return "<nullptr>";
5930 }
5931 return connection->getInputChannelName();
5932}
5933
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005934void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005935 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005936 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005937}
5938
Prabir Pradhancef936d2021-07-21 16:17:52 +00005939void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005940 const std::shared_ptr<Connection>& connection,
5941 uint32_t seq, bool handled,
5942 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005943 // Handle post-event policy actions.
5944 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5945 if (dispatchEntryIt == connection->waitQueue.end()) {
5946 return;
5947 }
5948 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5949 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5950 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5951 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5952 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5953 }
5954 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5955 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5956 connection->inputChannel->getConnectionToken(),
5957 dispatchEntry->deliveryTime, consumeTime, finishTime);
5958 }
5959
5960 bool restartEvent;
5961 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5962 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5963 restartEvent =
5964 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5965 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5966 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5967 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5968 handled);
5969 } else {
5970 restartEvent = false;
5971 }
5972
5973 // Dequeue the event and start the next cycle.
5974 // Because the lock might have been released, it is possible that the
5975 // contents of the wait queue to have been drained, so we need to double-check
5976 // a few things.
5977 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5978 if (dispatchEntryIt != connection->waitQueue.end()) {
5979 dispatchEntry = *dispatchEntryIt;
5980 connection->waitQueue.erase(dispatchEntryIt);
5981 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5982 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5983 if (!connection->responsive) {
5984 connection->responsive = isConnectionResponsive(*connection);
5985 if (connection->responsive) {
5986 // The connection was unresponsive, and now it's responsive.
5987 processConnectionResponsiveLocked(*connection);
5988 }
5989 }
5990 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005991 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005992 connection->outboundQueue.push_front(dispatchEntry);
5993 traceOutboundQueueLength(*connection);
5994 } else {
5995 releaseDispatchEntry(dispatchEntry);
5996 }
5997 }
5998
5999 // Start the next dispatch cycle for this connection.
6000 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006001}
6002
Prabir Pradhancef936d2021-07-21 16:17:52 +00006003void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6004 const sp<IBinder>& newToken) {
6005 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6006 scoped_unlock unlock(mLock);
6007 mPolicy->notifyFocusChanged(oldToken, newToken);
6008 };
6009 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006010}
6011
Prabir Pradhancef936d2021-07-21 16:17:52 +00006012void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6013 auto command = [this, token, x, y]() REQUIRES(mLock) {
6014 scoped_unlock unlock(mLock);
6015 mPolicy->notifyDropWindow(token, x, y);
6016 };
6017 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006018}
6019
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006020void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006021 if (connection == nullptr) {
6022 LOG_ALWAYS_FATAL("Caller must check for nullness");
6023 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006024 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6025 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006026 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006027 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006028 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006029 return;
6030 }
6031 /**
6032 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6033 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6034 * has changed. This could cause newer entries to time out before the already dispatched
6035 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6036 * processes the events linearly. So providing information about the oldest entry seems to be
6037 * most useful.
6038 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006039 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006040 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6041 std::string reason =
6042 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006043 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006044 ns2ms(currentWait),
6045 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006046 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006047 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006048
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006049 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6050
6051 // Stop waking up for events on this connection, it is already unresponsive
6052 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006053}
6054
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006055void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6056 std::string reason =
6057 StringPrintf("%s does not have a focused window", application->getName().c_str());
6058 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006059
Prabir Pradhancef936d2021-07-21 16:17:52 +00006060 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
6061 scoped_unlock unlock(mLock);
6062 mPolicy->notifyNoFocusedWindowAnr(application);
6063 };
6064 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006065}
6066
chaviw98318de2021-05-19 16:45:23 -05006067void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006068 const std::string& reason) {
6069 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6070 updateLastAnrStateLocked(windowLabel, reason);
6071}
6072
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006073void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6074 const std::string& reason) {
6075 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006076 updateLastAnrStateLocked(windowLabel, reason);
6077}
6078
6079void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6080 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006081 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006082 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006083 struct tm tm;
6084 localtime_r(&t, &tm);
6085 char timestr[64];
6086 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006087 mLastAnrState.clear();
6088 mLastAnrState += INDENT "ANR:\n";
6089 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006090 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6091 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006092 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006093}
6094
Prabir Pradhancef936d2021-07-21 16:17:52 +00006095void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6096 KeyEntry& entry) {
6097 const KeyEvent event = createKeyEvent(entry);
6098 nsecs_t delay = 0;
6099 { // release lock
6100 scoped_unlock unlock(mLock);
6101 android::base::Timer t;
6102 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
6103 entry.policyFlags);
6104 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6105 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6106 std::to_string(t.duration().count()).c_str());
6107 }
6108 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006109
6110 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006111 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006112 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006113 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006114 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006115 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006116 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006117 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006118}
6119
Prabir Pradhancef936d2021-07-21 16:17:52 +00006120void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006121 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006122 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006123 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006124 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006125 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006126 };
6127 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006128}
6129
Prabir Pradhanedd96402022-02-15 01:46:16 -08006130void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6131 std::optional<int32_t> pid) {
6132 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006133 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006134 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006135 };
6136 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006137}
6138
6139/**
6140 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6141 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6142 * command entry to the command queue.
6143 */
6144void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6145 std::string reason) {
6146 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006147 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006148 if (connection.monitor) {
6149 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6150 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006151 pid = findMonitorPidByTokenLocked(connectionToken);
6152 } else {
6153 // The connection is a window
6154 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6155 reason.c_str());
6156 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6157 if (handle != nullptr) {
6158 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006159 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006160 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006161 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006162}
6163
6164/**
6165 * Tell the policy that a connection has become responsive so that it can stop ANR.
6166 */
6167void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6168 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006169 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006170 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006171 pid = findMonitorPidByTokenLocked(connectionToken);
6172 } else {
6173 // The connection is a window
6174 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6175 if (handle != nullptr) {
6176 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006177 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006178 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006179 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006180}
6181
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006182bool InputDispatcher::afterKeyEventLockedInterruptable(
6183 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6184 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006185 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006186 if (!handled) {
6187 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006188 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006189 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006190 return false;
6191 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006192
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006193 // Get the fallback key state.
6194 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006195 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006196 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006197 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006198 connection->inputState.removeFallbackKey(originalKeyCode);
6199 }
6200
6201 if (handled || !dispatchEntry->hasForegroundTarget()) {
6202 // If the application handles the original key for which we previously
6203 // generated a fallback or if the window is not a foreground window,
6204 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006205 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006206 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006207 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6208 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6209 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6210 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6211 keyEntry.policyFlags);
6212 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006213 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006214 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006215
6216 mLock.unlock();
6217
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006218 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006219 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006220
6221 mLock.lock();
6222
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006223 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006224 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006225 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006226 "application handled the original non-fallback key "
6227 "or is no longer a foreground target, "
6228 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006229 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006230 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006231 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006232 connection->inputState.removeFallbackKey(originalKeyCode);
6233 }
6234 } else {
6235 // If the application did not handle a non-fallback key, first check
6236 // that we are in a good state to perform unhandled key event processing
6237 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006238 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006239 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006240 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6241 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6242 "since this is not an initial down. "
6243 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6244 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6245 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006246 return false;
6247 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006248
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006249 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006250 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6251 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6252 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6253 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6254 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006255 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006256
6257 mLock.unlock();
6258
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006259 bool fallback =
6260 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006261 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006262
6263 mLock.lock();
6264
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006265 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006266 connection->inputState.removeFallbackKey(originalKeyCode);
6267 return false;
6268 }
6269
6270 // Latch the fallback keycode for this key on an initial down.
6271 // The fallback keycode cannot change at any other point in the lifecycle.
6272 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006273 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006274 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006275 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006276 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006277 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006278 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006279 }
6280
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006281 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006282
6283 // Cancel the fallback key if the policy decides not to send it anymore.
6284 // We will continue to dispatch the key to the policy but we will no
6285 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006286 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6287 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006288 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6289 if (fallback) {
6290 ALOGD("Unhandled key event: Policy requested to send key %d"
6291 "as a fallback for %d, but on the DOWN it had requested "
6292 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006293 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006294 } else {
6295 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6296 "but on the DOWN it had requested to send %d. "
6297 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006298 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006299 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006300 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006301
Michael Wrightfb04fd52022-11-24 22:31:11 +00006302 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006303 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006304 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006305 synthesizeCancelationEventsForConnectionLocked(connection, options);
6306
6307 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006308 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006309 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006310 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006311 }
6312 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006313
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006314 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6315 {
6316 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006317 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006318 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006319 for (const auto& [key, value] : fallbackKeys) {
6320 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006321 }
6322 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6323 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006324 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006325 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006326
6327 if (fallback) {
6328 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006329 keyEntry.eventTime = event.getEventTime();
6330 keyEntry.deviceId = event.getDeviceId();
6331 keyEntry.source = event.getSource();
6332 keyEntry.displayId = event.getDisplayId();
6333 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006334 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006335 keyEntry.scanCode = event.getScanCode();
6336 keyEntry.metaState = event.getMetaState();
6337 keyEntry.repeatCount = event.getRepeatCount();
6338 keyEntry.downTime = event.getDownTime();
6339 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006340
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006341 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6342 ALOGD("Unhandled key event: Dispatching fallback key. "
6343 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006344 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006345 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006346 return true; // restart the event
6347 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006348 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6349 ALOGD("Unhandled key event: No fallback key.");
6350 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006351
6352 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006353 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006354 }
6355 }
6356 return false;
6357}
6358
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006359bool InputDispatcher::afterMotionEventLockedInterruptable(
6360 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6361 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006362 return false;
6363}
6364
Michael Wrightd02c5b62014-02-10 15:10:22 -08006365void InputDispatcher::traceInboundQueueLengthLocked() {
6366 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006367 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006368 }
6369}
6370
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006371void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006372 if (ATRACE_ENABLED()) {
6373 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006374 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6375 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006376 }
6377}
6378
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006379void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006380 if (ATRACE_ENABLED()) {
6381 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006382 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6383 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006384 }
6385}
6386
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006387void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006388 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006389
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006390 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006391 dumpDispatchStateLocked(dump);
6392
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006393 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006394 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006395 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006396 }
6397}
6398
6399void InputDispatcher::monitor() {
6400 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006401 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006402 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006403 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006404}
6405
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006406/**
6407 * Wake up the dispatcher and wait until it processes all events and commands.
6408 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6409 * this method can be safely called from any thread, as long as you've ensured that
6410 * the work you are interested in completing has already been queued.
6411 */
6412bool InputDispatcher::waitForIdle() {
6413 /**
6414 * Timeout should represent the longest possible time that a device might spend processing
6415 * events and commands.
6416 */
6417 constexpr std::chrono::duration TIMEOUT = 100ms;
6418 std::unique_lock lock(mLock);
6419 mLooper->wake();
6420 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6421 return result == std::cv_status::no_timeout;
6422}
6423
Vishnu Naire798b472020-07-23 13:52:21 -07006424/**
6425 * Sets focus to the window identified by the token. This must be called
6426 * after updating any input window handles.
6427 *
6428 * Params:
6429 * request.token - input channel token used to identify the window that should gain focus.
6430 * request.focusedToken - the token that the caller expects currently to be focused. If the
6431 * specified token does not match the currently focused window, this request will be dropped.
6432 * If the specified focused token matches the currently focused window, the call will succeed.
6433 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6434 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6435 * when requesting the focus change. This determines which request gets
6436 * precedence if there is a focus change request from another source such as pointer down.
6437 */
Vishnu Nair958da932020-08-21 17:12:37 -07006438void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6439 { // acquire lock
6440 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006441 std::optional<FocusResolver::FocusChanges> changes =
6442 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6443 if (changes) {
6444 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006445 }
6446 } // release lock
6447 // Wake up poll loop since it may need to make new input dispatching choices.
6448 mLooper->wake();
6449}
6450
Vishnu Nairc519ff72021-01-21 08:23:08 -08006451void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6452 if (changes.oldFocus) {
6453 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006454 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006455 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006456 "focus left window");
6457 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006458 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006459 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006460 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006461 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006462 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006463 }
6464
Prabir Pradhan99987712020-11-10 18:43:05 -08006465 // If a window has pointer capture, then it must have focus. We need to ensure that this
6466 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6467 // If the window loses focus before it loses pointer capture, then the window can be in a state
6468 // where it has pointer capture but not focus, violating the contract. Therefore we must
6469 // dispatch the pointer capture event before the focus event. Since focus events are added to
6470 // the front of the queue (above), we add the pointer capture event to the front of the queue
6471 // after the focus events are added. This ensures the pointer capture event ends up at the
6472 // front.
6473 disablePointerCaptureForcedLocked();
6474
Vishnu Nairc519ff72021-01-21 08:23:08 -08006475 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006476 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006477 }
6478}
Vishnu Nair958da932020-08-21 17:12:37 -07006479
Prabir Pradhan99987712020-11-10 18:43:05 -08006480void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006481 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006482 return;
6483 }
6484
6485 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6486
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006487 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006488 setPointerCaptureLocked(false);
6489 }
6490
6491 if (!mWindowTokenWithPointerCapture) {
6492 // No need to send capture changes because no window has capture.
6493 return;
6494 }
6495
6496 if (mPendingEvent != nullptr) {
6497 // Move the pending event to the front of the queue. This will give the chance
6498 // for the pending event to be dropped if it is a captured event.
6499 mInboundQueue.push_front(mPendingEvent);
6500 mPendingEvent = nullptr;
6501 }
6502
6503 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006504 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006505 mInboundQueue.push_front(std::move(entry));
6506}
6507
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006508void InputDispatcher::setPointerCaptureLocked(bool enable) {
6509 mCurrentPointerCaptureRequest.enable = enable;
6510 mCurrentPointerCaptureRequest.seq++;
6511 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006512 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006513 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006514 };
6515 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006516}
6517
Vishnu Nair599f1412021-06-21 10:39:58 -07006518void InputDispatcher::displayRemoved(int32_t displayId) {
6519 { // acquire lock
6520 std::scoped_lock _l(mLock);
6521 // Set an empty list to remove all handles from the specific display.
6522 setInputWindowsLocked(/* window handles */ {}, displayId);
6523 setFocusedApplicationLocked(displayId, nullptr);
6524 // Call focus resolver to clean up stale requests. This must be called after input windows
6525 // have been removed for the removed display.
6526 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006527 // Reset pointer capture eligibility, regardless of previous state.
6528 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006529 // Remove the associated touch mode state.
6530 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006531 } // release lock
6532
6533 // Wake up poll loop since it may need to make new input dispatching choices.
6534 mLooper->wake();
6535}
6536
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006537void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6538 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006539 // The listener sends the windows as a flattened array. Separate the windows by display for
6540 // more convenient parsing.
6541 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006542 for (const auto& info : windowInfos) {
6543 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006544 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006545 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006546
6547 { // acquire lock
6548 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006549
6550 // Ensure that we have an entry created for all existing displays so that if a displayId has
6551 // no windows, we can tell that the windows were removed from the display.
6552 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6553 handlesPerDisplay[displayId];
6554 }
6555
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006556 mDisplayInfos.clear();
6557 for (const auto& displayInfo : displayInfos) {
6558 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6559 }
6560
6561 for (const auto& [displayId, handles] : handlesPerDisplay) {
6562 setInputWindowsLocked(handles, displayId);
6563 }
6564 }
6565 // Wake up poll loop since it may need to make new input dispatching choices.
6566 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006567}
6568
Vishnu Nair062a8672021-09-03 16:07:44 -07006569bool InputDispatcher::shouldDropInput(
6570 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006571 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6572 (windowHandle->getInfo()->inputConfig.test(
6573 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006574 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006575 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6576 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006577 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006578 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006579 windowHandle->getInfo()->displayId);
6580 return true;
6581 }
6582 return false;
6583}
6584
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006585void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6586 const std::vector<gui::WindowInfo>& windowInfos,
6587 const std::vector<DisplayInfo>& displayInfos) {
6588 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6589}
6590
Arthur Hungdfd528e2021-12-08 13:23:04 +00006591void InputDispatcher::cancelCurrentTouch() {
6592 {
6593 std::scoped_lock _l(mLock);
6594 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006595 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006596 "cancel current touch");
6597 synthesizeCancelationEventsForAllConnectionsLocked(options);
6598
6599 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006600 }
6601 // Wake up poll loop since there might be work to do.
6602 mLooper->wake();
6603}
6604
Prabir Pradhan87112a72023-04-20 19:13:39 +00006605void InputDispatcher::requestRefreshConfiguration() {
6606 InputDispatcherConfiguration config;
6607 mPolicy->getDispatcherConfiguration(&config);
6608
6609 std::scoped_lock _l(mLock);
6610 mConfig = config;
6611}
6612
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006613void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6614 std::scoped_lock _l(mLock);
6615 mMonitorDispatchingTimeout = timeout;
6616}
6617
Arthur Hungc539dbb2022-12-08 07:45:36 +00006618void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6619 const sp<WindowInfoHandle>& oldWindowHandle,
6620 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006621 TouchState& state, int32_t pointerId,
6622 std::vector<InputTarget>& targets) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006623 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6624 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006625 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6626 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6627 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6628 newWindowHandle->getInfo()->inputConfig.test(
6629 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6630 const sp<WindowInfoHandle> oldWallpaper =
6631 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6632 const sp<WindowInfoHandle> newWallpaper =
6633 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6634 if (oldWallpaper == newWallpaper) {
6635 return;
6636 }
6637
6638 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006639 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6640 addWindowTargetLocked(oldWallpaper,
6641 oldTouchedWindow.targetFlags |
6642 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6643 pointerIds, oldTouchedWindow.firstDownTimeInTarget, targets);
6644 state.removeTouchedPointerFromWindow(pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006645 }
6646
6647 if (newWallpaper != nullptr) {
6648 state.addOrUpdateWindow(newWallpaper,
6649 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6650 InputTarget::Flags::WINDOW_IS_OBSCURED |
6651 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6652 pointerIds);
6653 }
6654}
6655
6656void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6657 ftl::Flags<InputTarget::Flags> newTargetFlags,
6658 const sp<WindowInfoHandle> fromWindowHandle,
6659 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006660 TouchState& state,
6661 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006662 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6663 fromWindowHandle->getInfo()->inputConfig.test(
6664 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6665 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6666 toWindowHandle->getInfo()->inputConfig.test(
6667 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6668
6669 const sp<WindowInfoHandle> oldWallpaper =
6670 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6671 const sp<WindowInfoHandle> newWallpaper =
6672 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6673 if (oldWallpaper == newWallpaper) {
6674 return;
6675 }
6676
6677 if (oldWallpaper != nullptr) {
6678 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6679 "transferring touch focus to another window");
6680 state.removeWindowByToken(oldWallpaper->getToken());
6681 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6682 }
6683
6684 if (newWallpaper != nullptr) {
6685 nsecs_t downTimeInTarget = now();
6686 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6687 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6688 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6689 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6690 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006691 std::shared_ptr<Connection> wallpaperConnection =
6692 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006693 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006694 std::shared_ptr<Connection> toConnection =
6695 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006696 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6697 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6698 wallpaperFlags);
6699 }
6700 }
6701}
6702
6703sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6704 const sp<WindowInfoHandle>& windowHandle) const {
6705 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6706 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6707 bool foundWindow = false;
6708 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6709 if (!foundWindow && otherHandle != windowHandle) {
6710 continue;
6711 }
6712 if (windowHandle == otherHandle) {
6713 foundWindow = true;
6714 continue;
6715 }
6716
6717 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6718 return otherHandle;
6719 }
6720 }
6721 return nullptr;
6722}
6723
Garfield Tane84e6f92019-08-29 17:28:41 -07006724} // namespace android::inputdispatcher