blob: 6e2f86223fa4dc2e67b3e55753030d5864979572 [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
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000120inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800121 return value ? "true" : "false";
122}
123
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000124inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000125 if (binder == nullptr) {
126 return "<null>";
127 }
128 return StringPrintf("%p", binder.get());
129}
130
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000131inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700132 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
133 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800134}
135
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000136bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800137 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700138 case AKEY_EVENT_ACTION_DOWN:
139 case AKEY_EVENT_ACTION_UP:
140 return true;
141 default:
142 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800143 }
144}
145
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000146bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700147 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800148 ALOGE("Key event has invalid action code 0x%x", action);
149 return false;
150 }
151 return true;
152}
153
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000154bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800155 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700156 case AMOTION_EVENT_ACTION_DOWN:
157 case AMOTION_EVENT_ACTION_UP:
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800158 return pointerCount == 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700159 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700160 case AMOTION_EVENT_ACTION_HOVER_ENTER:
161 case AMOTION_EVENT_ACTION_HOVER_MOVE:
162 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800163 return pointerCount >= 1;
164 case AMOTION_EVENT_ACTION_CANCEL:
165 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700166 case AMOTION_EVENT_ACTION_SCROLL:
167 return true;
168 case AMOTION_EVENT_ACTION_POINTER_DOWN:
169 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800170 const int32_t index = MotionEvent::getActionIndex(action);
171 return index >= 0 && index < pointerCount && pointerCount > 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700172 }
173 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
174 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
175 return actionButton != 0;
176 default:
177 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800178 }
179}
180
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000181int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500182 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
183}
184
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000185bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
186 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700187 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800188 ALOGE("Motion event has invalid action code 0x%x", action);
189 return false;
190 }
191 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800192 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %zu.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700193 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800194 return false;
195 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800196 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800197 for (size_t i = 0; i < pointerCount; i++) {
198 int32_t id = pointerProperties[i].id;
199 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700200 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
201 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800202 return false;
203 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800204 if (pointerIdBits.test(id)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800205 ALOGE("Motion event has duplicate pointer id %d", id);
206 return false;
207 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800208 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800209 }
210 return true;
211}
212
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000213std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800214 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000215 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 }
217
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000218 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800219 bool first = true;
220 Region::const_iterator cur = region.begin();
221 Region::const_iterator const tail = region.end();
222 while (cur != tail) {
223 if (first) {
224 first = false;
225 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800226 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800227 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800228 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800229 cur++;
230 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000231 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800232}
233
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000234std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500235 constexpr size_t maxEntries = 50; // max events to print
236 constexpr size_t skipBegin = maxEntries / 2;
237 const size_t skipEnd = queue.size() - maxEntries / 2;
238 // skip from maxEntries / 2 ... size() - maxEntries/2
239 // only print from 0 .. skipBegin and then from skipEnd .. size()
240
241 std::string dump;
242 for (size_t i = 0; i < queue.size(); i++) {
243 const DispatchEntry& entry = *queue[i];
244 if (i >= skipBegin && i < skipEnd) {
245 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
246 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
247 continue;
248 }
249 dump.append(INDENT4);
250 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800251 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
252 "ms",
253 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500254 ns2ms(currentTime - entry.eventEntry->eventTime));
255 if (entry.deliveryTime != 0) {
256 // This entry was delivered, so add information on how long we've been waiting
257 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
258 }
259 dump.append("\n");
260 }
261 return dump;
262}
263
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700264/**
265 * Find the entry in std::unordered_map by key, and return it.
266 * If the entry is not found, return a default constructed entry.
267 *
268 * Useful when the entries are vectors, since an empty vector will be returned
269 * if the entry is not found.
270 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
271 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700272template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000273V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700274 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700275 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800276}
277
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000278bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700279 if (first == second) {
280 return true;
281 }
282
283 if (first == nullptr || second == nullptr) {
284 return false;
285 }
286
287 return first->getToken() == second->getToken();
288}
289
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000290bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000291 if (first == nullptr || second == nullptr) {
292 return false;
293 }
294 return first->applicationInfo.token != nullptr &&
295 first->applicationInfo.token == second->applicationInfo.token;
296}
297
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800298template <typename T>
299size_t firstMarkedBit(T set) {
300 // TODO: replace with std::countr_zero from <bit> when that's available
301 LOG_ALWAYS_FATAL_IF(set.none());
302 size_t i = 0;
303 while (!set.test(i)) {
304 i++;
305 }
306 return i;
307}
308
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800309std::unique_ptr<DispatchEntry> createDispatchEntry(
310 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
311 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700312 if (inputTarget.useDefaultPointerTransform()) {
313 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700314 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700315 inputTarget.displayTransform,
316 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000317 }
318
319 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
320 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
321
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700322 std::vector<PointerCoords> pointerCoords;
323 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000324
325 // Use the first pointer information to normalize all other pointers. This could be any pointer
326 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700327 // uses the transform for the normalized pointer.
328 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800329 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700330 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000331
332 // Iterate through all pointers in the event to normalize against the first.
333 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
334 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
335 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700336 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000337
338 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700339 // First, apply the current pointer's transform to update the coordinates into
340 // window space.
341 pointerCoords[pointerIndex].transform(currTransform);
342 // Next, apply the inverse transform of the normalized coordinates so the
343 // current coordinates are transformed into the normalized coordinate space.
344 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000345 }
346
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700347 std::unique_ptr<MotionEntry> combinedMotionEntry =
348 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
349 motionEntry.deviceId, motionEntry.source,
350 motionEntry.displayId, motionEntry.policyFlags,
351 motionEntry.action, motionEntry.actionButton,
352 motionEntry.flags, motionEntry.metaState,
353 motionEntry.buttonState, motionEntry.classification,
354 motionEntry.edgeFlags, motionEntry.xPrecision,
355 motionEntry.yPrecision, motionEntry.xCursorPosition,
356 motionEntry.yCursorPosition, motionEntry.downTime,
357 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000358 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000359
360 if (motionEntry.injectionState) {
361 combinedMotionEntry->injectionState = motionEntry.injectionState;
362 combinedMotionEntry->injectionState->refCount += 1;
363 }
364
365 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700366 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700367 firstPointerTransform, inputTarget.displayTransform,
368 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000369 return dispatchEntry;
370}
371
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000372status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
373 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700374 std::unique_ptr<InputChannel> uniqueServerChannel;
375 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
376
377 serverChannel = std::move(uniqueServerChannel);
378 return result;
379}
380
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500381template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000382bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500383 if (lhs == nullptr && rhs == nullptr) {
384 return true;
385 }
386 if (lhs == nullptr || rhs == nullptr) {
387 return false;
388 }
389 return *lhs == *rhs;
390}
391
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000392KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000393 KeyEvent event;
394 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
395 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
396 entry.repeatCount, entry.downTime, entry.eventTime);
397 return event;
398}
399
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000400bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000401 // Do not keep track of gesture monitors. They receive every event and would disproportionately
402 // affect the statistics.
403 if (connection.monitor) {
404 return false;
405 }
406 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
407 if (!connection.responsive) {
408 return false;
409 }
410 return true;
411}
412
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000413bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000414 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
415 const int32_t& inputEventId = eventEntry.id;
416 if (inputEventId != dispatchEntry.resolvedEventId) {
417 // Event was transmuted
418 return false;
419 }
420 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
421 return false;
422 }
423 // Only track latency for events that originated from hardware
424 if (eventEntry.isSynthesized()) {
425 return false;
426 }
427 const EventEntry::Type& inputEventEntryType = eventEntry.type;
428 if (inputEventEntryType == EventEntry::Type::KEY) {
429 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
430 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
431 return false;
432 }
433 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
434 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
435 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
436 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
437 return false;
438 }
439 } else {
440 // Not a key or a motion
441 return false;
442 }
443 if (!shouldReportMetricsForConnection(connection)) {
444 return false;
445 }
446 return true;
447}
448
Prabir Pradhancef936d2021-07-21 16:17:52 +0000449/**
450 * Connection is responsive if it has no events in the waitQueue that are older than the
451 * current time.
452 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000453bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000454 const nsecs_t currentTime = now();
455 for (const DispatchEntry* entry : connection.waitQueue) {
456 if (entry->timeoutTime < currentTime) {
457 return false;
458 }
459 }
460 return true;
461}
462
Antonio Kantekf16f2832021-09-28 04:39:20 +0000463// Returns true if the event type passed as argument represents a user activity.
464bool isUserActivityEvent(const EventEntry& eventEntry) {
465 switch (eventEntry.type) {
466 case EventEntry::Type::FOCUS:
467 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
468 case EventEntry::Type::DRAG:
469 case EventEntry::Type::TOUCH_MODE_CHANGED:
470 case EventEntry::Type::SENSOR:
471 case EventEntry::Type::CONFIGURATION_CHANGED:
472 return false;
473 case EventEntry::Type::DEVICE_RESET:
474 case EventEntry::Type::KEY:
475 case EventEntry::Type::MOTION:
476 return true;
477 }
478}
479
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800480// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000481bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000482 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800483 const auto inputConfig = windowInfo.inputConfig;
484 if (windowInfo.displayId != displayId ||
485 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800486 return false;
487 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700488 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800489 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800490 return false;
491 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000492
493 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
494 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
495 // the window. Points on the right and bottom edges should not be inside the window, so we need
496 // to be careful about performing a hit test when the display is rotated, since the "right" and
497 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
498 // logical display in which WM determined the bounds. Perform the hit test in the logical
499 // display space to ensure these edges are considered correctly in all orientations.
500 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
501 const auto p = displayTransform.transform(x, y);
502 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800503 return false;
504 }
505 return true;
506}
507
Prabir Pradhand65552b2021-10-07 11:23:50 -0700508bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
509 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000510 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700511}
512
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800513// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000514// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
515// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
516// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800517// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000518bool canReceiveForegroundTouches(const WindowInfo& info) {
519 // A non-touchable window can still receive touch events (e.g. in the case of
520 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
521 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
522}
523
Antonio Kantek48710e42022-03-24 14:19:30 -0700524bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
525 if (windowHandle == nullptr) {
526 return false;
527 }
528 const WindowInfo* windowInfo = windowHandle->getInfo();
529 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
530 return true;
531 }
532 return false;
533}
534
Prabir Pradhan5735a322022-04-11 17:23:34 +0000535// Checks targeted injection using the window's owner's uid.
536// Returns an empty string if an entry can be sent to the given window, or an error message if the
537// entry is a targeted injection whose uid target doesn't match the window owner.
538std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
539 const EventEntry& entry) {
540 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
541 // The event was not injected, or the injected event does not target a window.
542 return {};
543 }
544 const int32_t uid = *entry.injectionState->targetUid;
545 if (window == nullptr) {
546 return StringPrintf("No valid window target for injection into uid %d.", uid);
547 }
548 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
549 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
550 "owned by uid %d.",
551 uid, window->getName().c_str(), window->getInfo()->ownerUid);
552 }
553 return {};
554}
555
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000556std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700557 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
558 // Always dispatch mouse events to cursor position.
559 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000560 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700561 }
562
563 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000564 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
565 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700566}
567
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700568std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
569 if (eventEntry.type == EventEntry::Type::KEY) {
570 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
571 return keyEntry.downTime;
572 } else if (eventEntry.type == EventEntry::Type::MOTION) {
573 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
574 return motionEntry.downTime;
575 }
576 return std::nullopt;
577}
578
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000579/**
580 * Compare the old touch state to the new touch state, and generate the corresponding touched
581 * windows (== input targets).
582 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
583 * If the pointer just entered the new window, produce HOVER_ENTER.
584 * For pointers remaining in the window, produce HOVER_MOVE.
585 */
586std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
587 const TouchState& newTouchState,
588 const MotionEntry& entry) {
589 std::vector<TouchedWindow> out;
590 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
591 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
592 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
593 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
594 // Not a hover event - don't need to do anything
595 return out;
596 }
597
598 // We should consider all hovering pointers here. But for now, just use the first one
599 const int32_t pointerId = entry.pointerProperties[0].id;
600
601 std::set<sp<WindowInfoHandle>> oldWindows;
602 if (oldState != nullptr) {
603 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
604 }
605
606 std::set<sp<WindowInfoHandle>> newWindows =
607 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
608
609 // If the pointer is no longer in the new window set, send HOVER_EXIT.
610 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
611 if (newWindows.find(oldWindow) == newWindows.end()) {
612 TouchedWindow touchedWindow;
613 touchedWindow.windowHandle = oldWindow;
614 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800615 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000616 out.push_back(touchedWindow);
617 }
618 }
619
620 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
621 TouchedWindow touchedWindow;
622 touchedWindow.windowHandle = newWindow;
623 if (oldWindows.find(newWindow) == oldWindows.end()) {
624 // Any windows that have this pointer now, and didn't have it before, should get
625 // HOVER_ENTER
626 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
627 } else {
628 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
629 LOG_ALWAYS_FATAL_IF(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE);
630 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
631 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800632 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000633 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
634 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
635 }
636 out.push_back(touchedWindow);
637 }
638 return out;
639}
640
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800641template <typename T>
642std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
643 left.insert(left.end(), right.begin(), right.end());
644 return left;
645}
646
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000647} // namespace
648
Michael Wrightd02c5b62014-02-10 15:10:22 -0800649// --- InputDispatcher ---
650
Garfield Tan00f511d2019-06-12 16:55:40 -0700651InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800652 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
653
654InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
655 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700656 : mPolicy(policy),
657 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700658 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800659 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700660 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700661 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700662 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800663 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700664 mDispatchEnabled(false),
665 mDispatchFrozen(false),
666 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100667 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000668 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800669 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800670 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000671 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000672 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700673 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800674 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800675
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700676 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700677#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700678 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700679#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700680 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681 policy->getDispatcherConfiguration(&mConfig);
682}
683
684InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000685 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800686
Prabir Pradhancef936d2021-07-21 16:17:52 +0000687 resetKeyRepeatLocked();
688 releasePendingEventLocked();
689 drainInboundQueueLocked();
690 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800691
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000692 while (!mConnectionsByToken.empty()) {
693 sp<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000694 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800695 }
696}
697
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700698status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700699 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700700 return ALREADY_EXISTS;
701 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700702 mThread = std::make_unique<InputThread>(
703 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
704 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700705}
706
707status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700708 if (mThread && mThread->isCallingThread()) {
709 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700710 return INVALID_OPERATION;
711 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700712 mThread.reset();
713 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700714}
715
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700717 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800719 std::scoped_lock _l(mLock);
720 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800721
722 // Run a dispatch loop if there are no pending commands.
723 // The dispatch loop might enqueue commands to run afterwards.
724 if (!haveCommandsLocked()) {
725 dispatchOnceInnerLocked(&nextWakeupTime);
726 }
727
728 // Run all pending commands if there are any.
729 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000730 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700731 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800732 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800733
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700734 // If we are still waiting for ack on some events,
735 // we might have to wake up earlier to check if an app is anr'ing.
736 const nsecs_t nextAnrCheck = processAnrsLocked();
737 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
738
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800739 // We are about to enter an infinitely long sleep, because we have no commands or
740 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700741 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800742 mDispatcherEnteredIdle.notify_all();
743 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744 } // release lock
745
746 // Wait for callback or timeout or wake. (make sure we round up, not down)
747 nsecs_t currentTime = now();
748 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
749 mLooper->pollOnce(timeoutMillis);
750}
751
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700752/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500753 * Raise ANR if there is no focused window.
754 * Before the ANR is raised, do a final state check:
755 * 1. The currently focused application must be the same one we are waiting for.
756 * 2. Ensure we still don't have a focused window.
757 */
758void InputDispatcher::processNoFocusedWindowAnrLocked() {
759 // Check if the application that we are waiting for is still focused.
760 std::shared_ptr<InputApplicationHandle> focusedApplication =
761 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
762 if (focusedApplication == nullptr ||
763 focusedApplication->getApplicationToken() !=
764 mAwaitedFocusedApplication->getApplicationToken()) {
765 // Unexpected because we should have reset the ANR timer when focused application changed
766 ALOGE("Waited for a focused window, but focused application has already changed to %s",
767 focusedApplication->getName().c_str());
768 return; // The focused application has changed.
769 }
770
chaviw98318de2021-05-19 16:45:23 -0500771 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500772 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
773 if (focusedWindowHandle != nullptr) {
774 return; // We now have a focused window. No need for ANR.
775 }
776 onAnrLocked(mAwaitedFocusedApplication);
777}
778
779/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700780 * Check if any of the connections' wait queues have events that are too old.
781 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
782 * Return the time at which we should wake up next.
783 */
784nsecs_t InputDispatcher::processAnrsLocked() {
785 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700786 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700787 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
788 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
789 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500790 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700791 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500792 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700793 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700794 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500795 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700796 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
797 }
798 }
799
800 // Check if any connection ANRs are due
801 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
802 if (currentTime < nextAnrCheck) { // most likely scenario
803 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
804 }
805
806 // If we reached here, we have an unresponsive connection.
807 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
808 if (connection == nullptr) {
809 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
810 return nextAnrCheck;
811 }
812 connection->responsive = false;
813 // Stop waking up for this unresponsive connection
814 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000815 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700816 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700817}
818
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800819std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
820 const sp<Connection>& connection) {
821 if (connection->monitor) {
822 return mMonitorDispatchingTimeout;
823 }
824 const sp<WindowInfoHandle> window =
825 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700826 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500827 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700828 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500829 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700830}
831
Michael Wrightd02c5b62014-02-10 15:10:22 -0800832void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
833 nsecs_t currentTime = now();
834
Jeff Browndc5992e2014-04-11 01:27:26 -0700835 // Reset the key repeat timer whenever normal dispatch is suspended while the
836 // device is in a non-interactive state. This is to ensure that we abort a key
837 // repeat if the device is just coming out of sleep.
838 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 resetKeyRepeatLocked();
840 }
841
842 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
843 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100844 if (DEBUG_FOCUS) {
845 ALOGD("Dispatch frozen. Waiting some more.");
846 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847 return;
848 }
849
850 // Optimize latency of app switches.
851 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
852 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
853 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
854 if (mAppSwitchDueTime < *nextWakeupTime) {
855 *nextWakeupTime = mAppSwitchDueTime;
856 }
857
858 // Ready to start a new event.
859 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700860 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700861 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 if (isAppSwitchDue) {
863 // The inbound queue is empty so the app switch key we were waiting
864 // for will never arrive. Stop waiting for it.
865 resetPendingAppSwitchLocked(false);
866 isAppSwitchDue = false;
867 }
868
869 // Synthesize a key repeat if appropriate.
870 if (mKeyRepeatState.lastKeyEntry) {
871 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
872 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
873 } else {
874 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
875 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
876 }
877 }
878 }
879
880 // Nothing to do if there is no pending event.
881 if (!mPendingEvent) {
882 return;
883 }
884 } else {
885 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700886 mPendingEvent = mInboundQueue.front();
887 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888 traceInboundQueueLengthLocked();
889 }
890
891 // Poke user activity for this event.
892 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700893 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895 }
896
897 // Now we have an event to dispatch.
898 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700899 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700901 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700903 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700905 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 }
907
908 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700909 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800910 }
911
912 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700913 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700914 const ConfigurationChangedEntry& typedEntry =
915 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700916 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700917 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700918 break;
919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700921 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700922 const DeviceResetEntry& typedEntry =
923 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700924 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700925 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700926 break;
927 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100929 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700930 std::shared_ptr<FocusEntry> typedEntry =
931 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100932 dispatchFocusLocked(currentTime, typedEntry);
933 done = true;
934 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
935 break;
936 }
937
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700938 case EventEntry::Type::TOUCH_MODE_CHANGED: {
939 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
940 dispatchTouchModeChangeLocked(currentTime, typedEntry);
941 done = true;
942 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
943 break;
944 }
945
Prabir Pradhan99987712020-11-10 18:43:05 -0800946 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
947 const auto typedEntry =
948 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
949 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
950 done = true;
951 break;
952 }
953
arthurhungb89ccb02020-12-30 16:19:01 +0800954 case EventEntry::Type::DRAG: {
955 std::shared_ptr<DragEntry> typedEntry =
956 std::static_pointer_cast<DragEntry>(mPendingEvent);
957 dispatchDragLocked(currentTime, typedEntry);
958 done = true;
959 break;
960 }
961
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700962 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700963 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700964 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700965 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700966 resetPendingAppSwitchLocked(true);
967 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700968 } else if (dropReason == DropReason::NOT_DROPPED) {
969 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700970 }
971 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700972 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700973 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700974 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700975 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
976 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700977 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700978 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700979 break;
980 }
981
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700982 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700983 std::shared_ptr<MotionEntry> motionEntry =
984 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700985 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
986 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700988 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700989 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700990 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700991 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
992 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700993 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700994 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700995 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996 }
Chris Yef59a2f42020-10-16 12:55:26 -0700997
998 case EventEntry::Type::SENSOR: {
999 std::shared_ptr<SensorEntry> sensorEntry =
1000 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1001 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1002 dropReason = DropReason::APP_SWITCH;
1003 }
1004 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1005 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1006 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1007 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1008 dropReason = DropReason::STALE;
1009 }
1010 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1011 done = true;
1012 break;
1013 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 }
1015
1016 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001017 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001018 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001019 }
Michael Wright3a981722015-06-10 15:26:13 +01001020 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021
1022 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001023 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 }
1025}
1026
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001027bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1028 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1029}
1030
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001031/**
1032 * Return true if the events preceding this incoming motion event should be dropped
1033 * Return false otherwise (the default behaviour)
1034 */
1035bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001036 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001037 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001038
1039 // Optimize case where the current application is unresponsive and the user
1040 // decides to touch a window in a different application.
1041 // If the application takes too long to catch up then we drop all events preceding
1042 // the touch into the other window.
1043 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001044 const int32_t displayId = motionEntry.displayId;
1045 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001046 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001047
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001048 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001049 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001050 touchedWindowHandle->getApplicationToken() !=
1051 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001052 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001053 ALOGI("Pruning input queue because user touched a different application while waiting "
1054 "for %s",
1055 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001056 return true;
1057 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001058
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001059 // Alternatively, maybe there's a spy window that could handle this event.
1060 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1061 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1062 for (const auto& windowHandle : touchedSpies) {
1063 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001064 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001065 // This spy window could take more input. Drop all events preceding this
1066 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001067 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001068 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001069 mAwaitedFocusedApplication->getName().c_str());
1070 return true;
1071 }
1072 }
1073 }
1074
1075 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1076 // yet been processed by some connections, the dispatcher will wait for these motion
1077 // events to be processed before dispatching the key event. This is because these motion events
1078 // may cause a new window to be launched, which the user might expect to receive focus.
1079 // To prevent waiting forever for such events, just send the key to the currently focused window
1080 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1081 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1082 "just send the pending key event to the focused window.");
1083 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001084 }
1085 return false;
1086}
1087
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001088bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001089 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001090 mInboundQueue.push_back(std::move(newEntry));
1091 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092 traceInboundQueueLengthLocked();
1093
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001094 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001095 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001096 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1097 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001098 // Optimize app switch latency.
1099 // If the application takes too long to catch up then we drop all events preceding
1100 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001101 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001102 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001103 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001104 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001105 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001106 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001107 if (DEBUG_APP_SWITCH) {
1108 ALOGD("App switch is pending!");
1109 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001110 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001111 mAppSwitchSawKeyDown = false;
1112 needWake = true;
1113 }
1114 }
1115 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001116
1117 // If a new up event comes in, and the pending event with same key code has been asked
1118 // to try again later because of the policy. We have to reset the intercept key wake up
1119 // time for it may have been handled in the policy and could be dropped.
1120 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1121 mPendingEvent->type == EventEntry::Type::KEY) {
1122 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1123 if (pendingKey.keyCode == keyEntry.keyCode &&
1124 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001125 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1126 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001127 pendingKey.interceptKeyWakeupTime = 0;
1128 needWake = true;
1129 }
1130 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001131 break;
1132 }
1133
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001134 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001135 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1136 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001137 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1138 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001139 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001141 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001143 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001144 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1145 break;
1146 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001147 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001148 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001149 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001150 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001151 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1152 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001153 // nothing to do
1154 break;
1155 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001156 }
1157
1158 return needWake;
1159}
1160
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001161void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001162 // Do not store sensor event in recent queue to avoid flooding the queue.
1163 if (entry->type != EventEntry::Type::SENSOR) {
1164 mRecentQueue.push_back(entry);
1165 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001166 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001167 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 }
1169}
1170
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001171std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001172InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001173 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001175 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001176 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001177 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001178 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001179 continue;
1180 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001182 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001183 if (!info.isSpy() &&
1184 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001185 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001186 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001187
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001188 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1189 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001190 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001191 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192 }
1193 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001194 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195}
1196
Prabir Pradhand65552b2021-10-07 11:23:50 -07001197std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001198 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001199 // Traverse windows from front to back and gather the touched spy windows.
1200 std::vector<sp<WindowInfoHandle>> spyWindows;
1201 const auto& windowHandles = getWindowHandlesLocked(displayId);
1202 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1203 const WindowInfo& info = *windowHandle->getInfo();
1204
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001205 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001206 continue;
1207 }
1208 if (!info.isSpy()) {
1209 // The first touched non-spy window was found, so return the spy windows touched so far.
1210 return spyWindows;
1211 }
1212 spyWindows.push_back(windowHandle);
1213 }
1214 return spyWindows;
1215}
1216
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001217void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218 const char* reason;
1219 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001220 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001221 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001222 ALOGD("Dropped event because policy consumed it.");
1223 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001224 reason = "inbound event was dropped because the policy consumed it";
1225 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001226 case DropReason::DISABLED:
1227 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001228 ALOGI("Dropped event because input dispatch is disabled.");
1229 }
1230 reason = "inbound event was dropped because input dispatch is disabled";
1231 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001232 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001233 ALOGI("Dropped event because of pending overdue app switch.");
1234 reason = "inbound event was dropped because of pending overdue app switch";
1235 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001236 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001237 ALOGI("Dropped event because the current application is not responding and the user "
1238 "has started interacting with a different application.");
1239 reason = "inbound event was dropped because the current application is not responding "
1240 "and the user has started interacting with a different application";
1241 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001242 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001243 ALOGI("Dropped event because it is stale.");
1244 reason = "inbound event was dropped because it is stale";
1245 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001246 case DropReason::NO_POINTER_CAPTURE:
1247 ALOGI("Dropped event because there is no window with Pointer Capture.");
1248 reason = "inbound event was dropped because there is no window with Pointer Capture";
1249 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001250 case DropReason::NOT_DROPPED: {
1251 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001252 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001253 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254 }
1255
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001256 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001257 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001258 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001260 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001262 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001263 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1264 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001265 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001266 synthesizeCancelationEventsForAllConnectionsLocked(options);
1267 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001268 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1269 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001270 synthesizeCancelationEventsForAllConnectionsLocked(options);
1271 }
1272 break;
1273 }
Chris Yef59a2f42020-10-16 12:55:26 -07001274 case EventEntry::Type::SENSOR: {
1275 break;
1276 }
arthurhungb89ccb02020-12-30 16:19:01 +08001277 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1278 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001279 break;
1280 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001281 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001282 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001283 case EventEntry::Type::CONFIGURATION_CHANGED:
1284 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001285 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001286 break;
1287 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288 }
1289}
1290
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001291static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001292 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1293 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294}
1295
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001296bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1297 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1298 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1299 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001300}
1301
1302bool InputDispatcher::isAppSwitchPendingLocked() {
Colin Cross5b799302022-10-18 21:52:41 -07001303 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304}
1305
1306void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001307 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001309 if (DEBUG_APP_SWITCH) {
1310 if (handled) {
1311 ALOGD("App switch has arrived.");
1312 } else {
1313 ALOGD("App switch was abandoned.");
1314 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316}
1317
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001319 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320}
1321
Prabir Pradhancef936d2021-07-21 16:17:52 +00001322bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001323 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 return false;
1325 }
1326
1327 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001328 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001329 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001330 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1331 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001332 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001333 return true;
1334}
1335
Prabir Pradhancef936d2021-07-21 16:17:52 +00001336void InputDispatcher::postCommandLocked(Command&& command) {
1337 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338}
1339
1340void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001341 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001342 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001343 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344 releaseInboundEventLocked(entry);
1345 }
1346 traceInboundQueueLengthLocked();
1347}
1348
1349void InputDispatcher::releasePendingEventLocked() {
1350 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001351 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001352 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001353 }
1354}
1355
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001356void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001357 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001358 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001359 if (DEBUG_DISPATCH_CYCLE) {
1360 ALOGD("Injected inbound event was dropped.");
1361 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001362 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363 }
1364 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001365 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366 }
1367 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001368}
1369
1370void InputDispatcher::resetKeyRepeatLocked() {
1371 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001372 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001373 }
1374}
1375
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001376std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1377 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378
Michael Wright2e732952014-09-24 13:26:59 -07001379 uint32_t policyFlags = entry->policyFlags &
1380 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001382 std::shared_ptr<KeyEntry> newEntry =
1383 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1384 entry->source, entry->displayId, policyFlags, entry->action,
1385 entry->flags, entry->keyCode, entry->scanCode,
1386 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001388 newEntry->syntheticRepeat = true;
1389 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001391 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001392}
1393
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001394bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001395 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001396 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1397 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1398 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399
1400 // Reset key repeating in case a keyboard device was added or removed or something.
1401 resetKeyRepeatLocked();
1402
1403 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001404 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1405 scoped_unlock unlock(mLock);
1406 mPolicy->notifyConfigurationChanged(eventTime);
1407 };
1408 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001409 return true;
1410}
1411
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001412bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1413 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001414 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1415 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1416 entry.deviceId);
1417 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001418
liushenxiang42232912021-05-21 20:24:09 +08001419 // Reset key repeating in case a keyboard device was disabled or enabled.
1420 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1421 resetKeyRepeatLocked();
1422 }
1423
Michael Wrightfb04fd52022-11-24 22:31:11 +00001424 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001425 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001426 synthesizeCancelationEventsForAllConnectionsLocked(options);
1427 return true;
1428}
1429
Vishnu Nairad321cd2020-08-20 16:40:21 -07001430void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001431 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001432 if (mPendingEvent != nullptr) {
1433 // Move the pending event to the front of the queue. This will give the chance
1434 // for the pending event to get dispatched to the newly focused window
1435 mInboundQueue.push_front(mPendingEvent);
1436 mPendingEvent = nullptr;
1437 }
1438
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001439 std::unique_ptr<FocusEntry> focusEntry =
1440 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1441 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001442
1443 // This event should go to the front of the queue, but behind all other focus events
1444 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001445 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001446 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001447 [](const std::shared_ptr<EventEntry>& event) {
1448 return event->type == EventEntry::Type::FOCUS;
1449 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001450
1451 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001452 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001453}
1454
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001455void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001456 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001457 if (channel == nullptr) {
1458 return; // Window has gone away
1459 }
1460 InputTarget target;
1461 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001462 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001463 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001464 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1465 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001466 std::string reason = std::string("reason=").append(entry->reason);
1467 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001468 dispatchEventLocked(currentTime, entry, {target});
1469}
1470
Prabir Pradhan99987712020-11-10 18:43:05 -08001471void InputDispatcher::dispatchPointerCaptureChangedLocked(
1472 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1473 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001474 dropReason = DropReason::NOT_DROPPED;
1475
Prabir Pradhan99987712020-11-10 18:43:05 -08001476 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001477 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001478
1479 if (entry->pointerCaptureRequest.enable) {
1480 // Enable Pointer Capture.
1481 if (haveWindowWithPointerCapture &&
1482 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001483 // This can happen if pointer capture is disabled and re-enabled before we notify the
1484 // app of the state change, so there is no need to notify the app.
1485 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1486 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001487 }
1488 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001489 // This can happen if a window requests capture and immediately releases capture.
1490 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001491 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001492 return;
1493 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001494 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1495 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1496 return;
1497 }
1498
Vishnu Nairc519ff72021-01-21 08:23:08 -08001499 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001500 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1501 mWindowTokenWithPointerCapture = token;
1502 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001503 // Disable Pointer Capture.
1504 // We do not check if the sequence number matches for requests to disable Pointer Capture
1505 // for two reasons:
1506 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1507 // to disable capture with the same sequence number: one generated by
1508 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1509 // Capture being disabled in InputReader.
1510 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1511 // actual Pointer Capture state that affects events being generated by input devices is
1512 // in InputReader.
1513 if (!haveWindowWithPointerCapture) {
1514 // Pointer capture was already forcefully disabled because of focus change.
1515 dropReason = DropReason::NOT_DROPPED;
1516 return;
1517 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001518 token = mWindowTokenWithPointerCapture;
1519 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001520 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001521 setPointerCaptureLocked(false);
1522 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001523 }
1524
1525 auto channel = getInputChannelLocked(token);
1526 if (channel == nullptr) {
1527 // Window has gone away, clean up Pointer Capture state.
1528 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001529 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001530 setPointerCaptureLocked(false);
1531 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001532 return;
1533 }
1534 InputTarget target;
1535 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001536 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001537 entry->dispatchInProgress = true;
1538 dispatchEventLocked(currentTime, entry, {target});
1539
1540 dropReason = DropReason::NOT_DROPPED;
1541}
1542
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001543void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1544 const std::shared_ptr<TouchModeEntry>& entry) {
1545 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001546 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001547 if (windowHandles.empty()) {
1548 return;
1549 }
1550 const std::vector<InputTarget> inputTargets =
1551 getInputTargetsFromWindowHandlesLocked(windowHandles);
1552 if (inputTargets.empty()) {
1553 return;
1554 }
1555 entry->dispatchInProgress = true;
1556 dispatchEventLocked(currentTime, entry, inputTargets);
1557}
1558
1559std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1560 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1561 std::vector<InputTarget> inputTargets;
1562 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001563 const sp<IBinder>& token = handle->getToken();
1564 if (token == nullptr) {
1565 continue;
1566 }
1567 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1568 if (channel == nullptr) {
1569 continue; // Window has gone away
1570 }
1571 InputTarget target;
1572 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001573 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001574 inputTargets.push_back(target);
1575 }
1576 return inputTargets;
1577}
1578
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001579bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001580 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001582 if (!entry->dispatchInProgress) {
1583 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1584 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1585 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1586 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001587 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001588 // We have seen two identical key downs in a row which indicates that the device
1589 // driver is automatically generating key repeats itself. We take note of the
1590 // repeat here, but we disable our own next key repeat timer since it is clear that
1591 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001592 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1593 // Make sure we don't get key down from a different device. If a different
1594 // device Id has same key pressed down, the new device Id will replace the
1595 // current one to hold the key repeat with repeat count reset.
1596 // In the future when got a KEY_UP on the device id, drop it and do not
1597 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001598 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1599 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001600 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001601 } else {
1602 // Not a repeat. Save key down state in case we do see a repeat later.
1603 resetKeyRepeatLocked();
1604 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1605 }
1606 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001607 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1608 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001609 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001610 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001611 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1612 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001613 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614 resetKeyRepeatLocked();
1615 }
1616
1617 if (entry->repeatCount == 1) {
1618 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1619 } else {
1620 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1621 }
1622
1623 entry->dispatchInProgress = true;
1624
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001625 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001626 }
1627
1628 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001629 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630 if (currentTime < entry->interceptKeyWakeupTime) {
1631 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1632 *nextWakeupTime = entry->interceptKeyWakeupTime;
1633 }
1634 return false; // wait until next wakeup
1635 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001636 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637 entry->interceptKeyWakeupTime = 0;
1638 }
1639
1640 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001641 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001643 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001644 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001645
1646 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1647 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1648 };
1649 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650 return false; // wait for the command to run
1651 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001652 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001653 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001654 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001655 if (*dropReason == DropReason::NOT_DROPPED) {
1656 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657 }
1658 }
1659
1660 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001661 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001662 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001663 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1664 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001665 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 return true;
1667 }
1668
1669 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001670 InputEventInjectionResult injectionResult;
1671 sp<WindowInfoHandle> focusedWindow =
1672 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1673 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001674 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 return false;
1676 }
1677
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001678 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001679 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 return true;
1681 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001682 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1683
1684 std::vector<InputTarget> inputTargets;
1685 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001686 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001687 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001689 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001690 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001691
1692 // Dispatch the key.
1693 dispatchEventLocked(currentTime, entry, inputTargets);
1694 return true;
1695}
1696
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001697void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001698 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1699 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1700 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1701 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1702 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1703 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1704 entry.metaState, entry.repeatCount, entry.downTime);
1705 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001706}
1707
Prabir Pradhancef936d2021-07-21 16:17:52 +00001708void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1709 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001710 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001711 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1712 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1713 "source=0x%x, sensorType=%s",
1714 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001715 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001716 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001717 auto command = [this, entry]() REQUIRES(mLock) {
1718 scoped_unlock unlock(mLock);
1719
1720 if (entry->accuracyChanged) {
1721 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1722 }
1723 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1724 entry->hwTimestamp, entry->values);
1725 };
1726 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001727}
1728
1729bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001730 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1731 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001732 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001733 }
Chris Yef59a2f42020-10-16 12:55:26 -07001734 { // acquire lock
1735 std::scoped_lock _l(mLock);
1736
1737 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1738 std::shared_ptr<EventEntry> entry = *it;
1739 if (entry->type == EventEntry::Type::SENSOR) {
1740 it = mInboundQueue.erase(it);
1741 releaseInboundEventLocked(entry);
1742 }
1743 }
1744 }
1745 return true;
1746}
1747
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001748bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001749 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001750 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001752 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001753 entry->dispatchInProgress = true;
1754
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001755 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756 }
1757
1758 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001759 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001760 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001761 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1762 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763 return true;
1764 }
1765
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001766 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767
1768 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001769 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770
1771 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001772 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773 if (isPointerEvent) {
1774 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001775
1776 if (mDragState &&
1777 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1778 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1779 pilferPointersLocked(mDragState->dragWindow->getToken());
1780 }
1781
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001782 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001783 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001784 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001785 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1786 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 } else {
1788 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001789 sp<WindowInfoHandle> focusedWindow =
1790 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1791 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1792 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1793 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001794 InputTarget::Flags::FOREGROUND |
1795 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001796 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001797 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001799 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800 return false;
1801 }
1802
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001803 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001804 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001805 return true;
1806 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001807 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001808 CancelationOptions::Mode mode(
1809 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1810 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001811 CancelationOptions options(mode, "input event injection failed");
1812 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813 return true;
1814 }
1815
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001816 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001817 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818
1819 // Dispatch the motion.
1820 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001821 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001822 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 synthesizeCancelationEventsForAllConnectionsLocked(options);
1824 }
1825 dispatchEventLocked(currentTime, entry, inputTargets);
1826 return true;
1827}
1828
chaviw98318de2021-05-19 16:45:23 -05001829void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001830 bool isExiting, const int32_t rawX,
1831 const int32_t rawY) {
1832 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001833 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001834 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1835 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001836
1837 enqueueInboundEventLocked(std::move(dragEntry));
1838}
1839
1840void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1841 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1842 if (channel == nullptr) {
1843 return; // Window has gone away
1844 }
1845 InputTarget target;
1846 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001847 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001848 entry->dispatchInProgress = true;
1849 dispatchEventLocked(currentTime, entry, {target});
1850}
1851
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001852void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001853 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001854 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001855 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001856 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001857 "metaState=0x%x, buttonState=0x%x,"
1858 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001859 prefix, entry.eventTime, entry.deviceId,
1860 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1861 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1862 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1863 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001865 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001866 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001867 "x=%f, y=%f, pressure=%f, size=%f, "
1868 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1869 "orientation=%f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001870 i, entry.pointerProperties[i].id,
1871 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001872 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1873 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1874 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1875 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1876 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1877 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1878 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1879 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1880 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001883}
1884
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001885void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1886 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001887 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001888 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001889 if (DEBUG_DISPATCH_CYCLE) {
1890 ALOGD("dispatchEventToCurrentInputTargets");
1891 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001893 updateInteractionTokensLocked(*eventEntry, inputTargets);
1894
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1896
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001897 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001899 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001900 sp<Connection> connection =
1901 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001902 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001903 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001905 if (DEBUG_FOCUS) {
1906 ALOGD("Dropping event delivery to target with channel '%s' because it "
1907 "is no longer registered with the input dispatcher.",
1908 inputTarget.inputChannel->getName().c_str());
1909 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910 }
1911 }
1912}
1913
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001914void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1915 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1916 // If the policy decides to close the app, we will get a channel removal event via
1917 // unregisterInputChannel, and will clean up the connection that way. We are already not
1918 // sending new pointers to the connection when it blocked, but focused events will continue to
1919 // pile up.
1920 ALOGW("Canceling events for %s because it is unresponsive",
1921 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001922 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001923 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001924 "application not responding");
1925 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926 }
1927}
1928
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001929void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001930 if (DEBUG_FOCUS) {
1931 ALOGD("Resetting ANR timeouts.");
1932 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933
1934 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001935 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001936 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937}
1938
Tiger Huang721e26f2018-07-24 22:26:19 +08001939/**
1940 * Get the display id that the given event should go to. If this event specifies a valid display id,
1941 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1942 * Focused display is the display that the user most recently interacted with.
1943 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001944int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001945 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001946 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001947 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001948 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1949 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001950 break;
1951 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001952 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001953 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1954 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001955 break;
1956 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001957 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001958 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001959 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001960 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001961 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001962 case EventEntry::Type::SENSOR:
1963 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001964 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001965 return ADISPLAY_ID_NONE;
1966 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001967 }
1968 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1969}
1970
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001971bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1972 const char* focusedWindowName) {
1973 if (mAnrTracker.empty()) {
1974 // already processed all events that we waited for
1975 mKeyIsWaitingForEventsTimeout = std::nullopt;
1976 return false;
1977 }
1978
1979 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1980 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001981 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001982 mKeyIsWaitingForEventsTimeout = currentTime +
1983 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1984 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001985 return true;
1986 }
1987
1988 // We still have pending events, and already started the timer
1989 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1990 return true; // Still waiting
1991 }
1992
1993 // Waited too long, and some connection still hasn't processed all motions
1994 // Just send the key to the focused window
1995 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1996 focusedWindowName);
1997 mKeyIsWaitingForEventsTimeout = std::nullopt;
1998 return false;
1999}
2000
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002001sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2002 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2003 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002004 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002005 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006
Tiger Huang721e26f2018-07-24 22:26:19 +08002007 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002008 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002009 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002010 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2011
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012 // If there is no currently focused window and no focused application
2013 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002014 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2015 ALOGI("Dropping %s event because there is no focused window or focused application in "
2016 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002017 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002018 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019 }
2020
Vishnu Nair062a8672021-09-03 16:07:44 -07002021 // Drop key events if requested by input feature
2022 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002023 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002024 }
2025
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002026 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2027 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2028 // start interacting with another application via touch (app switch). This code can be removed
2029 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2030 // an app is expected to have a focused window.
2031 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2032 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2033 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002034 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2035 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2036 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002037 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002038 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002039 ALOGW("Waiting because no window has focus but %s may eventually add a "
2040 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002041 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002042 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002043 outInjectionResult = InputEventInjectionResult::PENDING;
2044 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002045 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2046 // Already raised ANR. Drop the event
2047 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002048 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002049 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002050 } else {
2051 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002052 outInjectionResult = InputEventInjectionResult::PENDING;
2053 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002054 }
2055 }
2056
2057 // we have a valid, non-null focused window
2058 resetNoFocusedWindowTimeoutLocked();
2059
Prabir Pradhan5735a322022-04-11 17:23:34 +00002060 // Verify targeted injection.
2061 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2062 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002063 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2064 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002065 }
2066
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002067 if (focusedWindowHandle->getInfo()->inputConfig.test(
2068 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002069 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002070 outInjectionResult = InputEventInjectionResult::PENDING;
2071 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002072 }
2073
2074 // If the event is a key event, then we must wait for all previous events to
2075 // complete before delivering it because previous events may have the
2076 // side-effect of transferring focus to a different window and we want to
2077 // ensure that the following keys are sent to the new window.
2078 //
2079 // Suppose the user touches a button in a window then immediately presses "A".
2080 // If the button causes a pop-up window to appear then we want to ensure that
2081 // the "A" key is delivered to the new pop-up window. This is because users
2082 // often anticipate pending UI changes when typing on a keyboard.
2083 // To obtain this behavior, we must serialize key events with respect to all
2084 // prior input events.
2085 if (entry.type == EventEntry::Type::KEY) {
2086 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2087 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002088 outInjectionResult = InputEventInjectionResult::PENDING;
2089 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002090 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 }
2092
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002093 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2094 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002095}
2096
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002097/**
2098 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2099 * that are currently unresponsive.
2100 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002101std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2102 const std::vector<Monitor>& monitors) const {
2103 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002104 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002105 [this](const Monitor& monitor) REQUIRES(mLock) {
2106 sp<Connection> connection =
2107 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002108 if (connection == nullptr) {
2109 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002110 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002111 return false;
2112 }
2113 if (!connection->responsive) {
2114 ALOGW("Unresponsive monitor %s will not get the new gesture",
2115 connection->inputChannel->getName().c_str());
2116 return false;
2117 }
2118 return true;
2119 });
2120 return responsiveMonitors;
2121}
2122
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002123/**
2124 * In general, touch should be always split between windows. Some exceptions:
2125 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2126 * from the same device, *and* the window that's receiving the current pointer does not support
2127 * split touch.
2128 * 2. Don't split mouse events
2129 */
2130bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2131 const MotionEntry& entry) const {
2132 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2133 // We should never split mouse events
2134 return false;
2135 }
2136 for (const TouchedWindow& touchedWindow : touchState.windows) {
2137 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2138 // Spy windows should not affect whether or not touch is split.
2139 continue;
2140 }
2141 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2142 continue;
2143 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002144 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2145 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2146 // Wallpaper window should not affect whether or not touch is split
2147 continue;
2148 }
2149
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002150 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2151 // being sent there. For now, use deviceId from touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002152 if (entry.deviceId == touchState.deviceId && touchedWindow.pointerIds.any()) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002153 return false;
2154 }
2155 }
2156 return true;
2157}
2158
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002159std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002160 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2161 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002162 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002163
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002164 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165 // For security reasons, we defer updating the touch state until we are sure that
2166 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002167 const int32_t displayId = entry.displayId;
2168 const int32_t action = entry.action;
2169 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170
2171 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002172 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002174 // Copy current touch state into tempTouchState.
2175 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2176 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002177 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002178 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002179 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2180 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002181 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002182 }
2183
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002184 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002185 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002186 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002187
2188 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2189 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2190 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002191 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2192 // touchable windows.
2193 const bool wasDown = oldState != nullptr && oldState->isDown();
2194 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2195 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
2196 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002197 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002198
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002199 // If pointers are already down, let's finish the current gesture and ignore the new events
2200 // from another device. However, if the new event is a down event, let's cancel the current
2201 // touch and let the new one take over.
2202 if (switchedDevice && wasDown && !isDown) {
2203 LOG(INFO) << "Dropping event because a pointer for device " << oldState->deviceId
2204 << " is already down in display " << displayId << ": " << entry.getDescription();
2205 // TODO(b/211379801): test multiple simultaneous input streams.
2206 outInjectionResult = InputEventInjectionResult::FAILED;
2207 return {}; // wrong device
2208 }
2209
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002211 // If a new gesture is starting, clear the touch state completely.
2212 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002213 tempTouchState.deviceId = entry.deviceId;
2214 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002216 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002217 ALOGI("Dropping move event because a pointer for a different device is already active "
2218 "in display %" PRId32,
2219 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002220 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002221 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002222 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002223 }
2224
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002225 if (isHoverAction) {
2226 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2227 // all of the existing hovering pointers and recompute.
2228 tempTouchState.clearHoveringPointers();
2229 }
2230
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2232 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002233 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002234 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002235 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2236 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002237 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002238 auto [newTouchedWindowHandle, outsideTargets] =
2239 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002240
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002241 if (isDown) {
2242 targets += outsideTargets;
2243 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002244 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002245 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002246 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002248 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002249 }
2250
Prabir Pradhan5735a322022-04-11 17:23:34 +00002251 // Verify targeted injection.
2252 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2253 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002254 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002255 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002256 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002257 }
2258
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002259 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002260 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002261 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2262 // New window supports splitting, but we should never split mouse events.
2263 isSplit = !isFromMouse;
2264 } else if (isSplit) {
2265 // New window does not support splitting but we have already split events.
2266 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002267 newTouchedWindowHandle = nullptr;
2268 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002269 } else {
2270 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002271 // be delivered to a new window which supports split touch. Pointers from a mouse device
2272 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002273 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002274 }
2275
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002276 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002277 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002278 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002279 // Process the foreground window first so that it is the first to receive the event.
2280 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002281 }
2282
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002283 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002284 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2285 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002286 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002287 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002288 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002289 }
2290
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002291 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002292 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002293 continue;
2294 }
2295
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002296 if (isHoverAction) {
2297 const int32_t pointerId = entry.pointerProperties[0].id;
2298 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2299 // Pointer left. Remove it
2300 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2301 } else {
2302 // The "windowHandle" is the target of this hovering pointer.
2303 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId,
2304 pointerId);
2305 }
2306 }
2307
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002308 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002309 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002310
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002311 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2312 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002313 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002314 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002315
2316 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002317 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002318 }
2319 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002320 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002321 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002322 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002323 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002324
2325 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002326 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002327 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002328 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002329 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002330
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002331 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2332 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2333
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002334 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2335 // still add a window to the touch state. We should avoid doing that, but some of the
2336 // later checks ("at least one foreground window") rely on this in order to dispatch
2337 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002338 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002339 isDownOrPointerDown
2340 ? std::make_optional(entry.eventTime)
2341 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002342
2343 // If this is the pointer going down and the touched window has a wallpaper
2344 // then also add the touched wallpaper windows so they are locked in for the duration
2345 // of the touch gesture.
2346 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2347 // engine only supports touch events. We would need to add a mechanism similar
2348 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002349 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002350 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2351 windowHandle->getInfo()->inputConfig.test(
2352 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2353 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2354 if (wallpaper != nullptr) {
2355 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2356 InputTarget::Flags::WINDOW_IS_OBSCURED |
2357 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2358 InputTarget::Flags::DISPATCH_AS_IS;
2359 if (isSplit) {
2360 wallpaperFlags |= InputTarget::Flags::SPLIT;
2361 }
2362 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2363 entry.eventTime);
2364 }
2365 }
2366 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002368
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002369 // If a window is already pilfering some pointers, give it this new pointer as well and
2370 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2371 // which is a specific behaviour that we want.
2372 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2373 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002374 if (touchedWindow.pointerIds.test(pointerId) &&
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002375 touchedWindow.pilferedPointerIds.count() > 0) {
2376 // This window is already pilfering some pointers, and this new pointer is also
2377 // going to it. Therefore, take over this pointer and don't give it to anyone
2378 // else.
2379 touchedWindow.pilferedPointerIds.set(pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002380 }
2381 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002382
2383 // Restrict all pilfered pointers to the pilfering windows.
2384 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002385 } else {
2386 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2387
2388 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002389 if (!tempTouchState.isDown()) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002390 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2391 "dropped the pointer down event in display "
2392 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002393 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002394 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395 }
2396
arthurhung6d4bed92021-03-17 11:59:33 +08002397 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002398
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002400 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002401 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002402 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002403 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002404 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002405 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002406 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002407
Prabir Pradhan5735a322022-04-11 17:23:34 +00002408 // Verify targeted injection.
2409 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2410 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002411 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002412 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002413 }
2414
Vishnu Nair062a8672021-09-03 16:07:44 -07002415 // Drop touch events if requested by input feature
2416 if (newTouchedWindowHandle != nullptr &&
2417 shouldDropInput(entry, newTouchedWindowHandle)) {
2418 newTouchedWindowHandle = nullptr;
2419 }
2420
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002421 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2422 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002423 if (DEBUG_FOCUS) {
2424 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2425 oldTouchedWindowHandle->getName().c_str(),
2426 newTouchedWindowHandle->getName().c_str(), displayId);
2427 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002428 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002429 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002430 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002431 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002432
2433 const TouchedWindow& touchedWindow =
2434 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2435 addWindowTargetLocked(oldTouchedWindowHandle,
2436 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
2437 touchedWindow.firstDownTimeInTarget, targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002438
2439 // Make a slippery entrance into the new window.
2440 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002441 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442 }
2443
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002444 ftl::Flags<InputTarget::Flags> targetFlags =
2445 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002446 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002447 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002448 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002449 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002450 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002451 }
2452 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002453 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002454 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002455 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002456 }
2457
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002458 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2459 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002460
2461 // Check if the wallpaper window should deliver the corresponding event.
2462 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002463 tempTouchState, pointerId, targets);
2464 tempTouchState.removeTouchedPointerFromWindow(pointerId, oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002465 }
2466 }
Arthur Hung96483742022-11-15 03:30:48 +00002467
2468 // Update the pointerIds for non-splittable when it received pointer down.
2469 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2470 // If no split, we suppose all touched windows should receive pointer down.
2471 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2472 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2473 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2474 // Ignore drag window for it should just track one pointer.
2475 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2476 continue;
2477 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002478 touchedWindow.pointerIds.set(entry.pointerProperties[pointerIndex].id);
Arthur Hung96483742022-11-15 03:30:48 +00002479 }
2480 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002481 }
2482
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002483 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002484 {
2485 std::vector<TouchedWindow> hoveringWindows =
2486 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2487 for (const TouchedWindow& touchedWindow : hoveringWindows) {
2488 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2489 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2490 targets);
2491 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002492 }
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002493 // Ensure that we have at least one foreground window or at least one window that cannot be a
2494 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2495 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2496 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002497 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2498 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002499 return !canReceiveForegroundTouches(
2500 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002501 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002502 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002503 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2504 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002505 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002506 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002507 }
2508
Prabir Pradhan5735a322022-04-11 17:23:34 +00002509 // Ensure that all touched windows are valid for injection.
2510 if (entry.injectionState != nullptr) {
2511 std::string errs;
2512 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002513 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002514 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2515 // dispatched to any uid, since the coords will be zeroed out later.
2516 continue;
2517 }
2518 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2519 if (err) errs += "\n - " + *err;
2520 }
2521 if (!errs.empty()) {
2522 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2523 "%d:%s",
2524 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002525 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002526 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002527 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002528 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002529
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002530 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2531 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002533 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002534 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002535 if (foregroundWindowHandle) {
2536 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002537 for (InputTarget& target : targets) {
2538 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2539 sp<WindowInfoHandle> targetWindow =
2540 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2541 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2542 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002543 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002544 }
2545 }
2546 }
2547 }
2548
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002549 // Success! Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002550 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002551 if (touchedWindow.pointerIds.none() && !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002552 // Windows with hovering pointers are getting persisted inside TouchState.
2553 // Do not send this event to those windows.
2554 continue;
2555 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002556 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2557 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2558 targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002559 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002560
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002561 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002562 // Drop the outside or hover touch windows since we will not care about them
2563 // in the next iteration.
2564 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565
Michael Wrightd02c5b62014-02-10 15:10:22 -08002566 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002567 if (switchedDevice) {
2568 if (DEBUG_FOCUS) {
2569 ALOGD("Conflicting pointer actions: Switched to a different device.");
2570 }
2571 *outConflictingPointerActions = true;
2572 }
2573
2574 if (isHoverAction) {
2575 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002576 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002577 ALOGD_IF(DEBUG_FOCUS,
2578 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002579 *outConflictingPointerActions = true;
2580 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002581 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2582 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2583 tempTouchState.deviceId = entry.deviceId;
2584 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002585 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002586 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2587 // Pointer went up.
2588 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002589 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002590 // All pointers up or canceled.
2591 tempTouchState.reset();
2592 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2593 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002594 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2595 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002596 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002597 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002598 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2599 // One pointer went up.
2600 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2601 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002602
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002603 for (size_t i = 0; i < tempTouchState.windows.size();) {
2604 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002605 touchedWindow.pointerIds.reset(pointerId);
2606 if (touchedWindow.pointerIds.none()) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002607 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2608 continue;
2609 }
2610 i += 1;
2611 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002612 }
2613
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002614 // Save changes unless the action was scroll in which case the temporary touch
2615 // state was only valid for this one action.
2616 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002617 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002618 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002619 mTouchStatesByDisplay[displayId] = tempTouchState;
2620 } else {
2621 mTouchStatesByDisplay.erase(displayId);
2622 }
2623 }
2624
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002625 if (tempTouchState.windows.empty()) {
2626 mTouchStatesByDisplay.erase(displayId);
2627 }
2628
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002629 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002630}
2631
arthurhung6d4bed92021-03-17 11:59:33 +08002632void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002633 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2634 // have an explicit reason to support it.
2635 constexpr bool isStylus = false;
2636
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002637 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002638 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002639 if (dropWindow) {
2640 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002641 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002642 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002643 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002644 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002645 }
2646 mDragState.reset();
2647}
2648
2649void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002650 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002651 return;
2652 }
2653
arthurhung6d4bed92021-03-17 11:59:33 +08002654 if (!mDragState->isStartDrag) {
2655 mDragState->isStartDrag = true;
2656 mDragState->isStylusButtonDownAtStart =
2657 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2658 }
2659
Arthur Hung54745652022-04-20 07:17:41 +00002660 // Find the pointer index by id.
2661 int32_t pointerIndex = 0;
2662 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2663 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2664 if (pointerProperties.id == mDragState->pointerId) {
2665 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002666 }
Arthur Hung54745652022-04-20 07:17:41 +00002667 }
arthurhung6d4bed92021-03-17 11:59:33 +08002668
Arthur Hung54745652022-04-20 07:17:41 +00002669 if (uint32_t(pointerIndex) == entry.pointerCount) {
2670 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002671 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002672 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002673 return;
2674 }
2675
2676 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2677 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2678 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2679
2680 switch (maskedAction) {
2681 case AMOTION_EVENT_ACTION_MOVE: {
2682 // Handle the special case : stylus button no longer pressed.
2683 bool isStylusButtonDown =
2684 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2685 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2686 finishDragAndDrop(entry.displayId, x, y);
2687 return;
2688 }
2689
2690 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2691 // until we have an explicit reason to support it.
2692 constexpr bool isStylus = false;
2693
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002694 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002695 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002696 // enqueue drag exit if needed.
2697 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2698 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2699 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002700 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002701 y);
2702 }
2703 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2704 }
2705 // enqueue drag location if needed.
2706 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002707 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002708 }
2709 break;
2710 }
2711
2712 case AMOTION_EVENT_ACTION_POINTER_UP:
2713 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2714 break;
2715 }
2716 // The drag pointer is up.
2717 [[fallthrough]];
2718 case AMOTION_EVENT_ACTION_UP:
2719 finishDragAndDrop(entry.displayId, x, y);
2720 break;
2721 case AMOTION_EVENT_ACTION_CANCEL: {
2722 ALOGD("Receiving cancel when drag and drop.");
2723 sendDropWindowCommandLocked(nullptr, 0, 0);
2724 mDragState.reset();
2725 break;
2726 }
arthurhungb89ccb02020-12-30 16:19:01 +08002727 }
2728}
2729
chaviw98318de2021-05-19 16:45:23 -05002730void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002731 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002732 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002733 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002734 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002735 std::vector<InputTarget>::iterator it =
2736 std::find_if(inputTargets.begin(), inputTargets.end(),
2737 [&windowHandle](const InputTarget& inputTarget) {
2738 return inputTarget.inputChannel->getConnectionToken() ==
2739 windowHandle->getToken();
2740 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002741
chaviw98318de2021-05-19 16:45:23 -05002742 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002743
2744 if (it == inputTargets.end()) {
2745 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002746 std::shared_ptr<InputChannel> inputChannel =
2747 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002748 if (inputChannel == nullptr) {
2749 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2750 return;
2751 }
2752 inputTarget.inputChannel = inputChannel;
2753 inputTarget.flags = targetFlags;
2754 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002755 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002756 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2757 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002758 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002759 } else {
Siarhei Vishniakoua06bb552023-02-07 09:38:56 -08002760 // DisplayInfo not found for this window on display windowInfo->displayId.
2761 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002762 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002763 inputTargets.push_back(inputTarget);
2764 it = inputTargets.end() - 1;
2765 }
2766
2767 ALOG_ASSERT(it->flags == targetFlags);
2768 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2769
chaviw1ff3d1e2020-07-01 15:53:47 -07002770 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771}
2772
Michael Wright3dd60e22019-03-27 22:06:44 +00002773void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002774 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002775 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2776 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002777
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002778 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2779 InputTarget target;
2780 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002781 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002782 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2783 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002784 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2785 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002786 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002787 target.setDefaultPointerTransform(target.displayTransform);
2788 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002789 }
2790}
2791
Robert Carrc9bf1d32020-04-13 17:21:08 -07002792/**
2793 * Indicate whether one window handle should be considered as obscuring
2794 * another window handle. We only check a few preconditions. Actually
2795 * checking the bounds is left to the caller.
2796 */
chaviw98318de2021-05-19 16:45:23 -05002797static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2798 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002799 // Compare by token so cloned layers aren't counted
2800 if (haveSameToken(windowHandle, otherHandle)) {
2801 return false;
2802 }
2803 auto info = windowHandle->getInfo();
2804 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002805 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002806 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002807 } else if (otherInfo->alpha == 0 &&
2808 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002809 // Those act as if they were invisible, so we don't need to flag them.
2810 // We do want to potentially flag touchable windows even if they have 0
2811 // opacity, since they can consume touches and alter the effects of the
2812 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002813 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002814 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2815 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002816 } else if (info->ownerUid == otherInfo->ownerUid) {
2817 // If ownerUid is the same we don't generate occlusion events as there
2818 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002819 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002820 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002821 return false;
2822 } else if (otherInfo->displayId != info->displayId) {
2823 return false;
2824 }
2825 return true;
2826}
2827
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002828/**
2829 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2830 * untrusted, one should check:
2831 *
2832 * 1. If result.hasBlockingOcclusion is true.
2833 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2834 * BLOCK_UNTRUSTED.
2835 *
2836 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2837 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2838 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2839 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2840 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2841 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2842 *
2843 * If neither of those is true, then it means the touch can be allowed.
2844 */
2845InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002846 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2847 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002848 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002849 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002850 TouchOcclusionInfo info;
2851 info.hasBlockingOcclusion = false;
2852 info.obscuringOpacity = 0;
2853 info.obscuringUid = -1;
2854 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002855 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002856 if (windowHandle == otherHandle) {
2857 break; // All future windows are below us. Exit early.
2858 }
chaviw98318de2021-05-19 16:45:23 -05002859 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002860 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2861 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002862 if (DEBUG_TOUCH_OCCLUSION) {
2863 info.debugInfo.push_back(
2864 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2865 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002866 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2867 // we perform the checks below to see if the touch can be propagated or not based on the
2868 // window's touch occlusion mode
2869 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2870 info.hasBlockingOcclusion = true;
2871 info.obscuringUid = otherInfo->ownerUid;
2872 info.obscuringPackage = otherInfo->packageName;
2873 break;
2874 }
2875 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2876 uint32_t uid = otherInfo->ownerUid;
2877 float opacity =
2878 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2879 // Given windows A and B:
2880 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2881 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2882 opacityByUid[uid] = opacity;
2883 if (opacity > info.obscuringOpacity) {
2884 info.obscuringOpacity = opacity;
2885 info.obscuringUid = uid;
2886 info.obscuringPackage = otherInfo->packageName;
2887 }
2888 }
2889 }
2890 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002891 if (DEBUG_TOUCH_OCCLUSION) {
2892 info.debugInfo.push_back(
2893 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2894 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002895 return info;
2896}
2897
chaviw98318de2021-05-19 16:45:23 -05002898std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002899 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002900 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2901 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2902 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2903 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002904 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2905 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2906 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2907 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2908 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002909 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002910 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002911}
2912
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002913bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2914 if (occlusionInfo.hasBlockingOcclusion) {
2915 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2916 occlusionInfo.obscuringUid);
2917 return false;
2918 }
2919 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2920 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2921 "%.2f, maximum allowed = %.2f)",
2922 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2923 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2924 return false;
2925 }
2926 return true;
2927}
2928
chaviw98318de2021-05-19 16:45:23 -05002929bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002930 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002932 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2933 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002934 if (windowHandle == otherHandle) {
2935 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002936 }
chaviw98318de2021-05-19 16:45:23 -05002937 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002938 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002939 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940 return true;
2941 }
2942 }
2943 return false;
2944}
2945
chaviw98318de2021-05-19 16:45:23 -05002946bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002947 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002948 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2949 const WindowInfo* windowInfo = windowHandle->getInfo();
2950 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002951 if (windowHandle == otherHandle) {
2952 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002953 }
chaviw98318de2021-05-19 16:45:23 -05002954 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002955 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002956 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002957 return true;
2958 }
2959 }
2960 return false;
2961}
2962
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002963std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002964 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002965 if (applicationHandle != nullptr) {
2966 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002967 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002968 } else {
2969 return applicationHandle->getName();
2970 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002971 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002972 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002974 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002975 }
2976}
2977
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002978void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002979 if (!isUserActivityEvent(eventEntry)) {
2980 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002981 return;
2982 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002983 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002984 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002985 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002986 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002987 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002988 if (DEBUG_DISPATCH_CYCLE) {
2989 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2990 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002991 return;
2992 }
2993 }
2994
2995 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002996 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002997 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002998 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2999 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003000 return;
3001 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003002
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003003 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003004 eventType = USER_ACTIVITY_EVENT_TOUCH;
3005 }
3006 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003007 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003008 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003009 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3010 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003011 return;
3012 }
3013 eventType = USER_ACTIVITY_EVENT_BUTTON;
3014 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003015 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003016 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003017 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003018 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003019 break;
3020 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003021 }
3022
Prabir Pradhancef936d2021-07-21 16:17:52 +00003023 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3024 REQUIRES(mLock) {
3025 scoped_unlock unlock(mLock);
3026 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
3027 };
3028 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029}
3030
3031void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003032 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003033 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003034 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003035 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003036 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003037 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003038 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003039 ATRACE_NAME(message.c_str());
3040 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003041 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003042 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003043 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003044 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003045 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003046 inputTarget.getPointerInfoString().c_str());
3047 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003048
3049 // Skip this event if the connection status is not normal.
3050 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003051 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003052 if (DEBUG_DISPATCH_CYCLE) {
3053 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003054 connection->getInputChannelName().c_str(),
3055 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003057 return;
3058 }
3059
3060 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003061 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003062 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003063 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003064 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003065
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003066 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003067 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003068 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3069 logDispatchStateLocked();
3070 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3071 "target on connection "
3072 << connection->getInputChannelName() << " for "
3073 << originalMotionEntry.getDescription();
3074 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003075 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003076 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3077 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078 if (!splitMotionEntry) {
3079 return; // split event was dropped
3080 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003081 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3082 std::string reason = std::string("reason=pointer cancel on split window");
3083 android_log_event_list(LOGTAG_INPUT_CANCEL)
3084 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3085 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003086 if (DEBUG_FOCUS) {
3087 ALOGD("channel '%s' ~ Split motion event.",
3088 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003089 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003090 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003091 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3092 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003093 return;
3094 }
3095 }
3096
3097 // Not splitting. Enqueue dispatch entries for the event as is.
3098 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3099}
3100
3101void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003102 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003103 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003104 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003105 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003106 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003107 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003108 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003109 ATRACE_NAME(message.c_str());
3110 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003111 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3112 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003113
hongzuo liu95785e22022-09-06 02:51:35 +00003114 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003115
3116 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003117 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003118 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003119 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003120 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003121 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003122 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003123 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003124 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003125 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003126 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003127 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003128 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003129
3130 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003131 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132 startDispatchCycleLocked(currentTime, connection);
3133 }
3134}
3135
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003136void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003137 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003138 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003139 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003140 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003141 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3142 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003143 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003144 ATRACE_NAME(message.c_str());
3145 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003146 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3147 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148 return;
3149 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003150
3151 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3152 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153
3154 // This is a new event.
3155 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003156 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003157 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003159 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3160 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003161 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003163 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003164 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003165 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003166 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003167 dispatchEntry->resolvedAction = keyEntry.action;
3168 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003170 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3171 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003172 if (DEBUG_DISPATCH_CYCLE) {
3173 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3174 "event",
3175 connection->getInputChannelName().c_str());
3176 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003177 return; // skip the inconsistent event
3178 }
3179 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003182 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003183 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003184 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3185 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3186 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3187 static_cast<int32_t>(IdGenerator::Source::OTHER);
3188 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003189 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003190 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003191 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003192 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003193 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003194 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003195 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003196 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003197 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003198 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3199 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003200 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003201 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003202 }
3203 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003204 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3205 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003206 if (DEBUG_DISPATCH_CYCLE) {
3207 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3208 "enter event",
3209 connection->getInputChannelName().c_str());
3210 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003211 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3212 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003213 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3214 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003216 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003217 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3218 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3219 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003220 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003221 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3222 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003223 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003224 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3225 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003226
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003227 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3228 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003229 if (DEBUG_DISPATCH_CYCLE) {
3230 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3231 "event",
3232 connection->getInputChannelName().c_str());
3233 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003234 return; // skip the inconsistent event
3235 }
3236
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003237 dispatchEntry->resolvedEventId =
3238 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3239 ? mIdGenerator.nextId()
3240 : motionEntry.id;
3241 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3242 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3243 ") to MotionEvent(id=0x%" PRIx32 ").",
3244 motionEntry.id, dispatchEntry->resolvedEventId);
3245 ATRACE_NAME(message.c_str());
3246 }
3247
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003248 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3249 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3250 // Skip reporting pointer down outside focus to the policy.
3251 break;
3252 }
3253
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003254 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003255 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003256
3257 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003258 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003259 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003260 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003261 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3262 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003263 break;
3264 }
Chris Yef59a2f42020-10-16 12:55:26 -07003265 case EventEntry::Type::SENSOR: {
3266 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3267 break;
3268 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003269 case EventEntry::Type::CONFIGURATION_CHANGED:
3270 case EventEntry::Type::DEVICE_RESET: {
3271 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003272 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003273 break;
3274 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003275 }
3276
3277 // Remember that we are waiting for this dispatch to complete.
3278 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003279 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003280 }
3281
3282 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003283 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003284 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003285}
3286
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003287/**
3288 * This function is purely for debugging. It helps us understand where the user interaction
3289 * was taking place. For example, if user is touching launcher, we will see a log that user
3290 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3291 * We will see both launcher and wallpaper in that list.
3292 * Once the interaction with a particular set of connections starts, no new logs will be printed
3293 * until the set of interacted connections changes.
3294 *
3295 * The following items are skipped, to reduce the logspam:
3296 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3297 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3298 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3299 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3300 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003301 */
3302void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3303 const std::vector<InputTarget>& targets) {
3304 // Skip ACTION_UP events, and all events other than keys and motions
3305 if (entry.type == EventEntry::Type::KEY) {
3306 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3307 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3308 return;
3309 }
3310 } else if (entry.type == EventEntry::Type::MOTION) {
3311 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3312 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3313 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3314 return;
3315 }
3316 } else {
3317 return; // Not a key or a motion
3318 }
3319
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003320 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003321 std::vector<sp<Connection>> newConnections;
3322 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003323 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003324 continue; // Skip windows that receive ACTION_OUTSIDE
3325 }
3326
3327 sp<IBinder> token = target.inputChannel->getConnectionToken();
3328 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003329 if (connection == nullptr) {
3330 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003331 }
3332 newConnectionTokens.insert(std::move(token));
3333 newConnections.emplace_back(connection);
3334 }
3335 if (newConnectionTokens == mInteractionConnectionTokens) {
3336 return; // no change
3337 }
3338 mInteractionConnectionTokens = newConnectionTokens;
3339
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003340 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003341 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003342 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003343 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003344 std::string message = "Interaction with: " + targetList;
3345 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003346 message += "<none>";
3347 }
3348 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3349}
3350
chaviwfd6d3512019-03-25 13:23:49 -07003351void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003352 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003353 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003354 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3355 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003356 return;
3357 }
3358
Vishnu Nairc519ff72021-01-21 08:23:08 -08003359 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003360 if (focusedToken == token) {
3361 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003362 return;
3363 }
3364
Prabir Pradhancef936d2021-07-21 16:17:52 +00003365 auto command = [this, token]() REQUIRES(mLock) {
3366 scoped_unlock unlock(mLock);
3367 mPolicy->onPointerDownOutsideFocus(token);
3368 };
3369 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003370}
3371
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003372status_t InputDispatcher::publishMotionEvent(Connection& connection,
3373 DispatchEntry& dispatchEntry) const {
3374 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3375 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3376
3377 PointerCoords scaledCoords[MAX_POINTERS];
3378 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3379
3380 // Set the X and Y offset and X and Y scale depending on the input source.
3381 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003382 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003383 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3384 if (globalScaleFactor != 1.0f) {
3385 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3386 scaledCoords[i] = motionEntry.pointerCoords[i];
3387 // Don't apply window scale here since we don't want scale to affect raw
3388 // coordinates. The scale will be sent back to the client and applied
3389 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003390 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003391 }
3392 usingCoords = scaledCoords;
3393 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003394 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003395 // We don't want the dispatch target to know the coordinates
3396 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3397 scaledCoords[i].clear();
3398 }
3399 usingCoords = scaledCoords;
3400 }
3401
3402 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3403
3404 // Publish the motion event.
3405 return connection.inputPublisher
3406 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3407 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3408 std::move(hmac), dispatchEntry.resolvedAction,
3409 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3410 motionEntry.edgeFlags, motionEntry.metaState,
3411 motionEntry.buttonState, motionEntry.classification,
3412 dispatchEntry.transform, motionEntry.xPrecision,
3413 motionEntry.yPrecision, motionEntry.xCursorPosition,
3414 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3415 motionEntry.downTime, motionEntry.eventTime,
3416 motionEntry.pointerCount, motionEntry.pointerProperties,
3417 usingCoords);
3418}
3419
Michael Wrightd02c5b62014-02-10 15:10:22 -08003420void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003421 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003422 if (ATRACE_ENABLED()) {
3423 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003424 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003425 ATRACE_NAME(message.c_str());
3426 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003427 if (DEBUG_DISPATCH_CYCLE) {
3428 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3429 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003431 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003432 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003434 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003435 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436
3437 // Publish the event.
3438 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003439 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3440 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003441 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003442 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3443 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003444 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3445 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3446 << connection->getInputChannelName();
3447 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003449 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003450 status = connection->inputPublisher
3451 .publishKeyEvent(dispatchEntry->seq,
3452 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3453 keyEntry.source, keyEntry.displayId,
3454 std::move(hmac), dispatchEntry->resolvedAction,
3455 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3456 keyEntry.scanCode, keyEntry.metaState,
3457 keyEntry.repeatCount, keyEntry.downTime,
3458 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003459 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003460 }
3461
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003462 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003463 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3464 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3465 << connection->getInputChannelName();
3466 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003467 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003468 break;
3469 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003470
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003471 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003472 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003473 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003474 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003475 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003476 break;
3477 }
3478
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003479 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3480 const TouchModeEntry& touchModeEntry =
3481 static_cast<const TouchModeEntry&>(eventEntry);
3482 status = connection->inputPublisher
3483 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3484 touchModeEntry.inTouchMode);
3485
3486 break;
3487 }
3488
Prabir Pradhan99987712020-11-10 18:43:05 -08003489 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3490 const auto& captureEntry =
3491 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3492 status = connection->inputPublisher
3493 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003494 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003495 break;
3496 }
3497
arthurhungb89ccb02020-12-30 16:19:01 +08003498 case EventEntry::Type::DRAG: {
3499 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3500 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3501 dragEntry.id, dragEntry.x,
3502 dragEntry.y,
3503 dragEntry.isExiting);
3504 break;
3505 }
3506
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003507 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003508 case EventEntry::Type::DEVICE_RESET:
3509 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003510 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003511 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003512 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003513 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514 }
3515
3516 // Check the result.
3517 if (status) {
3518 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003519 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003521 "This is unexpected because the wait queue is empty, so the pipe "
3522 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003523 "event to it, status=%s(%d)",
3524 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3525 status);
Harry Cutts33476232023-01-30 19:57:29 +00003526 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 } else {
3528 // Pipe is full and we are waiting for the app to finish process some events
3529 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003530 if (DEBUG_DISPATCH_CYCLE) {
3531 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3532 "waiting for the application to catch up",
3533 connection->getInputChannelName().c_str());
3534 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535 }
3536 } else {
3537 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003538 "status=%s(%d)",
3539 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3540 status);
Harry Cutts33476232023-01-30 19:57:29 +00003541 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542 }
3543 return;
3544 }
3545
3546 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003547 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3548 connection->outboundQueue.end(),
3549 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003550 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003551 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003552 if (connection->responsive) {
3553 mAnrTracker.insert(dispatchEntry->timeoutTime,
3554 connection->inputChannel->getConnectionToken());
3555 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003556 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003557 }
3558}
3559
chaviw09c8d2d2020-08-24 15:48:26 -07003560std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3561 size_t size;
3562 switch (event.type) {
3563 case VerifiedInputEvent::Type::KEY: {
3564 size = sizeof(VerifiedKeyEvent);
3565 break;
3566 }
3567 case VerifiedInputEvent::Type::MOTION: {
3568 size = sizeof(VerifiedMotionEvent);
3569 break;
3570 }
3571 }
3572 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3573 return mHmacKeyManager.sign(start, size);
3574}
3575
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003576const std::array<uint8_t, 32> InputDispatcher::getSignature(
3577 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003578 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3579 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003580 // Only sign events up and down events as the purely move events
3581 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003582 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003583 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003584
3585 VerifiedMotionEvent verifiedEvent =
3586 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3587 verifiedEvent.actionMasked = actionMasked;
3588 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3589 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003590}
3591
3592const std::array<uint8_t, 32> InputDispatcher::getSignature(
3593 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3594 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3595 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3596 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003597 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003598}
3599
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003601 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003602 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003603 if (DEBUG_DISPATCH_CYCLE) {
3604 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3605 connection->getInputChannelName().c_str(), seq, toString(handled));
3606 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003607
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003608 if (connection->status == Connection::Status::BROKEN ||
3609 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 return;
3611 }
3612
3613 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003614 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3615 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3616 };
3617 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618}
3619
3620void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003621 const sp<Connection>& connection,
3622 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003623 if (DEBUG_DISPATCH_CYCLE) {
3624 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3625 connection->getInputChannelName().c_str(), toString(notify));
3626 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003627
3628 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003629 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003630 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003631 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003632 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633
3634 // The connection appears to be unrecoverably broken.
3635 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003636 if (connection->status == Connection::Status::NORMAL) {
3637 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638
3639 if (notify) {
3640 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003641 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3642 connection->getInputChannelName().c_str());
3643
3644 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003645 scoped_unlock unlock(mLock);
3646 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3647 };
3648 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649 }
3650 }
3651}
3652
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003653void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3654 while (!queue.empty()) {
3655 DispatchEntry* dispatchEntry = queue.front();
3656 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003657 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658 }
3659}
3660
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003661void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003663 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664 }
3665 delete dispatchEntry;
3666}
3667
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003668int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3669 std::scoped_lock _l(mLock);
3670 sp<Connection> connection = getConnectionLocked(connectionToken);
3671 if (connection == nullptr) {
3672 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3673 connectionToken.get(), events);
3674 return 0; // remove the callback
3675 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003676
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003677 bool notify;
3678 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3679 if (!(events & ALOOPER_EVENT_INPUT)) {
3680 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3681 "events=0x%x",
3682 connection->getInputChannelName().c_str(), events);
3683 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684 }
3685
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003686 nsecs_t currentTime = now();
3687 bool gotOne = false;
3688 status_t status = OK;
3689 for (;;) {
3690 Result<InputPublisher::ConsumerResponse> result =
3691 connection->inputPublisher.receiveConsumerResponse();
3692 if (!result.ok()) {
3693 status = result.error().code();
3694 break;
3695 }
3696
3697 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3698 const InputPublisher::Finished& finish =
3699 std::get<InputPublisher::Finished>(*result);
3700 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3701 finish.consumeTime);
3702 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003703 if (shouldReportMetricsForConnection(*connection)) {
3704 const InputPublisher::Timeline& timeline =
3705 std::get<InputPublisher::Timeline>(*result);
3706 mLatencyTracker
3707 .trackGraphicsLatency(timeline.inputEventId,
3708 connection->inputChannel->getConnectionToken(),
3709 std::move(timeline.graphicsTimeline));
3710 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003711 }
3712 gotOne = true;
3713 }
3714 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003715 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003716 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003717 return 1;
3718 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003719 }
3720
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003721 notify = status != DEAD_OBJECT || !connection->monitor;
3722 if (notify) {
3723 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3724 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3725 status);
3726 }
3727 } else {
3728 // Monitor channels are never explicitly unregistered.
3729 // We do it automatically when the remote endpoint is closed so don't warn about them.
3730 const bool stillHaveWindowHandle =
3731 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3732 notify = !connection->monitor && stillHaveWindowHandle;
3733 if (notify) {
3734 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3735 connection->getInputChannelName().c_str(), events);
3736 }
3737 }
3738
3739 // Remove the channel.
3740 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3741 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742}
3743
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003744void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003745 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003746 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003747 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003748 }
3749}
3750
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003751void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003752 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003753 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003754 for (const Monitor& monitor : monitors) {
3755 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003756 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003757 }
3758}
3759
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003761 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003762 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003763 if (connection == nullptr) {
3764 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003766
3767 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003768}
3769
3770void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3771 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003772 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773 return;
3774 }
3775
3776 nsecs_t currentTime = now();
3777
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003778 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003779 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003781 if (cancelationEvents.empty()) {
3782 return;
3783 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003784 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3785 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003786 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003787 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003788 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003789 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003790
Arthur Hungb3307ee2021-10-14 10:57:37 +00003791 std::string reason = std::string("reason=").append(options.reason);
3792 android_log_event_list(LOGTAG_INPUT_CANCEL)
3793 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3794
Svet Ganov5d3bc372020-01-26 23:11:07 -08003795 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003796 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003797 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3798 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003799 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003800 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003801 target.globalScaleFactor = windowInfo->globalScaleFactor;
3802 }
3803 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003804 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003805
hongzuo liu95785e22022-09-06 02:51:35 +00003806 const bool wasEmpty = connection->outboundQueue.empty();
3807
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003808 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003809 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003810 switch (cancelationEventEntry->type) {
3811 case EventEntry::Type::KEY: {
3812 logOutboundKeyDetails("cancel - ",
3813 static_cast<const KeyEntry&>(*cancelationEventEntry));
3814 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003816 case EventEntry::Type::MOTION: {
3817 logOutboundMotionDetails("cancel - ",
3818 static_cast<const MotionEntry&>(*cancelationEventEntry));
3819 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003821 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003822 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003823 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3824 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003825 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003826 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003827 break;
3828 }
3829 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003830 case EventEntry::Type::DEVICE_RESET:
3831 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003832 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003833 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003834 break;
3835 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003836 }
3837
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003838 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003839 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003840 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003841
hongzuo liu95785e22022-09-06 02:51:35 +00003842 // If the outbound queue was previously empty, start the dispatch cycle going.
3843 if (wasEmpty && !connection->outboundQueue.empty()) {
3844 startDispatchCycleLocked(currentTime, connection);
3845 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003846}
3847
Svet Ganov5d3bc372020-01-26 23:11:07 -08003848void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Arthur Hungc539dbb2022-12-08 07:45:36 +00003849 const nsecs_t downTime, const sp<Connection>& connection,
3850 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003851 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003852 return;
3853 }
3854
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003855 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003856 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003857
3858 if (downEvents.empty()) {
3859 return;
3860 }
3861
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003862 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003863 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3864 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003865 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003866
3867 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003868 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003869 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3870 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003871 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003872 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003873 target.globalScaleFactor = windowInfo->globalScaleFactor;
3874 }
3875 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00003876 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003877
hongzuo liu95785e22022-09-06 02:51:35 +00003878 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003879 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003880 switch (downEventEntry->type) {
3881 case EventEntry::Type::MOTION: {
3882 logOutboundMotionDetails("down - ",
3883 static_cast<const MotionEntry&>(*downEventEntry));
3884 break;
3885 }
3886
3887 case EventEntry::Type::KEY:
3888 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003889 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003890 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003891 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003892 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003893 case EventEntry::Type::SENSOR:
3894 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003895 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003896 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003897 break;
3898 }
3899 }
3900
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003901 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003902 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003903 }
3904
hongzuo liu95785e22022-09-06 02:51:35 +00003905 // If the outbound queue was previously empty, start the dispatch cycle going.
3906 if (wasEmpty && !connection->outboundQueue.empty()) {
3907 startDispatchCycleLocked(downTime, connection);
3908 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003909}
3910
Arthur Hungc539dbb2022-12-08 07:45:36 +00003911void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
3912 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
3913 if (windowHandle != nullptr) {
3914 sp<Connection> wallpaperConnection = getConnectionLocked(windowHandle->getToken());
3915 if (wallpaperConnection != nullptr) {
3916 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
3917 }
3918 }
3919}
3920
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003921std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003922 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
3923 nsecs_t splitDownTime) {
3924 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925
3926 uint32_t splitPointerIndexMap[MAX_POINTERS];
3927 PointerProperties splitPointerProperties[MAX_POINTERS];
3928 PointerCoords splitPointerCoords[MAX_POINTERS];
3929
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003930 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931 uint32_t splitPointerCount = 0;
3932
3933 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003934 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003936 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003938 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3940 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3941 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003942 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943 splitPointerCount += 1;
3944 }
3945 }
3946
3947 if (splitPointerCount != pointerIds.count()) {
3948 // This is bad. We are missing some of the pointers that we expected to deliver.
3949 // Most likely this indicates that we received an ACTION_MOVE events that has
3950 // different pointer ids than we expected based on the previous ACTION_DOWN
3951 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3952 // in this way.
3953 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003954 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003955 "a broken sequence of pointer ids from the input device: %s",
3956 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07003957 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003958 }
3959
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003960 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003962 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3963 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3965 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003966 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003968 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 if (pointerIds.count() == 1) {
3970 // The first/last pointer went down/up.
3971 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003972 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003973 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3974 ? AMOTION_EVENT_ACTION_CANCEL
3975 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976 } else {
3977 // A secondary pointer went down/up.
3978 uint32_t splitPointerIndex = 0;
3979 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3980 splitPointerIndex += 1;
3981 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003982 action = maskedAction |
3983 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984 }
3985 } else {
3986 // An unrelated pointer changed.
3987 action = AMOTION_EVENT_ACTION_MOVE;
3988 }
3989 }
3990
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003991 if (action == AMOTION_EVENT_ACTION_DOWN) {
3992 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3993 "Split motion event has mismatching downTime and eventTime for "
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08003994 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
3995 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003996 }
3997
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003998 int32_t newId = mIdGenerator.nextId();
3999 if (ATRACE_ENABLED()) {
4000 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
4001 ") to MotionEvent(id=0x%" PRIx32 ").",
4002 originalMotionEntry.id, newId);
4003 ATRACE_NAME(message.c_str());
4004 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004005 std::unique_ptr<MotionEntry> splitMotionEntry =
4006 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4007 originalMotionEntry.deviceId, originalMotionEntry.source,
4008 originalMotionEntry.displayId,
4009 originalMotionEntry.policyFlags, action,
4010 originalMotionEntry.actionButton,
4011 originalMotionEntry.flags, originalMotionEntry.metaState,
4012 originalMotionEntry.buttonState,
4013 originalMotionEntry.classification,
4014 originalMotionEntry.edgeFlags,
4015 originalMotionEntry.xPrecision,
4016 originalMotionEntry.yPrecision,
4017 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004018 originalMotionEntry.yCursorPosition, splitDownTime,
4019 splitPointerCount, splitPointerProperties,
4020 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004022 if (originalMotionEntry.injectionState) {
4023 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004024 splitMotionEntry->injectionState->refCount += 1;
4025 }
4026
4027 return splitMotionEntry;
4028}
4029
4030void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004031 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004032 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
4033 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004034
Antonio Kantekf16f2832021-09-28 04:39:20 +00004035 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004036 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004037 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004038
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004039 std::unique_ptr<ConfigurationChangedEntry> newEntry =
4040 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
4041 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004042 } // release lock
4043
4044 if (needWake) {
4045 mLooper->wake();
4046 }
4047}
4048
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004049/**
4050 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004051 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4052 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4053 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4054 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4055 * potentially handle the back key presses.
4056 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4057 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004058 */
4059void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004060 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004061 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4062 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004063 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004064 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004065 }
4066 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004067 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004068 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004069 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004070 keyCode = newKeyCode;
4071 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4072 }
4073 } else if (action == AKEY_EVENT_ACTION_UP) {
4074 // In order to maintain a consistent stream of up and down events, check to see if the key
4075 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4076 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004077 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004078 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004079 auto replacementIt = mReplacedKeys.find(replacement);
4080 if (replacementIt != mReplacedKeys.end()) {
4081 keyCode = replacementIt->second;
4082 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004083 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4084 }
4085 }
4086}
4087
Michael Wrightd02c5b62014-02-10 15:10:22 -08004088void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004089 ALOGD_IF(debugInboundEventDetails(),
4090 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4091 ", deviceId=%d, source=%s, displayId=%" PRId32
4092 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4093 "downTime=%" PRId64,
4094 args->id, args->eventTime, args->deviceId,
4095 inputEventSourceToString(args->source).c_str(), args->displayId, args->policyFlags,
4096 KeyEvent::actionToString(args->action), args->flags, KeyEvent::getLabel(args->keyCode),
4097 args->scanCode, args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098 if (!validateKeyEvent(args->action)) {
4099 return;
4100 }
4101
4102 uint32_t policyFlags = args->policyFlags;
4103 int32_t flags = args->flags;
4104 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004105 // InputDispatcher tracks and generates key repeats on behalf of
4106 // whatever notifies it, so repeatCount should always be set to 0
4107 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004108 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4109 policyFlags |= POLICY_FLAG_VIRTUAL;
4110 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4111 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004112 if (policyFlags & POLICY_FLAG_FUNCTION) {
4113 metaState |= AMETA_FUNCTION_ON;
4114 }
4115
4116 policyFlags |= POLICY_FLAG_TRUSTED;
4117
Michael Wright78f24442014-08-06 15:55:28 -07004118 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004119 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004120
Michael Wrightd02c5b62014-02-10 15:10:22 -08004121 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004122 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08004123 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
4124 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125
Michael Wright2b3c3302018-03-02 17:19:13 +00004126 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004128 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4129 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004130 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004131 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004132
Antonio Kantekf16f2832021-09-28 04:39:20 +00004133 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134 { // acquire lock
4135 mLock.lock();
4136
4137 if (shouldSendKeyToInputFilterLocked(args)) {
4138 mLock.unlock();
4139
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004140 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4142 return; // event was consumed by the filter
4143 }
4144
4145 mLock.lock();
4146 }
4147
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004148 std::unique_ptr<KeyEntry> newEntry =
4149 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4150 args->displayId, policyFlags, args->action, flags,
4151 keyCode, args->scanCode, metaState, repeatCount,
4152 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004154 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155 mLock.unlock();
4156 } // release lock
4157
4158 if (needWake) {
4159 mLooper->wake();
4160 }
4161}
4162
4163bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4164 return mInputFilterEnabled;
4165}
4166
4167void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004168 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004169 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004170 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004171 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004172 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4173 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhan96282b02023-02-24 22:36:17 +00004174 args->id, args->eventTime, args->deviceId,
4175 inputEventSourceToString(args->source).c_str(), args->displayId, args->policyFlags,
4176 MotionEvent::actionToString(args->action).c_str(), args->actionButton, args->flags,
4177 args->metaState, args->buttonState, args->edgeFlags, args->xPrecision,
4178 args->yPrecision, args->xCursorPosition, args->yCursorPosition, args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004179 for (uint32_t i = 0; i < args->pointerCount; i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004180 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4181 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
4182 i, args->pointerProperties[i].id,
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07004183 ftl::enum_string(args->pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004184 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4185 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4186 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4187 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4188 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4189 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4190 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4191 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4192 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4193 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194 }
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004195
4196 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4197 args->pointerProperties)) {
4198 LOG(ERROR) << "Invalid event: " << args->dump();
4199 return;
4200 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201
4202 uint32_t policyFlags = args->policyFlags;
4203 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004204
4205 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004206 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004207 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4208 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004209 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004210 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211
Antonio Kantekf16f2832021-09-28 04:39:20 +00004212 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213 { // acquire lock
4214 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004215 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4216 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4217 // complete the processing of the current stroke.
4218 const auto touchStateIt = mTouchStatesByDisplay.find(args->displayId);
4219 if (touchStateIt != mTouchStatesByDisplay.end()) {
4220 const TouchState& touchState = touchStateIt->second;
4221 if (touchState.deviceId == args->deviceId && touchState.isDown()) {
4222 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4223 }
4224 }
4225 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226
4227 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004228 ui::Transform displayTransform;
4229 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4230 displayTransform = it->second.transform;
4231 }
4232
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233 mLock.unlock();
4234
4235 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004236 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4237 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004238 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004239 displayTransform, args->xPrecision, args->yPrecision,
4240 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004241 args->downTime, args->eventTime, args->pointerCount,
4242 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243
4244 policyFlags |= POLICY_FLAG_FILTERED;
4245 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4246 return; // event was consumed by the filter
4247 }
4248
4249 mLock.lock();
4250 }
4251
4252 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004253 std::unique_ptr<MotionEntry> newEntry =
4254 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4255 args->source, args->displayId, policyFlags,
4256 args->action, args->actionButton, args->flags,
4257 args->metaState, args->buttonState,
4258 args->classification, args->edgeFlags,
4259 args->xPrecision, args->yPrecision,
4260 args->xCursorPosition, args->yCursorPosition,
4261 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004262 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004264 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4265 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4266 !mInputFilterEnabled) {
4267 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4268 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4269 }
4270
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004271 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 mLock.unlock();
4273 } // release lock
4274
4275 if (needWake) {
4276 mLooper->wake();
4277 }
4278}
4279
Chris Yef59a2f42020-10-16 12:55:26 -07004280void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004281 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004282 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4283 " sensorType=%s",
4284 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004285 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004286 }
Chris Yef59a2f42020-10-16 12:55:26 -07004287
Antonio Kantekf16f2832021-09-28 04:39:20 +00004288 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004289 { // acquire lock
4290 mLock.lock();
4291
4292 // Just enqueue a new sensor event.
4293 std::unique_ptr<SensorEntry> newEntry =
4294 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
Harry Cutts33476232023-01-30 19:57:29 +00004295 args->source, /* policyFlags=*/0, args->hwTimestamp,
Chris Yef59a2f42020-10-16 12:55:26 -07004296 args->sensorType, args->accuracy,
4297 args->accuracyChanged, args->values);
4298
4299 needWake = enqueueInboundEventLocked(std::move(newEntry));
4300 mLock.unlock();
4301 } // release lock
4302
4303 if (needWake) {
4304 mLooper->wake();
4305 }
4306}
4307
Chris Yefb552902021-02-03 17:18:37 -08004308void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004309 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004310 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4311 args->deviceId, args->isOn);
4312 }
Chris Yefb552902021-02-03 17:18:37 -08004313 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4314}
4315
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004317 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318}
4319
4320void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004321 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004322 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4323 "switchMask=0x%08x",
4324 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4325 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326
4327 uint32_t policyFlags = args->policyFlags;
4328 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004329 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330}
4331
4332void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004333 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004334 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4335 args->deviceId);
4336 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004337
Antonio Kantekf16f2832021-09-28 04:39:20 +00004338 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004340 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004342 std::unique_ptr<DeviceResetEntry> newEntry =
4343 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4344 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004345 } // release lock
4346
4347 if (needWake) {
4348 mLooper->wake();
4349 }
4350}
4351
Prabir Pradhan7e186182020-11-10 13:56:45 -08004352void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004353 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004354 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004355 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004356 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004357
Antonio Kantekf16f2832021-09-28 04:39:20 +00004358 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004359 { // acquire lock
4360 std::scoped_lock _l(mLock);
4361 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004362 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004363 needWake = enqueueInboundEventLocked(std::move(entry));
4364 } // release lock
4365
4366 if (needWake) {
4367 mLooper->wake();
4368 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004369}
4370
Prabir Pradhan5735a322022-04-11 17:23:34 +00004371InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4372 std::optional<int32_t> targetUid,
4373 InputEventInjectionSync syncMode,
4374 std::chrono::milliseconds timeout,
4375 uint32_t policyFlags) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004376 if (debugInboundEventDetails()) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004377 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4378 "policyFlags=0x%08x",
4379 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4380 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004381 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004382 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383
Prabir Pradhan5735a322022-04-11 17:23:34 +00004384 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004386 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004387 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4388 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4389 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4390 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4391 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004392 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004393 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004394 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004395 }
4396
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004397 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004398 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004399 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004400 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4401 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004402 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004403 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004404 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004406 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004407 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4408 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4409 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004410 int32_t keyCode = incomingKey.getKeyCode();
4411 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004412 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004413 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004414 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004415 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004416 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4417 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4418 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004419
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004420 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4421 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004422 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004423
4424 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4425 android::base::Timer t;
4426 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4427 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4428 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4429 std::to_string(t.duration().count()).c_str());
4430 }
4431 }
4432
4433 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004434 std::unique_ptr<KeyEntry> injectedEntry =
4435 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004436 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004437 incomingKey.getDisplayId(), policyFlags, action,
4438 flags, keyCode, incomingKey.getScanCode(), metaState,
4439 incomingKey.getRepeatCount(),
4440 incomingKey.getDownTime());
4441 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004442 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004443 }
4444
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004445 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004446 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004447 const int32_t action = motionEvent.getAction();
4448 const bool isPointerEvent =
4449 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4450 // If a pointer event has no displayId specified, inject it to the default display.
4451 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4452 ? ADISPLAY_ID_DEFAULT
4453 : event->getDisplayId();
4454 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004455 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004456 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004457 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004458 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004459 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004460 }
4461
4462 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004463 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004464 android::base::Timer t;
4465 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4466 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4467 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4468 std::to_string(t.duration().count()).c_str());
4469 }
4470 }
4471
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004472 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4473 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4474 }
4475
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004476 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004477 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4478 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004479 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004480 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4481 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004482 displayId, policyFlags, action, actionButton,
4483 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004484 motionEvent.getButtonState(),
4485 motionEvent.getClassification(),
4486 motionEvent.getEdgeFlags(),
4487 motionEvent.getXPrecision(),
4488 motionEvent.getYPrecision(),
4489 motionEvent.getRawXCursorPosition(),
4490 motionEvent.getRawYCursorPosition(),
4491 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004492 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004493 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004494 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004495 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004496 sampleEventTimes += 1;
4497 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004498 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004499 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4500 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004501 displayId, policyFlags, action, actionButton,
4502 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004503 motionEvent.getButtonState(),
4504 motionEvent.getClassification(),
4505 motionEvent.getEdgeFlags(),
4506 motionEvent.getXPrecision(),
4507 motionEvent.getYPrecision(),
4508 motionEvent.getRawXCursorPosition(),
4509 motionEvent.getRawYCursorPosition(),
4510 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004511 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004512 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004513 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4514 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004515 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004516 }
4517 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004518 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004520 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004521 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004522 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523 }
4524
Prabir Pradhan5735a322022-04-11 17:23:34 +00004525 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004526 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004527 injectionState->injectionIsAsync = true;
4528 }
4529
4530 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004531 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004532
4533 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004534 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004535 if (DEBUG_INJECTION) {
4536 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4537 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004538 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004539 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004540 }
4541
4542 mLock.unlock();
4543
4544 if (needWake) {
4545 mLooper->wake();
4546 }
4547
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004548 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004550 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004551
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004552 if (syncMode == InputEventInjectionSync::NONE) {
4553 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554 } else {
4555 for (;;) {
4556 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004557 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004558 break;
4559 }
4560
4561 nsecs_t remainingTimeout = endTime - now();
4562 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004563 if (DEBUG_INJECTION) {
4564 ALOGD("injectInputEvent - Timed out waiting for injection result "
4565 "to become available.");
4566 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004567 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004568 break;
4569 }
4570
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004571 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572 }
4573
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004574 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4575 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004576 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004577 if (DEBUG_INJECTION) {
4578 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4579 injectionState->pendingForegroundDispatches);
4580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581 nsecs_t remainingTimeout = endTime - now();
4582 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004583 if (DEBUG_INJECTION) {
4584 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4585 "dispatches to finish.");
4586 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004587 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588 break;
4589 }
4590
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004591 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004592 }
4593 }
4594 }
4595
4596 injectionState->release();
4597 } // release lock
4598
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004599 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004600 LOG(DEBUG) << "injectInputEvent - Finished with result "
4601 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603
4604 return injectionResult;
4605}
4606
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004607std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004608 std::array<uint8_t, 32> calculatedHmac;
4609 std::unique_ptr<VerifiedInputEvent> result;
4610 switch (event.getType()) {
4611 case AINPUT_EVENT_TYPE_KEY: {
4612 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4613 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4614 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004615 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004616 break;
4617 }
4618 case AINPUT_EVENT_TYPE_MOTION: {
4619 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4620 VerifiedMotionEvent verifiedMotionEvent =
4621 verifiedMotionEventFromMotionEvent(motionEvent);
4622 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004623 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004624 break;
4625 }
4626 default: {
4627 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4628 return nullptr;
4629 }
4630 }
4631 if (calculatedHmac == INVALID_HMAC) {
4632 return nullptr;
4633 }
tyiu1573a672023-02-21 22:38:32 +00004634 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004635 return nullptr;
4636 }
4637 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004638}
4639
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004640void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004641 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004642 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004643 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004644 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004645 LOG(DEBUG) << "Setting input event injection result to "
4646 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004647 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004648
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004649 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650 // Log the outcome since the injector did not wait for the injection result.
4651 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004652 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004653 ALOGV("Asynchronous input event injection succeeded.");
4654 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004655 case InputEventInjectionResult::TARGET_MISMATCH:
4656 ALOGV("Asynchronous input event injection target mismatch.");
4657 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004658 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004659 ALOGW("Asynchronous input event injection failed.");
4660 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004661 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004662 ALOGW("Asynchronous input event injection timed out.");
4663 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004664 case InputEventInjectionResult::PENDING:
4665 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4666 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004667 }
4668 }
4669
4670 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004671 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004672 }
4673}
4674
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004675void InputDispatcher::transformMotionEntryForInjectionLocked(
4676 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004677 // Input injection works in the logical display coordinate space, but the input pipeline works
4678 // display space, so we need to transform the injected events accordingly.
4679 const auto it = mDisplayInfos.find(entry.displayId);
4680 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004681 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004682
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004683 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4684 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4685 const vec2 cursor =
4686 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4687 {entry.xCursorPosition, entry.yCursorPosition});
4688 entry.xCursorPosition = cursor.x;
4689 entry.yCursorPosition = cursor.y;
4690 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004691 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004692 entry.pointerCoords[i] =
4693 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4694 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004695 }
4696}
4697
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004698void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4699 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004700 if (injectionState) {
4701 injectionState->pendingForegroundDispatches += 1;
4702 }
4703}
4704
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004705void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4706 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004707 if (injectionState) {
4708 injectionState->pendingForegroundDispatches -= 1;
4709
4710 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004711 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004712 }
4713 }
4714}
4715
chaviw98318de2021-05-19 16:45:23 -05004716const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004717 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004718 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004719 auto it = mWindowHandlesByDisplay.find(displayId);
4720 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004721}
4722
chaviw98318de2021-05-19 16:45:23 -05004723sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004724 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004725 if (windowHandleToken == nullptr) {
4726 return nullptr;
4727 }
4728
Arthur Hungb92218b2018-08-14 12:00:21 +08004729 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004730 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4731 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004732 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004733 return windowHandle;
4734 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004735 }
4736 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004737 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004738}
4739
chaviw98318de2021-05-19 16:45:23 -05004740sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4741 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004742 if (windowHandleToken == nullptr) {
4743 return nullptr;
4744 }
4745
chaviw98318de2021-05-19 16:45:23 -05004746 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004747 if (windowHandle->getToken() == windowHandleToken) {
4748 return windowHandle;
4749 }
4750 }
4751 return nullptr;
4752}
4753
chaviw98318de2021-05-19 16:45:23 -05004754sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4755 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004756 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004757 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4758 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004759 if (handle->getId() == windowHandle->getId() &&
4760 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004761 if (windowHandle->getInfo()->displayId != it.first) {
4762 ALOGE("Found window %s in display %" PRId32
4763 ", but it should belong to display %" PRId32,
4764 windowHandle->getName().c_str(), it.first,
4765 windowHandle->getInfo()->displayId);
4766 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004767 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004768 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004769 }
4770 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004771 return nullptr;
4772}
4773
chaviw98318de2021-05-19 16:45:23 -05004774sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004775 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4776 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004777}
4778
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004779ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4780 auto displayInfoIt = mDisplayInfos.find(displayId);
4781 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4782 : kIdentityTransform;
4783}
4784
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004785bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4786 const MotionEntry& motionEntry) const {
4787 const WindowInfo& info = *window->getInfo();
4788
4789 // Skip spy window targets that are not valid for targeted injection.
4790 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004791 return false;
4792 }
4793
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004794 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4795 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4796 return false;
4797 }
4798
4799 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4800 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4801 window->getName().c_str());
4802 return false;
4803 }
4804
4805 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004806 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004807 ALOGW("Not sending touch to %s because there's no corresponding connection",
4808 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004809 return false;
4810 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004811
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004812 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004813 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004814 return false;
4815 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004816
4817 // Drop events that can't be trusted due to occlusion
4818 const auto [x, y] = resolveTouchedPosition(motionEntry);
4819 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4820 if (!isTouchTrustedLocked(occlusionInfo)) {
4821 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004822 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004823 for (const auto& log : occlusionInfo.debugInfo) {
4824 ALOGD("%s", log.c_str());
4825 }
4826 }
4827 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4828 occlusionInfo.obscuringUid);
4829 return false;
4830 }
4831
4832 // Drop touch events if requested by input feature
4833 if (shouldDropInput(motionEntry, window)) {
4834 return false;
4835 }
4836
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004837 return true;
4838}
4839
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004840std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4841 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004842 auto connectionIt = mConnectionsByToken.find(token);
4843 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004844 return nullptr;
4845 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004846 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004847}
4848
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004849void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004850 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4851 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004852 // Remove all handles on a display if there are no windows left.
4853 mWindowHandlesByDisplay.erase(displayId);
4854 return;
4855 }
4856
4857 // Since we compare the pointer of input window handles across window updates, we need
4858 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004859 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4860 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4861 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004862 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004863 }
4864
chaviw98318de2021-05-19 16:45:23 -05004865 std::vector<sp<WindowInfoHandle>> newHandles;
4866 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004867 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004868 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004869 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004870 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004871 const bool canReceiveInput =
4872 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4873 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004874 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004875 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004876 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004877 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004878 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004879 }
4880
4881 if (info->displayId != displayId) {
4882 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4883 handle->getName().c_str(), displayId, info->displayId);
4884 continue;
4885 }
4886
Robert Carredd13602020-04-13 17:24:34 -07004887 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4888 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004889 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004890 oldHandle->updateFrom(handle);
4891 newHandles.push_back(oldHandle);
4892 } else {
4893 newHandles.push_back(handle);
4894 }
4895 }
4896
4897 // Insert or replace
4898 mWindowHandlesByDisplay[displayId] = newHandles;
4899}
4900
Arthur Hung72d8dc32020-03-28 00:48:39 +00004901void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004902 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004903 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004904 { // acquire lock
4905 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004906 for (const auto& [displayId, handles] : handlesPerDisplay) {
4907 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004908 }
4909 }
4910 // Wake up poll loop since it may need to make new input dispatching choices.
4911 mLooper->wake();
4912}
4913
Arthur Hungb92218b2018-08-14 12:00:21 +08004914/**
4915 * Called from InputManagerService, update window handle list by displayId that can receive input.
4916 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4917 * If set an empty list, remove all handles from the specific display.
4918 * For focused handle, check if need to change and send a cancel event to previous one.
4919 * For removed handle, check if need to send a cancel event if already in touch.
4920 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004921void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004922 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004923 if (DEBUG_FOCUS) {
4924 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004925 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004926 windowList += iwh->getName() + " ";
4927 }
4928 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4929 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930
Prabir Pradhand65552b2021-10-07 11:23:50 -07004931 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004932 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004933 const WindowInfo& info = *window->getInfo();
4934
4935 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004936 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004937 if (noInputWindow && window->getToken() != nullptr) {
4938 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4939 window->getName().c_str());
4940 window->releaseChannel();
4941 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004942
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004943 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004944 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4945 !info.inputConfig.test(
4946 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004947 "%s has feature SPY, but is not a trusted overlay.",
4948 window->getName().c_str());
4949
Prabir Pradhand65552b2021-10-07 11:23:50 -07004950 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004951 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4952 !info.inputConfig.test(
4953 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004954 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4955 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004956 }
4957
Arthur Hung72d8dc32020-03-28 00:48:39 +00004958 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004959 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004960
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004961 // Save the old windows' orientation by ID before it gets updated.
4962 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004963 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004964 oldWindowOrientations.emplace(handle->getId(),
4965 handle->getInfo()->transform.getOrientation());
4966 }
4967
chaviw98318de2021-05-19 16:45:23 -05004968 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004969
chaviw98318de2021-05-19 16:45:23 -05004970 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004971
Vishnu Nairc519ff72021-01-21 08:23:08 -08004972 std::optional<FocusResolver::FocusChanges> changes =
4973 mFocusResolver.setInputWindows(displayId, windowHandles);
4974 if (changes) {
4975 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004976 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004977
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004978 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4979 mTouchStatesByDisplay.find(displayId);
4980 if (stateIt != mTouchStatesByDisplay.end()) {
4981 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004982 for (size_t i = 0; i < state.windows.size();) {
4983 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004984 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004985 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004986 ALOGD("Touched window was removed: %s in display %" PRId32,
4987 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004988 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004989 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004990 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4991 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004992 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00004993 "touched window was removed");
4994 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004995 // Since we are about to drop the touch, cancel the events for the wallpaper as
4996 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004997 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004998 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4999 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005000 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005001 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005002 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005003 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005004 state.windows.erase(state.windows.begin() + i);
5005 } else {
5006 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005007 }
5008 }
arthurhungb89ccb02020-12-30 16:19:01 +08005009
arthurhung6d4bed92021-03-17 11:59:33 +08005010 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005011 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005012 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005013 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005014 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005015 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5016 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005017 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005018 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005019 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005020
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005021 // Determine if the orientation of any of the input windows have changed, and cancel all
5022 // pointer events if necessary.
5023 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
5024 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
5025 if (newWindowHandle != nullptr &&
5026 newWindowHandle->getInfo()->transform.getOrientation() !=
5027 oldWindowOrientations[oldWindowHandle->getId()]) {
5028 std::shared_ptr<InputChannel> inputChannel =
5029 getInputChannelLocked(newWindowHandle->getToken());
5030 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005031 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005032 "touched window's orientation changed");
5033 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005034 }
5035 }
5036 }
5037
Arthur Hung72d8dc32020-03-28 00:48:39 +00005038 // Release information for windows that are no longer present.
5039 // This ensures that unused input channels are released promptly.
5040 // Otherwise, they might stick around until the window handle is destroyed
5041 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005042 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005043 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005044 if (DEBUG_FOCUS) {
5045 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005046 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005047 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005048 }
chaviw291d88a2019-02-14 10:33:58 -08005049 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005050}
5051
5052void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005053 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005054 if (DEBUG_FOCUS) {
5055 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5056 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5057 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005058 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005059 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005060 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005061 } // release lock
5062
5063 // Wake up poll loop since it may need to make new input dispatching choices.
5064 mLooper->wake();
5065}
5066
Vishnu Nair599f1412021-06-21 10:39:58 -07005067void InputDispatcher::setFocusedApplicationLocked(
5068 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5069 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5070 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5071
5072 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5073 return; // This application is already focused. No need to wake up or change anything.
5074 }
5075
5076 // Set the new application handle.
5077 if (inputApplicationHandle != nullptr) {
5078 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5079 } else {
5080 mFocusedApplicationHandlesByDisplay.erase(displayId);
5081 }
5082
5083 // No matter what the old focused application was, stop waiting on it because it is
5084 // no longer focused.
5085 resetNoFocusedWindowTimeoutLocked();
5086}
5087
Tiger Huang721e26f2018-07-24 22:26:19 +08005088/**
5089 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5090 * the display not specified.
5091 *
5092 * We track any unreleased events for each window. If a window loses the ability to receive the
5093 * released event, we will send a cancel event to it. So when the focused display is changed, we
5094 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5095 * display. The display-specified events won't be affected.
5096 */
5097void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005098 if (DEBUG_FOCUS) {
5099 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5100 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005101 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005102 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005103
5104 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005105 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005106 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005107 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005108 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005109 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005110 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005111 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005112 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005113 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005114 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005115 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5116 }
5117 }
5118 mFocusedDisplayId = displayId;
5119
Chris Ye3c2d6f52020-08-09 10:39:48 -07005120 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005121 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005122 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005123
Vishnu Nairad321cd2020-08-20 16:40:21 -07005124 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005125 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005126 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005127 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005128 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005129 }
5130 }
5131 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005132 } // release lock
5133
5134 // Wake up poll loop since it may need to make new input dispatching choices.
5135 mLooper->wake();
5136}
5137
Michael Wrightd02c5b62014-02-10 15:10:22 -08005138void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005139 if (DEBUG_FOCUS) {
5140 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5141 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005142
5143 bool changed;
5144 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005145 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146
5147 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5148 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005149 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005150 }
5151
5152 if (mDispatchEnabled && !enabled) {
5153 resetAndDropEverythingLocked("dispatcher is being disabled");
5154 }
5155
5156 mDispatchEnabled = enabled;
5157 mDispatchFrozen = frozen;
5158 changed = true;
5159 } else {
5160 changed = false;
5161 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005162 } // release lock
5163
5164 if (changed) {
5165 // Wake up poll loop since it may need to make new input dispatching choices.
5166 mLooper->wake();
5167 }
5168}
5169
5170void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005171 if (DEBUG_FOCUS) {
5172 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005174
5175 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005176 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005177
5178 if (mInputFilterEnabled == enabled) {
5179 return;
5180 }
5181
5182 mInputFilterEnabled = enabled;
5183 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5184 } // release lock
5185
5186 // Wake up poll loop since there might be work to do to drop everything.
5187 mLooper->wake();
5188}
5189
Antonio Kanteka042c022022-07-06 16:51:07 -07005190bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5191 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005192 bool needWake = false;
5193 {
5194 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005195 ALOGD_IF(DEBUG_TOUCH_MODE,
5196 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5197 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5198 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5199 mTouchModePerDisplay.count(displayId) == 0
5200 ? "not set"
5201 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5202
Antonio Kantek15beb512022-06-13 22:35:41 +00005203 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5204 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005205 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005206 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005207 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005208 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5209 !recentWindowsAreOwnedByLocked(pid, uid)) {
5210 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5211 "window nor none of the previously interacted window",
5212 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005213 return false;
5214 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005215 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005216 mTouchModePerDisplay[displayId] = inTouchMode;
5217 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5218 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005219 needWake = enqueueInboundEventLocked(std::move(entry));
5220 } // release lock
5221
5222 if (needWake) {
5223 mLooper->wake();
5224 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005225 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005226}
5227
Antonio Kantek48710e42022-03-24 14:19:30 -07005228bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5229 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5230 if (focusedToken == nullptr) {
5231 return false;
5232 }
5233 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5234 return isWindowOwnedBy(windowHandle, pid, uid);
5235}
5236
5237bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5238 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5239 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5240 const sp<WindowInfoHandle> windowHandle =
5241 getWindowHandleLocked(connectionToken);
5242 return isWindowOwnedBy(windowHandle, pid, uid);
5243 }) != mInteractionConnectionTokens.end();
5244}
5245
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005246void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5247 if (opacity < 0 || opacity > 1) {
5248 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5249 return;
5250 }
5251
5252 std::scoped_lock lock(mLock);
5253 mMaximumObscuringOpacityForTouch = opacity;
5254}
5255
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005256std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5257InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005258 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5259 for (TouchedWindow& w : state.windows) {
5260 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005261 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005262 }
5263 }
5264 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005265 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005266}
5267
arthurhungb89ccb02020-12-30 16:19:01 +08005268bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5269 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005270 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005271 if (DEBUG_FOCUS) {
5272 ALOGD("Trivial transfer to same window.");
5273 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005274 return true;
5275 }
5276
Michael Wrightd02c5b62014-02-10 15:10:22 -08005277 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005278 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005279
Arthur Hungabbb9d82021-09-01 14:52:30 +00005280 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005281 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005282 if (state == nullptr || touchedWindow == nullptr) {
5283 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005284 return false;
5285 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005286
Arthur Hungabbb9d82021-09-01 14:52:30 +00005287 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5288 if (toWindowHandle == nullptr) {
5289 ALOGW("Cannot transfer focus because to window not found.");
5290 return false;
5291 }
5292
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005293 if (DEBUG_FOCUS) {
5294 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005295 touchedWindow->windowHandle->getName().c_str(),
5296 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005297 }
5298
Arthur Hungabbb9d82021-09-01 14:52:30 +00005299 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005300 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005301 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005302 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005303 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005304
Arthur Hungabbb9d82021-09-01 14:52:30 +00005305 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005306 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005307 ftl::Flags<InputTarget::Flags> newTargetFlags =
5308 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005309 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005310 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005311 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005312 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313
Arthur Hungabbb9d82021-09-01 14:52:30 +00005314 // Store the dragging window.
5315 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005316 if (pointerIds.count() != 1) {
5317 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5318 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005319 return false;
5320 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005321 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005322 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005323 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005324 }
5325
Arthur Hungabbb9d82021-09-01 14:52:30 +00005326 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005327 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5328 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005329 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005330 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005331 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005332 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005333 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005334 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005335 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5336 newTargetFlags);
5337
5338 // Check if the wallpaper window should deliver the corresponding event.
5339 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5340 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005341 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005342 } // release lock
5343
5344 // Wake up poll loop since it may need to make new input dispatching choices.
5345 mLooper->wake();
5346 return true;
5347}
5348
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005349/**
5350 * Get the touched foreground window on the given display.
5351 * Return null if there are no windows touched on that display, or if more than one foreground
5352 * window is being touched.
5353 */
5354sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5355 auto stateIt = mTouchStatesByDisplay.find(displayId);
5356 if (stateIt == mTouchStatesByDisplay.end()) {
5357 ALOGI("No touch state on display %" PRId32, displayId);
5358 return nullptr;
5359 }
5360
5361 const TouchState& state = stateIt->second;
5362 sp<WindowInfoHandle> touchedForegroundWindow;
5363 // If multiple foreground windows are touched, return nullptr
5364 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005365 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005366 if (touchedForegroundWindow != nullptr) {
5367 ALOGI("Two or more foreground windows: %s and %s",
5368 touchedForegroundWindow->getName().c_str(),
5369 window.windowHandle->getName().c_str());
5370 return nullptr;
5371 }
5372 touchedForegroundWindow = window.windowHandle;
5373 }
5374 }
5375 return touchedForegroundWindow;
5376}
5377
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005378// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005379bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005380 sp<IBinder> fromToken;
5381 { // acquire lock
5382 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005383 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005384 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005385 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5386 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005387 return false;
5388 }
5389
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005390 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5391 if (from == nullptr) {
5392 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5393 return false;
5394 }
5395
5396 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005397 } // release lock
5398
5399 return transferTouchFocus(fromToken, destChannelToken);
5400}
5401
Michael Wrightd02c5b62014-02-10 15:10:22 -08005402void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005403 if (DEBUG_FOCUS) {
5404 ALOGD("Resetting and dropping all events (%s).", reason);
5405 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005406
Michael Wrightfb04fd52022-11-24 22:31:11 +00005407 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408 synthesizeCancelationEventsForAllConnectionsLocked(options);
5409
5410 resetKeyRepeatLocked();
5411 releasePendingEventLocked();
5412 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005413 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005414
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005415 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005416 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005417 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005418}
5419
5420void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005421 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005422 dumpDispatchStateLocked(dump);
5423
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005424 std::istringstream stream(dump);
5425 std::string line;
5426
5427 while (std::getline(stream, line, '\n')) {
5428 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005429 }
5430}
5431
Prabir Pradhan99987712020-11-10 18:43:05 -08005432std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5433 std::string dump;
5434
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005435 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5436 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005437
5438 std::string windowName = "None";
5439 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005440 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005441 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5442 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5443 : "token has capture without window";
5444 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005445 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005446
5447 return dump;
5448}
5449
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005450void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005451 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5452 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5453 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005454 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005455
Tiger Huang721e26f2018-07-24 22:26:19 +08005456 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5457 dump += StringPrintf(INDENT "FocusedApplications:\n");
5458 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5459 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005460 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005461 const std::chrono::duration timeout =
5462 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005463 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005464 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005465 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005466 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005467 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005468 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005469 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005470
Vishnu Nairc519ff72021-01-21 08:23:08 -08005471 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005472 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005473
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005474 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005475 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005476 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005477 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5478 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005479 }
5480 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005481 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482 }
5483
arthurhung6d4bed92021-03-17 11:59:33 +08005484 if (mDragState) {
5485 dump += StringPrintf(INDENT "DragState:\n");
5486 mDragState->dump(dump, INDENT2);
5487 }
5488
Arthur Hungb92218b2018-08-14 12:00:21 +08005489 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005490 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5491 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5492 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5493 const auto& displayInfo = it->second;
5494 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5495 displayInfo.logicalHeight);
5496 displayInfo.transform.dump(dump, "transform", INDENT4);
5497 } else {
5498 dump += INDENT2 "No DisplayInfo found!\n";
5499 }
5500
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005501 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005502 dump += INDENT2 "Windows:\n";
5503 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005504 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5505 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005506
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005507 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005508 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005509 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005510 "applicationInfo.name=%s, "
5511 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005512 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005513 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005514 windowInfo->displayId,
5515 windowInfo->inputConfig.string().c_str(),
5516 windowInfo->alpha, windowInfo->frameLeft,
5517 windowInfo->frameTop, windowInfo->frameRight,
5518 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005519 windowInfo->applicationInfo.name.c_str(),
5520 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005521 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005522 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005523 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005524 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005525 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005526 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005527 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005528 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005529 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005530 }
5531 } else {
5532 dump += INDENT2 "Windows: <none>\n";
5533 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005534 }
5535 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005536 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005537 }
5538
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005539 if (!mGlobalMonitorsByDisplay.empty()) {
5540 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5541 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005542 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005543 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005544 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005545 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005546 }
5547
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005548 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005549
5550 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005551 if (!mRecentQueue.empty()) {
5552 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005553 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005554 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005555 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005556 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005557 }
5558 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005559 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005560 }
5561
5562 // Dump event currently being dispatched.
5563 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005564 dump += INDENT "PendingEvent:\n";
5565 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005566 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005567 dump += StringPrintf(", age=%" PRId64 "ms\n",
5568 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005569 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005570 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005571 }
5572
5573 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005574 if (!mInboundQueue.empty()) {
5575 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005576 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005577 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005578 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005579 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005580 }
5581 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005582 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005583 }
5584
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005585 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005586 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005587 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005588 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005589 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005590 }
5591 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005592 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005593 }
5594
Prabir Pradhancef936d2021-07-21 16:17:52 +00005595 if (!mCommandQueue.empty()) {
5596 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5597 } else {
5598 dump += INDENT "CommandQueue: <empty>\n";
5599 }
5600
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005601 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005602 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005603 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005604 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005605 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005606 connection->inputChannel->getFd().get(),
5607 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005608 connection->getWindowName().c_str(),
5609 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005610 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005611
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005612 if (!connection->outboundQueue.empty()) {
5613 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5614 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005615 dump += dumpQueue(connection->outboundQueue, currentTime);
5616
Michael Wrightd02c5b62014-02-10 15:10:22 -08005617 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005618 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005619 }
5620
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005621 if (!connection->waitQueue.empty()) {
5622 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5623 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005624 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005625 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005626 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005627 }
5628 }
5629 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005630 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005631 }
5632
5633 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005634 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5635 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005636 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005637 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005638 }
5639
Antonio Kantek15beb512022-06-13 22:35:41 +00005640 if (!mTouchModePerDisplay.empty()) {
5641 dump += INDENT "TouchModePerDisplay:\n";
5642 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5643 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5644 std::to_string(touchMode).c_str());
5645 }
5646 } else {
5647 dump += INDENT "TouchModePerDisplay: <none>\n";
5648 }
5649
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005650 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005651 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5652 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5653 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005654 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005655 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005656}
5657
Michael Wright3dd60e22019-03-27 22:06:44 +00005658void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5659 const size_t numMonitors = monitors.size();
5660 for (size_t i = 0; i < numMonitors; i++) {
5661 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005662 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005663 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5664 dump += "\n";
5665 }
5666}
5667
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005668class LooperEventCallback : public LooperCallback {
5669public:
5670 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5671 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5672
5673private:
5674 std::function<int(int events)> mCallback;
5675};
5676
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005677Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005678 if (DEBUG_CHANNEL_CREATION) {
5679 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5680 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005681
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005682 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005683 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005684 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005685
5686 if (result) {
5687 return base::Error(result) << "Failed to open input channel pair with name " << name;
5688 }
5689
Michael Wrightd02c5b62014-02-10 15:10:22 -08005690 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005691 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005692 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005693 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005694 sp<Connection> connection =
Harry Cutts33476232023-01-30 19:57:29 +00005695 sp<Connection>::make(std::move(serverChannel), /*monitor=*/false, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005696
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005697 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5698 ALOGE("Created a new connection, but the token %p is already known", token.get());
5699 }
5700 mConnectionsByToken.emplace(token, connection);
5701
5702 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5703 this, std::placeholders::_1, token);
5704
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005705 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5706 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005707 } // release lock
5708
5709 // Wake the looper because some connections have changed.
5710 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005711 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005712}
5713
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005714Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005715 const std::string& name,
5716 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005717 std::shared_ptr<InputChannel> serverChannel;
5718 std::unique_ptr<InputChannel> clientChannel;
5719 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5720 if (result) {
5721 return base::Error(result) << "Failed to open input channel pair with name " << name;
5722 }
5723
Michael Wright3dd60e22019-03-27 22:06:44 +00005724 { // acquire lock
5725 std::scoped_lock _l(mLock);
5726
5727 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005728 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5729 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005730 }
5731
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005732 sp<Connection> connection =
Harry Cutts33476232023-01-30 19:57:29 +00005733 sp<Connection>::make(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005734 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005735 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005736
5737 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5738 ALOGE("Created a new connection, but the token %p is already known", token.get());
5739 }
5740 mConnectionsByToken.emplace(token, connection);
5741 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5742 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005743
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005744 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005745
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005746 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5747 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005748 }
Garfield Tan15601662020-09-22 15:32:38 -07005749
Michael Wright3dd60e22019-03-27 22:06:44 +00005750 // Wake the looper because some connections have changed.
5751 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005752 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005753}
5754
Garfield Tan15601662020-09-22 15:32:38 -07005755status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005756 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005757 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005758
Harry Cutts33476232023-01-30 19:57:29 +00005759 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005760 if (status) {
5761 return status;
5762 }
5763 } // release lock
5764
5765 // Wake the poll loop because removing the connection may have changed the current
5766 // synchronization state.
5767 mLooper->wake();
5768 return OK;
5769}
5770
Garfield Tan15601662020-09-22 15:32:38 -07005771status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5772 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005773 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005774 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005775 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005776 return BAD_VALUE;
5777 }
5778
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005779 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005780
Michael Wrightd02c5b62014-02-10 15:10:22 -08005781 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005782 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783 }
5784
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005785 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005786
5787 nsecs_t currentTime = now();
5788 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5789
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005790 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005791 return OK;
5792}
5793
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005794void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005795 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5796 auto& [displayId, monitors] = *it;
5797 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5798 return monitor.inputChannel->getConnectionToken() == connectionToken;
5799 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005800
Michael Wright3dd60e22019-03-27 22:06:44 +00005801 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005802 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005803 } else {
5804 ++it;
5805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005806 }
5807}
5808
Michael Wright3dd60e22019-03-27 22:06:44 +00005809status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005810 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005811 return pilferPointersLocked(token);
5812}
Michael Wright3dd60e22019-03-27 22:06:44 +00005813
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005814status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005815 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5816 if (!requestingChannel) {
5817 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5818 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005819 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005820
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005821 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005822 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.none()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005823 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5824 " Ignoring.");
5825 return BAD_VALUE;
5826 }
5827
5828 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005829 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005830 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005831 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005832 "input channel stole pointer stream");
5833 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005834 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005835 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005836 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005837 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005838 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005839 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005840 if (channel != nullptr && channel->getConnectionToken() != token) {
5841 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5842 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5843 canceledWindows += channel->getName();
5844 }
5845 }
5846 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5847 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5848 canceledWindows.c_str());
5849
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005850 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005851 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005852 window.pilferedPointerIds |= window.pointerIds;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005853
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005854 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005855 return OK;
5856}
5857
Prabir Pradhan99987712020-11-10 18:43:05 -08005858void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5859 { // acquire lock
5860 std::scoped_lock _l(mLock);
5861 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005862 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005863 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5864 windowHandle != nullptr ? windowHandle->getName().c_str()
5865 : "token without window");
5866 }
5867
Vishnu Nairc519ff72021-01-21 08:23:08 -08005868 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005869 if (focusedToken != windowToken) {
5870 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5871 enabled ? "enable" : "disable");
5872 return;
5873 }
5874
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005875 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005876 ALOGW("Ignoring request to %s Pointer Capture: "
5877 "window has %s requested pointer capture.",
5878 enabled ? "enable" : "disable", enabled ? "already" : "not");
5879 return;
5880 }
5881
Christine Franksb768bb42021-11-29 12:11:31 -08005882 if (enabled) {
5883 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5884 mIneligibleDisplaysForPointerCapture.end(),
5885 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5886 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5887 return;
5888 }
5889 }
5890
Prabir Pradhan99987712020-11-10 18:43:05 -08005891 setPointerCaptureLocked(enabled);
5892 } // release lock
5893
5894 // Wake the thread to process command entries.
5895 mLooper->wake();
5896}
5897
Christine Franksb768bb42021-11-29 12:11:31 -08005898void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5899 { // acquire lock
5900 std::scoped_lock _l(mLock);
5901 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5902 if (!isEligible) {
5903 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5904 }
5905 } // release lock
5906}
5907
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005908std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5909 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005910 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005911 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005912 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005913 }
5914 }
5915 }
5916 return std::nullopt;
5917}
5918
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005919sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005920 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005921 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005922 }
5923
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005924 for (const auto& [token, connection] : mConnectionsByToken) {
5925 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005926 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005927 }
5928 }
Robert Carr4e670e52018-08-15 13:26:12 -07005929
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005930 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005931}
5932
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005933std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5934 sp<Connection> connection = getConnectionLocked(connectionToken);
5935 if (connection == nullptr) {
5936 return "<nullptr>";
5937 }
5938 return connection->getInputChannelName();
5939}
5940
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005941void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005942 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005943 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005944}
5945
Prabir Pradhancef936d2021-07-21 16:17:52 +00005946void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5947 const sp<Connection>& connection, uint32_t seq,
5948 bool handled, nsecs_t consumeTime) {
5949 // Handle post-event policy actions.
5950 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5951 if (dispatchEntryIt == connection->waitQueue.end()) {
5952 return;
5953 }
5954 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5955 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5956 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5957 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5958 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5959 }
5960 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5961 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5962 connection->inputChannel->getConnectionToken(),
5963 dispatchEntry->deliveryTime, consumeTime, finishTime);
5964 }
5965
5966 bool restartEvent;
5967 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5968 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5969 restartEvent =
5970 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5971 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5972 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5973 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5974 handled);
5975 } else {
5976 restartEvent = false;
5977 }
5978
5979 // Dequeue the event and start the next cycle.
5980 // Because the lock might have been released, it is possible that the
5981 // contents of the wait queue to have been drained, so we need to double-check
5982 // a few things.
5983 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5984 if (dispatchEntryIt != connection->waitQueue.end()) {
5985 dispatchEntry = *dispatchEntryIt;
5986 connection->waitQueue.erase(dispatchEntryIt);
5987 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5988 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5989 if (!connection->responsive) {
5990 connection->responsive = isConnectionResponsive(*connection);
5991 if (connection->responsive) {
5992 // The connection was unresponsive, and now it's responsive.
5993 processConnectionResponsiveLocked(*connection);
5994 }
5995 }
5996 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005997 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005998 connection->outboundQueue.push_front(dispatchEntry);
5999 traceOutboundQueueLength(*connection);
6000 } else {
6001 releaseDispatchEntry(dispatchEntry);
6002 }
6003 }
6004
6005 // Start the next dispatch cycle for this connection.
6006 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006007}
6008
Prabir Pradhancef936d2021-07-21 16:17:52 +00006009void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6010 const sp<IBinder>& newToken) {
6011 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6012 scoped_unlock unlock(mLock);
6013 mPolicy->notifyFocusChanged(oldToken, newToken);
6014 };
6015 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006016}
6017
Prabir Pradhancef936d2021-07-21 16:17:52 +00006018void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6019 auto command = [this, token, x, y]() REQUIRES(mLock) {
6020 scoped_unlock unlock(mLock);
6021 mPolicy->notifyDropWindow(token, x, y);
6022 };
6023 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006024}
6025
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006026void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
6027 if (connection == nullptr) {
6028 LOG_ALWAYS_FATAL("Caller must check for nullness");
6029 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006030 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6031 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006032 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006033 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006034 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006035 return;
6036 }
6037 /**
6038 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6039 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6040 * has changed. This could cause newer entries to time out before the already dispatched
6041 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6042 * processes the events linearly. So providing information about the oldest entry seems to be
6043 * most useful.
6044 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006045 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006046 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6047 std::string reason =
6048 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006049 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006050 ns2ms(currentWait),
6051 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006052 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006053 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006054
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006055 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6056
6057 // Stop waking up for events on this connection, it is already unresponsive
6058 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006059}
6060
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006061void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6062 std::string reason =
6063 StringPrintf("%s does not have a focused window", application->getName().c_str());
6064 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006065
Prabir Pradhancef936d2021-07-21 16:17:52 +00006066 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
6067 scoped_unlock unlock(mLock);
6068 mPolicy->notifyNoFocusedWindowAnr(application);
6069 };
6070 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006071}
6072
chaviw98318de2021-05-19 16:45:23 -05006073void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006074 const std::string& reason) {
6075 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6076 updateLastAnrStateLocked(windowLabel, reason);
6077}
6078
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006079void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6080 const std::string& reason) {
6081 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006082 updateLastAnrStateLocked(windowLabel, reason);
6083}
6084
6085void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6086 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006087 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006088 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006089 struct tm tm;
6090 localtime_r(&t, &tm);
6091 char timestr[64];
6092 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006093 mLastAnrState.clear();
6094 mLastAnrState += INDENT "ANR:\n";
6095 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006096 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6097 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006098 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006099}
6100
Prabir Pradhancef936d2021-07-21 16:17:52 +00006101void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6102 KeyEntry& entry) {
6103 const KeyEvent event = createKeyEvent(entry);
6104 nsecs_t delay = 0;
6105 { // release lock
6106 scoped_unlock unlock(mLock);
6107 android::base::Timer t;
6108 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
6109 entry.policyFlags);
6110 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6111 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6112 std::to_string(t.duration().count()).c_str());
6113 }
6114 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006115
6116 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006117 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006118 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006119 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006120 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006121 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006122 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006123 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006124}
6125
Prabir Pradhancef936d2021-07-21 16:17:52 +00006126void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006127 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006128 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006129 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006130 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006131 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006132 };
6133 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006134}
6135
Prabir Pradhanedd96402022-02-15 01:46:16 -08006136void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6137 std::optional<int32_t> pid) {
6138 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006139 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006140 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006141 };
6142 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006143}
6144
6145/**
6146 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6147 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6148 * command entry to the command queue.
6149 */
6150void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6151 std::string reason) {
6152 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006153 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006154 if (connection.monitor) {
6155 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6156 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006157 pid = findMonitorPidByTokenLocked(connectionToken);
6158 } else {
6159 // The connection is a window
6160 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6161 reason.c_str());
6162 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6163 if (handle != nullptr) {
6164 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006165 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006166 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006167 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006168}
6169
6170/**
6171 * Tell the policy that a connection has become responsive so that it can stop ANR.
6172 */
6173void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6174 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006175 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006176 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006177 pid = findMonitorPidByTokenLocked(connectionToken);
6178 } else {
6179 // The connection is a window
6180 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6181 if (handle != nullptr) {
6182 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006183 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006184 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006185 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006186}
6187
Prabir Pradhancef936d2021-07-21 16:17:52 +00006188bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006189 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006190 KeyEntry& keyEntry, bool handled) {
6191 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006192 if (!handled) {
6193 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006194 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006195 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006196 return false;
6197 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006198
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006199 // Get the fallback key state.
6200 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006201 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006202 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006203 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006204 connection->inputState.removeFallbackKey(originalKeyCode);
6205 }
6206
6207 if (handled || !dispatchEntry->hasForegroundTarget()) {
6208 // If the application handles the original key for which we previously
6209 // generated a fallback or if the window is not a foreground window,
6210 // then cancel the associated fallback key, if any.
6211 if (fallbackKeyCode != -1) {
6212 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006213 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6214 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6215 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6216 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6217 keyEntry.policyFlags);
6218 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006219 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006220 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006221
6222 mLock.unlock();
6223
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006224 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006225 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006226
6227 mLock.lock();
6228
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006229 // Cancel the fallback key.
6230 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006231 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006232 "application handled the original non-fallback key "
6233 "or is no longer a foreground target, "
6234 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006235 options.keyCode = fallbackKeyCode;
6236 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006237 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006238 connection->inputState.removeFallbackKey(originalKeyCode);
6239 }
6240 } else {
6241 // If the application did not handle a non-fallback key, first check
6242 // that we are in a good state to perform unhandled key event processing
6243 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006244 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006245 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006246 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6247 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6248 "since this is not an initial down. "
6249 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6250 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6251 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006252 return false;
6253 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006254
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006255 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006256 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6257 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6258 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6259 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6260 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006261 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006262
6263 mLock.unlock();
6264
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006265 bool fallback =
6266 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006267 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006268
6269 mLock.lock();
6270
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006271 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006272 connection->inputState.removeFallbackKey(originalKeyCode);
6273 return false;
6274 }
6275
6276 // Latch the fallback keycode for this key on an initial down.
6277 // The fallback keycode cannot change at any other point in the lifecycle.
6278 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006279 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006280 fallbackKeyCode = event.getKeyCode();
6281 } else {
6282 fallbackKeyCode = AKEYCODE_UNKNOWN;
6283 }
6284 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6285 }
6286
6287 ALOG_ASSERT(fallbackKeyCode != -1);
6288
6289 // Cancel the fallback key if the policy decides not to send it anymore.
6290 // We will continue to dispatch the key to the policy but we will no
6291 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006292 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6293 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006294 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6295 if (fallback) {
6296 ALOGD("Unhandled key event: Policy requested to send key %d"
6297 "as a fallback for %d, but on the DOWN it had requested "
6298 "to send %d instead. Fallback canceled.",
6299 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6300 } else {
6301 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6302 "but on the DOWN it had requested to send %d. "
6303 "Fallback canceled.",
6304 originalKeyCode, fallbackKeyCode);
6305 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006306 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006307
Michael Wrightfb04fd52022-11-24 22:31:11 +00006308 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006309 "canceling fallback, policy no longer desires it");
6310 options.keyCode = fallbackKeyCode;
6311 synthesizeCancelationEventsForConnectionLocked(connection, options);
6312
6313 fallback = false;
6314 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006315 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006316 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006317 }
6318 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006319
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006320 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6321 {
6322 std::string msg;
6323 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6324 connection->inputState.getFallbackKeys();
6325 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6326 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6327 }
6328 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6329 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006330 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006331 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006332
6333 if (fallback) {
6334 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006335 keyEntry.eventTime = event.getEventTime();
6336 keyEntry.deviceId = event.getDeviceId();
6337 keyEntry.source = event.getSource();
6338 keyEntry.displayId = event.getDisplayId();
6339 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6340 keyEntry.keyCode = fallbackKeyCode;
6341 keyEntry.scanCode = event.getScanCode();
6342 keyEntry.metaState = event.getMetaState();
6343 keyEntry.repeatCount = event.getRepeatCount();
6344 keyEntry.downTime = event.getDownTime();
6345 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006346
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006347 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6348 ALOGD("Unhandled key event: Dispatching fallback key. "
6349 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6350 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6351 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006352 return true; // restart the event
6353 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006354 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6355 ALOGD("Unhandled key event: No fallback key.");
6356 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006357
6358 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006359 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006360 }
6361 }
6362 return false;
6363}
6364
Prabir Pradhancef936d2021-07-21 16:17:52 +00006365bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006366 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006367 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006368 return false;
6369}
6370
Michael Wrightd02c5b62014-02-10 15:10:22 -08006371void InputDispatcher::traceInboundQueueLengthLocked() {
6372 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006373 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006374 }
6375}
6376
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006377void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006378 if (ATRACE_ENABLED()) {
6379 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006380 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6381 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006382 }
6383}
6384
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006385void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006386 if (ATRACE_ENABLED()) {
6387 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006388 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6389 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006390 }
6391}
6392
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006393void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006394 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006395
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006396 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006397 dumpDispatchStateLocked(dump);
6398
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006399 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006400 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006401 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006402 }
6403}
6404
6405void InputDispatcher::monitor() {
6406 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006407 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006408 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006409 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006410}
6411
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006412/**
6413 * Wake up the dispatcher and wait until it processes all events and commands.
6414 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6415 * this method can be safely called from any thread, as long as you've ensured that
6416 * the work you are interested in completing has already been queued.
6417 */
6418bool InputDispatcher::waitForIdle() {
6419 /**
6420 * Timeout should represent the longest possible time that a device might spend processing
6421 * events and commands.
6422 */
6423 constexpr std::chrono::duration TIMEOUT = 100ms;
6424 std::unique_lock lock(mLock);
6425 mLooper->wake();
6426 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6427 return result == std::cv_status::no_timeout;
6428}
6429
Vishnu Naire798b472020-07-23 13:52:21 -07006430/**
6431 * Sets focus to the window identified by the token. This must be called
6432 * after updating any input window handles.
6433 *
6434 * Params:
6435 * request.token - input channel token used to identify the window that should gain focus.
6436 * request.focusedToken - the token that the caller expects currently to be focused. If the
6437 * specified token does not match the currently focused window, this request will be dropped.
6438 * If the specified focused token matches the currently focused window, the call will succeed.
6439 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6440 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6441 * when requesting the focus change. This determines which request gets
6442 * precedence if there is a focus change request from another source such as pointer down.
6443 */
Vishnu Nair958da932020-08-21 17:12:37 -07006444void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6445 { // acquire lock
6446 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006447 std::optional<FocusResolver::FocusChanges> changes =
6448 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6449 if (changes) {
6450 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006451 }
6452 } // release lock
6453 // Wake up poll loop since it may need to make new input dispatching choices.
6454 mLooper->wake();
6455}
6456
Vishnu Nairc519ff72021-01-21 08:23:08 -08006457void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6458 if (changes.oldFocus) {
6459 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006460 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006461 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006462 "focus left window");
6463 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006464 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006465 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006466 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006467 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006468 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006469 }
6470
Prabir Pradhan99987712020-11-10 18:43:05 -08006471 // If a window has pointer capture, then it must have focus. We need to ensure that this
6472 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6473 // If the window loses focus before it loses pointer capture, then the window can be in a state
6474 // where it has pointer capture but not focus, violating the contract. Therefore we must
6475 // dispatch the pointer capture event before the focus event. Since focus events are added to
6476 // the front of the queue (above), we add the pointer capture event to the front of the queue
6477 // after the focus events are added. This ensures the pointer capture event ends up at the
6478 // front.
6479 disablePointerCaptureForcedLocked();
6480
Vishnu Nairc519ff72021-01-21 08:23:08 -08006481 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006482 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006483 }
6484}
Vishnu Nair958da932020-08-21 17:12:37 -07006485
Prabir Pradhan99987712020-11-10 18:43:05 -08006486void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006487 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006488 return;
6489 }
6490
6491 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6492
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006493 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006494 setPointerCaptureLocked(false);
6495 }
6496
6497 if (!mWindowTokenWithPointerCapture) {
6498 // No need to send capture changes because no window has capture.
6499 return;
6500 }
6501
6502 if (mPendingEvent != nullptr) {
6503 // Move the pending event to the front of the queue. This will give the chance
6504 // for the pending event to be dropped if it is a captured event.
6505 mInboundQueue.push_front(mPendingEvent);
6506 mPendingEvent = nullptr;
6507 }
6508
6509 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006510 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006511 mInboundQueue.push_front(std::move(entry));
6512}
6513
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006514void InputDispatcher::setPointerCaptureLocked(bool enable) {
6515 mCurrentPointerCaptureRequest.enable = enable;
6516 mCurrentPointerCaptureRequest.seq++;
6517 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006518 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006519 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006520 };
6521 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006522}
6523
Vishnu Nair599f1412021-06-21 10:39:58 -07006524void InputDispatcher::displayRemoved(int32_t displayId) {
6525 { // acquire lock
6526 std::scoped_lock _l(mLock);
6527 // Set an empty list to remove all handles from the specific display.
6528 setInputWindowsLocked(/* window handles */ {}, displayId);
6529 setFocusedApplicationLocked(displayId, nullptr);
6530 // Call focus resolver to clean up stale requests. This must be called after input windows
6531 // have been removed for the removed display.
6532 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006533 // Reset pointer capture eligibility, regardless of previous state.
6534 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006535 // Remove the associated touch mode state.
6536 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006537 } // release lock
6538
6539 // Wake up poll loop since it may need to make new input dispatching choices.
6540 mLooper->wake();
6541}
6542
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006543void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6544 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006545 // The listener sends the windows as a flattened array. Separate the windows by display for
6546 // more convenient parsing.
6547 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006548 for (const auto& info : windowInfos) {
6549 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006550 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006551 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006552
6553 { // acquire lock
6554 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006555
6556 // Ensure that we have an entry created for all existing displays so that if a displayId has
6557 // no windows, we can tell that the windows were removed from the display.
6558 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6559 handlesPerDisplay[displayId];
6560 }
6561
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006562 mDisplayInfos.clear();
6563 for (const auto& displayInfo : displayInfos) {
6564 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6565 }
6566
6567 for (const auto& [displayId, handles] : handlesPerDisplay) {
6568 setInputWindowsLocked(handles, displayId);
6569 }
6570 }
6571 // Wake up poll loop since it may need to make new input dispatching choices.
6572 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006573}
6574
Vishnu Nair062a8672021-09-03 16:07:44 -07006575bool InputDispatcher::shouldDropInput(
6576 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006577 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6578 (windowHandle->getInfo()->inputConfig.test(
6579 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006580 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006581 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6582 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006583 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006584 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006585 windowHandle->getInfo()->displayId);
6586 return true;
6587 }
6588 return false;
6589}
6590
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006591void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6592 const std::vector<gui::WindowInfo>& windowInfos,
6593 const std::vector<DisplayInfo>& displayInfos) {
6594 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6595}
6596
Arthur Hungdfd528e2021-12-08 13:23:04 +00006597void InputDispatcher::cancelCurrentTouch() {
6598 {
6599 std::scoped_lock _l(mLock);
6600 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006601 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006602 "cancel current touch");
6603 synthesizeCancelationEventsForAllConnectionsLocked(options);
6604
6605 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006606 }
6607 // Wake up poll loop since there might be work to do.
6608 mLooper->wake();
6609}
6610
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006611void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6612 std::scoped_lock _l(mLock);
6613 mMonitorDispatchingTimeout = timeout;
6614}
6615
Arthur Hungc539dbb2022-12-08 07:45:36 +00006616void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6617 const sp<WindowInfoHandle>& oldWindowHandle,
6618 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006619 TouchState& state, int32_t pointerId,
6620 std::vector<InputTarget>& targets) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006621 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6622 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006623 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6624 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6625 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6626 newWindowHandle->getInfo()->inputConfig.test(
6627 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6628 const sp<WindowInfoHandle> oldWallpaper =
6629 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6630 const sp<WindowInfoHandle> newWallpaper =
6631 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6632 if (oldWallpaper == newWallpaper) {
6633 return;
6634 }
6635
6636 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006637 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6638 addWindowTargetLocked(oldWallpaper,
6639 oldTouchedWindow.targetFlags |
6640 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6641 pointerIds, oldTouchedWindow.firstDownTimeInTarget, targets);
6642 state.removeTouchedPointerFromWindow(pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006643 }
6644
6645 if (newWallpaper != nullptr) {
6646 state.addOrUpdateWindow(newWallpaper,
6647 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6648 InputTarget::Flags::WINDOW_IS_OBSCURED |
6649 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6650 pointerIds);
6651 }
6652}
6653
6654void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6655 ftl::Flags<InputTarget::Flags> newTargetFlags,
6656 const sp<WindowInfoHandle> fromWindowHandle,
6657 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006658 TouchState& state,
6659 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006660 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6661 fromWindowHandle->getInfo()->inputConfig.test(
6662 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6663 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6664 toWindowHandle->getInfo()->inputConfig.test(
6665 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6666
6667 const sp<WindowInfoHandle> oldWallpaper =
6668 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6669 const sp<WindowInfoHandle> newWallpaper =
6670 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6671 if (oldWallpaper == newWallpaper) {
6672 return;
6673 }
6674
6675 if (oldWallpaper != nullptr) {
6676 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6677 "transferring touch focus to another window");
6678 state.removeWindowByToken(oldWallpaper->getToken());
6679 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6680 }
6681
6682 if (newWallpaper != nullptr) {
6683 nsecs_t downTimeInTarget = now();
6684 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6685 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6686 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6687 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6688 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
6689 sp<Connection> wallpaperConnection = getConnectionLocked(newWallpaper->getToken());
6690 if (wallpaperConnection != nullptr) {
6691 sp<Connection> toConnection = getConnectionLocked(toWindowHandle->getToken());
6692 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6693 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6694 wallpaperFlags);
6695 }
6696 }
6697}
6698
6699sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6700 const sp<WindowInfoHandle>& windowHandle) const {
6701 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6702 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6703 bool foundWindow = false;
6704 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6705 if (!foundWindow && otherHandle != windowHandle) {
6706 continue;
6707 }
6708 if (windowHandle == otherHandle) {
6709 foundWindow = true;
6710 continue;
6711 }
6712
6713 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6714 return otherHandle;
6715 }
6716 }
6717 return nullptr;
6718}
6719
Garfield Tane84e6f92019-08-29 17:28:41 -07006720} // namespace android::inputdispatcher