blob: 851f13c0d5bbe882058de3b2e654edbe67392370 [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.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700629 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
630 LOG(FATAL) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
631 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000632 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
633 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800634 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000635 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
636 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
637 }
638 out.push_back(touchedWindow);
639 }
640 return out;
641}
642
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800643template <typename T>
644std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
645 left.insert(left.end(), right.begin(), right.end());
646 return left;
647}
648
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000649} // namespace
650
Michael Wrightd02c5b62014-02-10 15:10:22 -0800651// --- InputDispatcher ---
652
Garfield Tan00f511d2019-06-12 16:55:40 -0700653InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800654 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
655
656InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
657 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700658 : mPolicy(policy),
659 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700660 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800661 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700662 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700663 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700664 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800665 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700666 mDispatchEnabled(false),
667 mDispatchFrozen(false),
668 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100669 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000670 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800671 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800672 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000673 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000674 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700675 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800676 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800677
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700678 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700679#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700680 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700681#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700682 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800683 policy->getDispatcherConfiguration(&mConfig);
684}
685
686InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000687 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688
Prabir Pradhancef936d2021-07-21 16:17:52 +0000689 resetKeyRepeatLocked();
690 releasePendingEventLocked();
691 drainInboundQueueLocked();
692 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800693
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000694 while (!mConnectionsByToken.empty()) {
695 sp<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000696 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800697 }
698}
699
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700700status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700701 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700702 return ALREADY_EXISTS;
703 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700704 mThread = std::make_unique<InputThread>(
705 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
706 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700707}
708
709status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700710 if (mThread && mThread->isCallingThread()) {
711 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700712 return INVALID_OPERATION;
713 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700714 mThread.reset();
715 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700716}
717
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700719 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800720 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800721 std::scoped_lock _l(mLock);
722 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800723
724 // Run a dispatch loop if there are no pending commands.
725 // The dispatch loop might enqueue commands to run afterwards.
726 if (!haveCommandsLocked()) {
727 dispatchOnceInnerLocked(&nextWakeupTime);
728 }
729
730 // Run all pending commands if there are any.
731 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000732 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700733 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800734 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800735
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700736 // If we are still waiting for ack on some events,
737 // we might have to wake up earlier to check if an app is anr'ing.
738 const nsecs_t nextAnrCheck = processAnrsLocked();
739 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
740
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800741 // We are about to enter an infinitely long sleep, because we have no commands or
742 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700743 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800744 mDispatcherEnteredIdle.notify_all();
745 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800746 } // release lock
747
748 // Wait for callback or timeout or wake. (make sure we round up, not down)
749 nsecs_t currentTime = now();
750 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
751 mLooper->pollOnce(timeoutMillis);
752}
753
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700754/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500755 * Raise ANR if there is no focused window.
756 * Before the ANR is raised, do a final state check:
757 * 1. The currently focused application must be the same one we are waiting for.
758 * 2. Ensure we still don't have a focused window.
759 */
760void InputDispatcher::processNoFocusedWindowAnrLocked() {
761 // Check if the application that we are waiting for is still focused.
762 std::shared_ptr<InputApplicationHandle> focusedApplication =
763 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
764 if (focusedApplication == nullptr ||
765 focusedApplication->getApplicationToken() !=
766 mAwaitedFocusedApplication->getApplicationToken()) {
767 // Unexpected because we should have reset the ANR timer when focused application changed
768 ALOGE("Waited for a focused window, but focused application has already changed to %s",
769 focusedApplication->getName().c_str());
770 return; // The focused application has changed.
771 }
772
chaviw98318de2021-05-19 16:45:23 -0500773 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500774 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
775 if (focusedWindowHandle != nullptr) {
776 return; // We now have a focused window. No need for ANR.
777 }
778 onAnrLocked(mAwaitedFocusedApplication);
779}
780
781/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700782 * Check if any of the connections' wait queues have events that are too old.
783 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
784 * Return the time at which we should wake up next.
785 */
786nsecs_t InputDispatcher::processAnrsLocked() {
787 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700788 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700789 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
790 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
791 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500792 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700793 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500794 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700795 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700796 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500797 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700798 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
799 }
800 }
801
802 // Check if any connection ANRs are due
803 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
804 if (currentTime < nextAnrCheck) { // most likely scenario
805 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
806 }
807
808 // If we reached here, we have an unresponsive connection.
809 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
810 if (connection == nullptr) {
811 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
812 return nextAnrCheck;
813 }
814 connection->responsive = false;
815 // Stop waking up for this unresponsive connection
816 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000817 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700818 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700819}
820
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800821std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
822 const sp<Connection>& connection) {
823 if (connection->monitor) {
824 return mMonitorDispatchingTimeout;
825 }
826 const sp<WindowInfoHandle> window =
827 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700828 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500829 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700830 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500831 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700832}
833
Michael Wrightd02c5b62014-02-10 15:10:22 -0800834void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
835 nsecs_t currentTime = now();
836
Jeff Browndc5992e2014-04-11 01:27:26 -0700837 // Reset the key repeat timer whenever normal dispatch is suspended while the
838 // device is in a non-interactive state. This is to ensure that we abort a key
839 // repeat if the device is just coming out of sleep.
840 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841 resetKeyRepeatLocked();
842 }
843
844 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
845 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100846 if (DEBUG_FOCUS) {
847 ALOGD("Dispatch frozen. Waiting some more.");
848 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849 return;
850 }
851
852 // Optimize latency of app switches.
853 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
854 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
855 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
856 if (mAppSwitchDueTime < *nextWakeupTime) {
857 *nextWakeupTime = mAppSwitchDueTime;
858 }
859
860 // Ready to start a new event.
861 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700862 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700863 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864 if (isAppSwitchDue) {
865 // The inbound queue is empty so the app switch key we were waiting
866 // for will never arrive. Stop waiting for it.
867 resetPendingAppSwitchLocked(false);
868 isAppSwitchDue = false;
869 }
870
871 // Synthesize a key repeat if appropriate.
872 if (mKeyRepeatState.lastKeyEntry) {
873 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
874 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
875 } else {
876 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
877 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
878 }
879 }
880 }
881
882 // Nothing to do if there is no pending event.
883 if (!mPendingEvent) {
884 return;
885 }
886 } else {
887 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700888 mPendingEvent = mInboundQueue.front();
889 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890 traceInboundQueueLengthLocked();
891 }
892
893 // Poke user activity for this event.
894 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700895 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 }
898
899 // Now we have an event to dispatch.
900 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700901 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700903 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700905 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700907 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 }
909
910 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700911 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912 }
913
914 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700915 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700916 const ConfigurationChangedEntry& typedEntry =
917 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700918 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700919 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700920 break;
921 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700923 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700924 const DeviceResetEntry& typedEntry =
925 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700926 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700927 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700928 break;
929 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100931 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700932 std::shared_ptr<FocusEntry> typedEntry =
933 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100934 dispatchFocusLocked(currentTime, typedEntry);
935 done = true;
936 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
937 break;
938 }
939
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700940 case EventEntry::Type::TOUCH_MODE_CHANGED: {
941 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
942 dispatchTouchModeChangeLocked(currentTime, typedEntry);
943 done = true;
944 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
945 break;
946 }
947
Prabir Pradhan99987712020-11-10 18:43:05 -0800948 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
949 const auto typedEntry =
950 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
951 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
952 done = true;
953 break;
954 }
955
arthurhungb89ccb02020-12-30 16:19:01 +0800956 case EventEntry::Type::DRAG: {
957 std::shared_ptr<DragEntry> typedEntry =
958 std::static_pointer_cast<DragEntry>(mPendingEvent);
959 dispatchDragLocked(currentTime, typedEntry);
960 done = true;
961 break;
962 }
963
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700964 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700965 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700966 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700967 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700968 resetPendingAppSwitchLocked(true);
969 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700970 } else if (dropReason == DropReason::NOT_DROPPED) {
971 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700972 }
973 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700974 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700975 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700976 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700977 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
978 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700979 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700980 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700981 break;
982 }
983
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700984 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700985 std::shared_ptr<MotionEntry> motionEntry =
986 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700987 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
988 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700990 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700991 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700992 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700993 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
994 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700995 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700996 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700997 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998 }
Chris Yef59a2f42020-10-16 12:55:26 -0700999
1000 case EventEntry::Type::SENSOR: {
1001 std::shared_ptr<SensorEntry> sensorEntry =
1002 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1003 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1004 dropReason = DropReason::APP_SWITCH;
1005 }
1006 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1007 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1008 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1009 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1010 dropReason = DropReason::STALE;
1011 }
1012 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1013 done = true;
1014 break;
1015 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016 }
1017
1018 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001019 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001020 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021 }
Michael Wright3a981722015-06-10 15:26:13 +01001022 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023
1024 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001025 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 }
1027}
1028
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001029bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1030 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1031}
1032
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001033/**
1034 * Return true if the events preceding this incoming motion event should be dropped
1035 * Return false otherwise (the default behaviour)
1036 */
1037bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001038 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001039 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001040
1041 // Optimize case where the current application is unresponsive and the user
1042 // decides to touch a window in a different application.
1043 // If the application takes too long to catch up then we drop all events preceding
1044 // the touch into the other window.
1045 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001046 const int32_t displayId = motionEntry.displayId;
1047 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001048 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001049
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001050 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001051 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001052 touchedWindowHandle->getApplicationToken() !=
1053 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001054 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001055 ALOGI("Pruning input queue because user touched a different application while waiting "
1056 "for %s",
1057 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001058 return true;
1059 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001060
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001061 // Alternatively, maybe there's a spy window that could handle this event.
1062 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1063 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1064 for (const auto& windowHandle : touchedSpies) {
1065 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001066 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001067 // This spy window could take more input. Drop all events preceding this
1068 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001069 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001070 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001071 mAwaitedFocusedApplication->getName().c_str());
1072 return true;
1073 }
1074 }
1075 }
1076
1077 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1078 // yet been processed by some connections, the dispatcher will wait for these motion
1079 // events to be processed before dispatching the key event. This is because these motion events
1080 // may cause a new window to be launched, which the user might expect to receive focus.
1081 // To prevent waiting forever for such events, just send the key to the currently focused window
1082 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1083 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1084 "just send the pending key event to the focused window.");
1085 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001086 }
1087 return false;
1088}
1089
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001090bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001091 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001092 mInboundQueue.push_back(std::move(newEntry));
1093 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 traceInboundQueueLengthLocked();
1095
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001096 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001097 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001098 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1099 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001100 // Optimize app switch latency.
1101 // If the application takes too long to catch up then we drop all events preceding
1102 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001103 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001104 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001105 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001106 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001107 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001108 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001109 if (DEBUG_APP_SWITCH) {
1110 ALOGD("App switch is pending!");
1111 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001112 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001113 mAppSwitchSawKeyDown = false;
1114 needWake = true;
1115 }
1116 }
1117 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001118
1119 // If a new up event comes in, and the pending event with same key code has been asked
1120 // to try again later because of the policy. We have to reset the intercept key wake up
1121 // time for it may have been handled in the policy and could be dropped.
1122 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1123 mPendingEvent->type == EventEntry::Type::KEY) {
1124 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1125 if (pendingKey.keyCode == keyEntry.keyCode &&
1126 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001127 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1128 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001129 pendingKey.interceptKeyWakeupTime = 0;
1130 needWake = true;
1131 }
1132 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001133 break;
1134 }
1135
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001136 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001137 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1138 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001139 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1140 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001141 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001143 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001144 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001145 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001146 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1147 break;
1148 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001149 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001150 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001151 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001152 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001153 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1154 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001155 // nothing to do
1156 break;
1157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001158 }
1159
1160 return needWake;
1161}
1162
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001163void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001164 // Do not store sensor event in recent queue to avoid flooding the queue.
1165 if (entry->type != EventEntry::Type::SENSOR) {
1166 mRecentQueue.push_back(entry);
1167 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001168 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001169 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170 }
1171}
1172
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001173std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001174InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001175 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001177 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001178 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001179 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001180 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001181 continue;
1182 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001184 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001185 if (!info.isSpy() &&
1186 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001187 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001188 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001189
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001190 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1191 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001192 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001193 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 }
1195 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001196 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197}
1198
Prabir Pradhand65552b2021-10-07 11:23:50 -07001199std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001200 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001201 // Traverse windows from front to back and gather the touched spy windows.
1202 std::vector<sp<WindowInfoHandle>> spyWindows;
1203 const auto& windowHandles = getWindowHandlesLocked(displayId);
1204 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1205 const WindowInfo& info = *windowHandle->getInfo();
1206
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001207 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001208 continue;
1209 }
1210 if (!info.isSpy()) {
1211 // The first touched non-spy window was found, so return the spy windows touched so far.
1212 return spyWindows;
1213 }
1214 spyWindows.push_back(windowHandle);
1215 }
1216 return spyWindows;
1217}
1218
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001219void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001220 const char* reason;
1221 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001222 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001223 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001224 ALOGD("Dropped event because policy consumed it.");
1225 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001226 reason = "inbound event was dropped because the policy consumed it";
1227 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001228 case DropReason::DISABLED:
1229 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001230 ALOGI("Dropped event because input dispatch is disabled.");
1231 }
1232 reason = "inbound event was dropped because input dispatch is disabled";
1233 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001234 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001235 ALOGI("Dropped event because of pending overdue app switch.");
1236 reason = "inbound event was dropped because of pending overdue app switch";
1237 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001238 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001239 ALOGI("Dropped event because the current application is not responding and the user "
1240 "has started interacting with a different application.");
1241 reason = "inbound event was dropped because the current application is not responding "
1242 "and the user has started interacting with a different application";
1243 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001244 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001245 ALOGI("Dropped event because it is stale.");
1246 reason = "inbound event was dropped because it is stale";
1247 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001248 case DropReason::NO_POINTER_CAPTURE:
1249 ALOGI("Dropped event because there is no window with Pointer Capture.");
1250 reason = "inbound event was dropped because there is no window with Pointer Capture";
1251 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001252 case DropReason::NOT_DROPPED: {
1253 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001254 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256 }
1257
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001258 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001259 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001260 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001262 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001264 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001265 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1266 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001267 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001268 synthesizeCancelationEventsForAllConnectionsLocked(options);
1269 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001270 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1271 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001272 synthesizeCancelationEventsForAllConnectionsLocked(options);
1273 }
1274 break;
1275 }
Chris Yef59a2f42020-10-16 12:55:26 -07001276 case EventEntry::Type::SENSOR: {
1277 break;
1278 }
arthurhungb89ccb02020-12-30 16:19:01 +08001279 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1280 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001281 break;
1282 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001283 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001284 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001285 case EventEntry::Type::CONFIGURATION_CHANGED:
1286 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001287 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001288 break;
1289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290 }
1291}
1292
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001293static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001294 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1295 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296}
1297
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001298bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1299 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1300 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1301 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302}
1303
1304bool InputDispatcher::isAppSwitchPendingLocked() {
Colin Cross5b799302022-10-18 21:52:41 -07001305 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306}
1307
1308void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001309 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001311 if (DEBUG_APP_SWITCH) {
1312 if (handled) {
1313 ALOGD("App switch has arrived.");
1314 } else {
1315 ALOGD("App switch was abandoned.");
1316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318}
1319
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001321 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322}
1323
Prabir Pradhancef936d2021-07-21 16:17:52 +00001324bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001325 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 return false;
1327 }
1328
1329 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001330 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001331 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001332 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1333 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001334 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335 return true;
1336}
1337
Prabir Pradhancef936d2021-07-21 16:17:52 +00001338void InputDispatcher::postCommandLocked(Command&& command) {
1339 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340}
1341
1342void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001343 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001344 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001345 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001346 releaseInboundEventLocked(entry);
1347 }
1348 traceInboundQueueLengthLocked();
1349}
1350
1351void InputDispatcher::releasePendingEventLocked() {
1352 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001353 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001354 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355 }
1356}
1357
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001358void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001359 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001360 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001361 if (DEBUG_DISPATCH_CYCLE) {
1362 ALOGD("Injected inbound event was dropped.");
1363 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001364 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365 }
1366 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001367 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001368 }
1369 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370}
1371
1372void InputDispatcher::resetKeyRepeatLocked() {
1373 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001374 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001375 }
1376}
1377
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001378std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1379 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380
Michael Wright2e732952014-09-24 13:26:59 -07001381 uint32_t policyFlags = entry->policyFlags &
1382 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001383
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001384 std::shared_ptr<KeyEntry> newEntry =
1385 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1386 entry->source, entry->displayId, policyFlags, entry->action,
1387 entry->flags, entry->keyCode, entry->scanCode,
1388 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001390 newEntry->syntheticRepeat = true;
1391 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001392 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001393 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394}
1395
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001396bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001397 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001398 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1399 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1400 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001401
1402 // Reset key repeating in case a keyboard device was added or removed or something.
1403 resetKeyRepeatLocked();
1404
1405 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001406 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1407 scoped_unlock unlock(mLock);
1408 mPolicy->notifyConfigurationChanged(eventTime);
1409 };
1410 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001411 return true;
1412}
1413
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001414bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1415 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001416 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1417 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1418 entry.deviceId);
1419 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001420
liushenxiang42232912021-05-21 20:24:09 +08001421 // Reset key repeating in case a keyboard device was disabled or enabled.
1422 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1423 resetKeyRepeatLocked();
1424 }
1425
Michael Wrightfb04fd52022-11-24 22:31:11 +00001426 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001427 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428 synthesizeCancelationEventsForAllConnectionsLocked(options);
1429 return true;
1430}
1431
Vishnu Nairad321cd2020-08-20 16:40:21 -07001432void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001433 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001434 if (mPendingEvent != nullptr) {
1435 // Move the pending event to the front of the queue. This will give the chance
1436 // for the pending event to get dispatched to the newly focused window
1437 mInboundQueue.push_front(mPendingEvent);
1438 mPendingEvent = nullptr;
1439 }
1440
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001441 std::unique_ptr<FocusEntry> focusEntry =
1442 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1443 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001444
1445 // This event should go to the front of the queue, but behind all other focus events
1446 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001447 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001448 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001449 [](const std::shared_ptr<EventEntry>& event) {
1450 return event->type == EventEntry::Type::FOCUS;
1451 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001452
1453 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001454 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001455}
1456
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001457void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001458 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001459 if (channel == nullptr) {
1460 return; // Window has gone away
1461 }
1462 InputTarget target;
1463 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001464 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001465 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001466 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1467 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001468 std::string reason = std::string("reason=").append(entry->reason);
1469 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001470 dispatchEventLocked(currentTime, entry, {target});
1471}
1472
Prabir Pradhan99987712020-11-10 18:43:05 -08001473void InputDispatcher::dispatchPointerCaptureChangedLocked(
1474 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1475 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001476 dropReason = DropReason::NOT_DROPPED;
1477
Prabir Pradhan99987712020-11-10 18:43:05 -08001478 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001479 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001480
1481 if (entry->pointerCaptureRequest.enable) {
1482 // Enable Pointer Capture.
1483 if (haveWindowWithPointerCapture &&
1484 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001485 // This can happen if pointer capture is disabled and re-enabled before we notify the
1486 // app of the state change, so there is no need to notify the app.
1487 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1488 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001489 }
1490 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001491 // This can happen if a window requests capture and immediately releases capture.
1492 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001493 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001494 return;
1495 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001496 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1497 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1498 return;
1499 }
1500
Vishnu Nairc519ff72021-01-21 08:23:08 -08001501 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001502 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1503 mWindowTokenWithPointerCapture = token;
1504 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001505 // Disable Pointer Capture.
1506 // We do not check if the sequence number matches for requests to disable Pointer Capture
1507 // for two reasons:
1508 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1509 // to disable capture with the same sequence number: one generated by
1510 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1511 // Capture being disabled in InputReader.
1512 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1513 // actual Pointer Capture state that affects events being generated by input devices is
1514 // in InputReader.
1515 if (!haveWindowWithPointerCapture) {
1516 // Pointer capture was already forcefully disabled because of focus change.
1517 dropReason = DropReason::NOT_DROPPED;
1518 return;
1519 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001520 token = mWindowTokenWithPointerCapture;
1521 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001522 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001523 setPointerCaptureLocked(false);
1524 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001525 }
1526
1527 auto channel = getInputChannelLocked(token);
1528 if (channel == nullptr) {
1529 // Window has gone away, clean up Pointer Capture state.
1530 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001531 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001532 setPointerCaptureLocked(false);
1533 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001534 return;
1535 }
1536 InputTarget target;
1537 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001538 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001539 entry->dispatchInProgress = true;
1540 dispatchEventLocked(currentTime, entry, {target});
1541
1542 dropReason = DropReason::NOT_DROPPED;
1543}
1544
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001545void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1546 const std::shared_ptr<TouchModeEntry>& entry) {
1547 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001548 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001549 if (windowHandles.empty()) {
1550 return;
1551 }
1552 const std::vector<InputTarget> inputTargets =
1553 getInputTargetsFromWindowHandlesLocked(windowHandles);
1554 if (inputTargets.empty()) {
1555 return;
1556 }
1557 entry->dispatchInProgress = true;
1558 dispatchEventLocked(currentTime, entry, inputTargets);
1559}
1560
1561std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1562 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1563 std::vector<InputTarget> inputTargets;
1564 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001565 const sp<IBinder>& token = handle->getToken();
1566 if (token == nullptr) {
1567 continue;
1568 }
1569 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1570 if (channel == nullptr) {
1571 continue; // Window has gone away
1572 }
1573 InputTarget target;
1574 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001575 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001576 inputTargets.push_back(target);
1577 }
1578 return inputTargets;
1579}
1580
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001581bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001582 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001584 if (!entry->dispatchInProgress) {
1585 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1586 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1587 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1588 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001589 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590 // We have seen two identical key downs in a row which indicates that the device
1591 // driver is automatically generating key repeats itself. We take note of the
1592 // repeat here, but we disable our own next key repeat timer since it is clear that
1593 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001594 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1595 // Make sure we don't get key down from a different device. If a different
1596 // device Id has same key pressed down, the new device Id will replace the
1597 // current one to hold the key repeat with repeat count reset.
1598 // In the future when got a KEY_UP on the device id, drop it and do not
1599 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1601 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001602 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603 } else {
1604 // Not a repeat. Save key down state in case we do see a repeat later.
1605 resetKeyRepeatLocked();
1606 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1607 }
1608 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001609 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1610 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001611 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001612 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001613 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1614 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001615 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001616 resetKeyRepeatLocked();
1617 }
1618
1619 if (entry->repeatCount == 1) {
1620 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1621 } else {
1622 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1623 }
1624
1625 entry->dispatchInProgress = true;
1626
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001627 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628 }
1629
1630 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001631 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632 if (currentTime < entry->interceptKeyWakeupTime) {
1633 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1634 *nextWakeupTime = entry->interceptKeyWakeupTime;
1635 }
1636 return false; // wait until next wakeup
1637 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001638 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001639 entry->interceptKeyWakeupTime = 0;
1640 }
1641
1642 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001643 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001645 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001646 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001647
1648 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1649 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1650 };
1651 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 return false; // wait for the command to run
1653 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001654 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001656 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001657 if (*dropReason == DropReason::NOT_DROPPED) {
1658 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659 }
1660 }
1661
1662 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001663 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001664 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001665 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1666 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001667 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668 return true;
1669 }
1670
1671 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001672 InputEventInjectionResult injectionResult;
1673 sp<WindowInfoHandle> focusedWindow =
1674 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1675 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001676 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001677 return false;
1678 }
1679
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001680 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001681 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 return true;
1683 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001684 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1685
1686 std::vector<InputTarget> inputTargets;
1687 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001688 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001689 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001691 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001692 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001693
1694 // Dispatch the key.
1695 dispatchEventLocked(currentTime, entry, inputTargets);
1696 return true;
1697}
1698
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001699void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001700 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1701 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1702 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1703 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1704 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1705 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1706 entry.metaState, entry.repeatCount, entry.downTime);
1707 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708}
1709
Prabir Pradhancef936d2021-07-21 16:17:52 +00001710void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1711 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001712 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001713 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1714 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1715 "source=0x%x, sensorType=%s",
1716 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001717 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001718 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001719 auto command = [this, entry]() REQUIRES(mLock) {
1720 scoped_unlock unlock(mLock);
1721
1722 if (entry->accuracyChanged) {
1723 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1724 }
1725 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1726 entry->hwTimestamp, entry->values);
1727 };
1728 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001729}
1730
1731bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001732 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1733 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001734 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001735 }
Chris Yef59a2f42020-10-16 12:55:26 -07001736 { // acquire lock
1737 std::scoped_lock _l(mLock);
1738
1739 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1740 std::shared_ptr<EventEntry> entry = *it;
1741 if (entry->type == EventEntry::Type::SENSOR) {
1742 it = mInboundQueue.erase(it);
1743 releaseInboundEventLocked(entry);
1744 }
1745 }
1746 }
1747 return true;
1748}
1749
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001750bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001751 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001752 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001753 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001754 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 entry->dispatchInProgress = true;
1756
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001757 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758 }
1759
1760 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001761 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001762 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001763 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1764 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765 return true;
1766 }
1767
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001768 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769
1770 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001771 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772
1773 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001774 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001775 if (isPointerEvent) {
1776 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001777
1778 if (mDragState &&
1779 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1780 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1781 pilferPointersLocked(mDragState->dragWindow->getToken());
1782 }
1783
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001784 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001785 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001786 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001787 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1788 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 } else {
1790 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001791 sp<WindowInfoHandle> focusedWindow =
1792 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1793 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1794 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1795 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001796 InputTarget::Flags::FOREGROUND |
1797 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001798 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001801 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802 return false;
1803 }
1804
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001805 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001806 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001807 return true;
1808 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001809 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001810 CancelationOptions::Mode mode(
1811 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1812 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001813 CancelationOptions options(mode, "input event injection failed");
1814 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001815 return true;
1816 }
1817
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001818 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001819 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001820
1821 // Dispatch the motion.
1822 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001823 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001824 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825 synthesizeCancelationEventsForAllConnectionsLocked(options);
1826 }
1827 dispatchEventLocked(currentTime, entry, inputTargets);
1828 return true;
1829}
1830
chaviw98318de2021-05-19 16:45:23 -05001831void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001832 bool isExiting, const int32_t rawX,
1833 const int32_t rawY) {
1834 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001835 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001836 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1837 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001838
1839 enqueueInboundEventLocked(std::move(dragEntry));
1840}
1841
1842void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1843 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1844 if (channel == nullptr) {
1845 return; // Window has gone away
1846 }
1847 InputTarget target;
1848 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001849 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001850 entry->dispatchInProgress = true;
1851 dispatchEventLocked(currentTime, entry, {target});
1852}
1853
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001854void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001855 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001856 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001857 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001858 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001859 "metaState=0x%x, buttonState=0x%x,"
1860 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001861 prefix, entry.eventTime, entry.deviceId,
1862 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1863 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1864 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1865 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001866
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001867 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001868 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001869 "x=%f, y=%f, pressure=%f, size=%f, "
1870 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1871 "orientation=%f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001872 i, entry.pointerProperties[i].id,
1873 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001874 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1875 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1876 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1877 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1878 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1879 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1880 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1881 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1882 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1883 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001884 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885}
1886
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001887void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1888 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001889 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001890 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001891 if (DEBUG_DISPATCH_CYCLE) {
1892 ALOGD("dispatchEventToCurrentInputTargets");
1893 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001894
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001895 updateInteractionTokensLocked(*eventEntry, inputTargets);
1896
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1898
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001899 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001901 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001902 sp<Connection> connection =
1903 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001904 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001905 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001907 if (DEBUG_FOCUS) {
1908 ALOGD("Dropping event delivery to target with channel '%s' because it "
1909 "is no longer registered with the input dispatcher.",
1910 inputTarget.inputChannel->getName().c_str());
1911 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001912 }
1913 }
1914}
1915
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001916void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1917 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1918 // If the policy decides to close the app, we will get a channel removal event via
1919 // unregisterInputChannel, and will clean up the connection that way. We are already not
1920 // sending new pointers to the connection when it blocked, but focused events will continue to
1921 // pile up.
1922 ALOGW("Canceling events for %s because it is unresponsive",
1923 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001924 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001925 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001926 "application not responding");
1927 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928 }
1929}
1930
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001931void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001932 if (DEBUG_FOCUS) {
1933 ALOGD("Resetting ANR timeouts.");
1934 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935
1936 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001937 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001938 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939}
1940
Tiger Huang721e26f2018-07-24 22:26:19 +08001941/**
1942 * Get the display id that the given event should go to. If this event specifies a valid display id,
1943 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1944 * Focused display is the display that the user most recently interacted with.
1945 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001946int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001947 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001948 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001949 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001950 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1951 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001952 break;
1953 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001954 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001955 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1956 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001957 break;
1958 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001959 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001960 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001961 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001962 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001963 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001964 case EventEntry::Type::SENSOR:
1965 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001966 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001967 return ADISPLAY_ID_NONE;
1968 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001969 }
1970 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1971}
1972
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001973bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1974 const char* focusedWindowName) {
1975 if (mAnrTracker.empty()) {
1976 // already processed all events that we waited for
1977 mKeyIsWaitingForEventsTimeout = std::nullopt;
1978 return false;
1979 }
1980
1981 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1982 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001983 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001984 mKeyIsWaitingForEventsTimeout = currentTime +
1985 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1986 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001987 return true;
1988 }
1989
1990 // We still have pending events, and already started the timer
1991 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1992 return true; // Still waiting
1993 }
1994
1995 // Waited too long, and some connection still hasn't processed all motions
1996 // Just send the key to the focused window
1997 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1998 focusedWindowName);
1999 mKeyIsWaitingForEventsTimeout = std::nullopt;
2000 return false;
2001}
2002
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002003sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2004 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2005 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002006 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002007 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008
Tiger Huang721e26f2018-07-24 22:26:19 +08002009 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002010 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002011 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002012 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2013
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014 // If there is no currently focused window and no focused application
2015 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002016 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2017 ALOGI("Dropping %s event because there is no focused window or focused application in "
2018 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002019 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002020 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002021 }
2022
Vishnu Nair062a8672021-09-03 16:07:44 -07002023 // Drop key events if requested by input feature
2024 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002025 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002026 }
2027
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002028 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2029 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2030 // start interacting with another application via touch (app switch). This code can be removed
2031 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2032 // an app is expected to have a focused window.
2033 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2034 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2035 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002036 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2037 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2038 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002039 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002040 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002041 ALOGW("Waiting because no window has focus but %s may eventually add a "
2042 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002043 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002044 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002045 outInjectionResult = InputEventInjectionResult::PENDING;
2046 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002047 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2048 // Already raised ANR. Drop the event
2049 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002050 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002051 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002052 } else {
2053 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002054 outInjectionResult = InputEventInjectionResult::PENDING;
2055 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002056 }
2057 }
2058
2059 // we have a valid, non-null focused window
2060 resetNoFocusedWindowTimeoutLocked();
2061
Prabir Pradhan5735a322022-04-11 17:23:34 +00002062 // Verify targeted injection.
2063 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2064 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002065 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2066 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067 }
2068
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002069 if (focusedWindowHandle->getInfo()->inputConfig.test(
2070 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002071 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002072 outInjectionResult = InputEventInjectionResult::PENDING;
2073 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002074 }
2075
2076 // If the event is a key event, then we must wait for all previous events to
2077 // complete before delivering it because previous events may have the
2078 // side-effect of transferring focus to a different window and we want to
2079 // ensure that the following keys are sent to the new window.
2080 //
2081 // Suppose the user touches a button in a window then immediately presses "A".
2082 // If the button causes a pop-up window to appear then we want to ensure that
2083 // the "A" key is delivered to the new pop-up window. This is because users
2084 // often anticipate pending UI changes when typing on a keyboard.
2085 // To obtain this behavior, we must serialize key events with respect to all
2086 // prior input events.
2087 if (entry.type == EventEntry::Type::KEY) {
2088 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2089 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002090 outInjectionResult = InputEventInjectionResult::PENDING;
2091 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002092 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093 }
2094
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002095 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2096 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002097}
2098
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002099/**
2100 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2101 * that are currently unresponsive.
2102 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002103std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2104 const std::vector<Monitor>& monitors) const {
2105 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002106 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002107 [this](const Monitor& monitor) REQUIRES(mLock) {
2108 sp<Connection> connection =
2109 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002110 if (connection == nullptr) {
2111 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002112 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002113 return false;
2114 }
2115 if (!connection->responsive) {
2116 ALOGW("Unresponsive monitor %s will not get the new gesture",
2117 connection->inputChannel->getName().c_str());
2118 return false;
2119 }
2120 return true;
2121 });
2122 return responsiveMonitors;
2123}
2124
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002125/**
2126 * In general, touch should be always split between windows. Some exceptions:
2127 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2128 * from the same device, *and* the window that's receiving the current pointer does not support
2129 * split touch.
2130 * 2. Don't split mouse events
2131 */
2132bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2133 const MotionEntry& entry) const {
2134 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2135 // We should never split mouse events
2136 return false;
2137 }
2138 for (const TouchedWindow& touchedWindow : touchState.windows) {
2139 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2140 // Spy windows should not affect whether or not touch is split.
2141 continue;
2142 }
2143 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2144 continue;
2145 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002146 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2147 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2148 // Wallpaper window should not affect whether or not touch is split
2149 continue;
2150 }
2151
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002152 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2153 // being sent there. For now, use deviceId from touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002154 if (entry.deviceId == touchState.deviceId && touchedWindow.pointerIds.any()) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002155 return false;
2156 }
2157 }
2158 return true;
2159}
2160
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002161std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002162 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2163 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002164 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002166 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167 // For security reasons, we defer updating the touch state until we are sure that
2168 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002169 const int32_t displayId = entry.displayId;
2170 const int32_t action = entry.action;
2171 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172
2173 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002174 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002175
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002176 // Copy current touch state into tempTouchState.
2177 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2178 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002179 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002180 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002181 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2182 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002183 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002184 }
2185
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002186 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002187 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002188 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002189
2190 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2191 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2192 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002193 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2194 // touchable windows.
2195 const bool wasDown = oldState != nullptr && oldState->isDown();
2196 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2197 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
2198 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002199 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002200
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002201 // If pointers are already down, let's finish the current gesture and ignore the new events
2202 // from another device. However, if the new event is a down event, let's cancel the current
2203 // touch and let the new one take over.
2204 if (switchedDevice && wasDown && !isDown) {
2205 LOG(INFO) << "Dropping event because a pointer for device " << oldState->deviceId
2206 << " is already down in display " << displayId << ": " << entry.getDescription();
2207 // TODO(b/211379801): test multiple simultaneous input streams.
2208 outInjectionResult = InputEventInjectionResult::FAILED;
2209 return {}; // wrong device
2210 }
2211
Michael Wrightd02c5b62014-02-10 15:10:22 -08002212 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002213 // If a new gesture is starting, clear the touch state completely.
2214 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002215 tempTouchState.deviceId = entry.deviceId;
2216 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002217 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002218 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002219 ALOGI("Dropping move event because a pointer for a different device is already active "
2220 "in display %" PRId32,
2221 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002222 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002223 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002224 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225 }
2226
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002227 if (isHoverAction) {
2228 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2229 // all of the existing hovering pointers and recompute.
2230 tempTouchState.clearHoveringPointers();
2231 }
2232
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2234 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002235 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002236 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002237 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2238 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002239 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002240 auto [newTouchedWindowHandle, outsideTargets] =
2241 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002242
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002243 if (isDown) {
2244 targets += outsideTargets;
2245 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002247 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002248 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002250 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002251 }
2252
Prabir Pradhan5735a322022-04-11 17:23:34 +00002253 // Verify targeted injection.
2254 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2255 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002256 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002257 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002258 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002259 }
2260
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002261 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002262 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002263 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2264 // New window supports splitting, but we should never split mouse events.
2265 isSplit = !isFromMouse;
2266 } else if (isSplit) {
2267 // New window does not support splitting but we have already split events.
2268 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002269 newTouchedWindowHandle = nullptr;
2270 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002271 } else {
2272 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002273 // be delivered to a new window which supports split touch. Pointers from a mouse device
2274 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002275 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002276 }
2277
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002278 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002279 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002280 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002281 // Process the foreground window first so that it is the first to receive the event.
2282 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002283 }
2284
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002285 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002286 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2287 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002288 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002289 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002290 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002291 }
2292
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002293 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002294 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002295 continue;
2296 }
2297
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002298 if (isHoverAction) {
2299 const int32_t pointerId = entry.pointerProperties[0].id;
2300 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2301 // Pointer left. Remove it
2302 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2303 } else {
2304 // The "windowHandle" is the target of this hovering pointer.
2305 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId,
2306 pointerId);
2307 }
2308 }
2309
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002310 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002311 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002312
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002313 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2314 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002315 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002316 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002317
2318 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002319 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002320 }
2321 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002322 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002323 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002324 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002325 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002326
2327 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002328 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002329 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002330 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002331 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002332
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002333 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2334 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2335
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002336 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2337 // still add a window to the touch state. We should avoid doing that, but some of the
2338 // later checks ("at least one foreground window") rely on this in order to dispatch
2339 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002340 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002341 isDownOrPointerDown
2342 ? std::make_optional(entry.eventTime)
2343 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002344
2345 // If this is the pointer going down and the touched window has a wallpaper
2346 // then also add the touched wallpaper windows so they are locked in for the duration
2347 // of the touch gesture.
2348 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2349 // engine only supports touch events. We would need to add a mechanism similar
2350 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002351 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002352 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2353 windowHandle->getInfo()->inputConfig.test(
2354 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2355 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2356 if (wallpaper != nullptr) {
2357 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2358 InputTarget::Flags::WINDOW_IS_OBSCURED |
2359 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2360 InputTarget::Flags::DISPATCH_AS_IS;
2361 if (isSplit) {
2362 wallpaperFlags |= InputTarget::Flags::SPLIT;
2363 }
2364 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2365 entry.eventTime);
2366 }
2367 }
2368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002369 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002370
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002371 // If a window is already pilfering some pointers, give it this new pointer as well and
2372 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2373 // which is a specific behaviour that we want.
2374 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2375 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002376 if (touchedWindow.pointerIds.test(pointerId) &&
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002377 touchedWindow.pilferedPointerIds.count() > 0) {
2378 // This window is already pilfering some pointers, and this new pointer is also
2379 // going to it. Therefore, take over this pointer and don't give it to anyone
2380 // else.
2381 touchedWindow.pilferedPointerIds.set(pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002382 }
2383 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002384
2385 // Restrict all pilfered pointers to the pilfering windows.
2386 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002387 } else {
2388 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2389
2390 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002391 if (!tempTouchState.isDown()) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002392 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2393 "dropped the pointer down event in display "
2394 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002395 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002396 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002397 }
2398
arthurhung6d4bed92021-03-17 11:59:33 +08002399 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002400
Michael Wrightd02c5b62014-02-10 15:10:22 -08002401 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002402 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002403 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002404 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002405 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002406 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002407 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002408 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002409
Prabir Pradhan5735a322022-04-11 17:23:34 +00002410 // Verify targeted injection.
2411 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2412 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002413 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002414 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002415 }
2416
Vishnu Nair062a8672021-09-03 16:07:44 -07002417 // Drop touch events if requested by input feature
2418 if (newTouchedWindowHandle != nullptr &&
2419 shouldDropInput(entry, newTouchedWindowHandle)) {
2420 newTouchedWindowHandle = nullptr;
2421 }
2422
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002423 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2424 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002425 if (DEBUG_FOCUS) {
2426 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2427 oldTouchedWindowHandle->getName().c_str(),
2428 newTouchedWindowHandle->getName().c_str(), displayId);
2429 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002430 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002431 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002432 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002433 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002434
2435 const TouchedWindow& touchedWindow =
2436 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2437 addWindowTargetLocked(oldTouchedWindowHandle,
2438 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
2439 touchedWindow.firstDownTimeInTarget, targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440
2441 // Make a slippery entrance into the new window.
2442 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002443 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002444 }
2445
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002446 ftl::Flags<InputTarget::Flags> targetFlags =
2447 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002448 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002449 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002450 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002451 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002452 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002453 }
2454 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002455 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002456 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002457 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002458 }
2459
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002460 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2461 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002462
2463 // Check if the wallpaper window should deliver the corresponding event.
2464 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002465 tempTouchState, pointerId, targets);
2466 tempTouchState.removeTouchedPointerFromWindow(pointerId, oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002467 }
2468 }
Arthur Hung96483742022-11-15 03:30:48 +00002469
2470 // Update the pointerIds for non-splittable when it received pointer down.
2471 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2472 // If no split, we suppose all touched windows should receive pointer down.
2473 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2474 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2475 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2476 // Ignore drag window for it should just track one pointer.
2477 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2478 continue;
2479 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002480 touchedWindow.pointerIds.set(entry.pointerProperties[pointerIndex].id);
Arthur Hung96483742022-11-15 03:30:48 +00002481 }
2482 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483 }
2484
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002485 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002486 {
2487 std::vector<TouchedWindow> hoveringWindows =
2488 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2489 for (const TouchedWindow& touchedWindow : hoveringWindows) {
2490 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2491 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2492 targets);
2493 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494 }
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002495 // Ensure that we have at least one foreground window or at least one window that cannot be a
2496 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2497 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2498 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002499 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2500 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002501 return !canReceiveForegroundTouches(
2502 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002503 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002504 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002505 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2506 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002507 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002508 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002509 }
2510
Prabir Pradhan5735a322022-04-11 17:23:34 +00002511 // Ensure that all touched windows are valid for injection.
2512 if (entry.injectionState != nullptr) {
2513 std::string errs;
2514 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002515 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002516 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2517 // dispatched to any uid, since the coords will be zeroed out later.
2518 continue;
2519 }
2520 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2521 if (err) errs += "\n - " + *err;
2522 }
2523 if (!errs.empty()) {
2524 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2525 "%d:%s",
2526 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002527 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002528 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002529 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002530 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002531
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002532 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2533 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002534 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002535 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002536 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002537 if (foregroundWindowHandle) {
2538 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002539 for (InputTarget& target : targets) {
2540 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2541 sp<WindowInfoHandle> targetWindow =
2542 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2543 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2544 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002545 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002546 }
2547 }
2548 }
2549 }
2550
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002551 // Success! Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002552 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002553 if (touchedWindow.pointerIds.none() && !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002554 // Windows with hovering pointers are getting persisted inside TouchState.
2555 // Do not send this event to those windows.
2556 continue;
2557 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002558 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2559 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2560 targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002561 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002562
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002563 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002564 // Drop the outside or hover touch windows since we will not care about them
2565 // in the next iteration.
2566 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002567
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002569 if (switchedDevice) {
2570 if (DEBUG_FOCUS) {
2571 ALOGD("Conflicting pointer actions: Switched to a different device.");
2572 }
2573 *outConflictingPointerActions = true;
2574 }
2575
2576 if (isHoverAction) {
2577 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002578 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002579 ALOGD_IF(DEBUG_FOCUS,
2580 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002581 *outConflictingPointerActions = true;
2582 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002583 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2584 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2585 tempTouchState.deviceId = entry.deviceId;
2586 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002587 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002588 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2589 // Pointer went up.
2590 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002591 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002592 // All pointers up or canceled.
2593 tempTouchState.reset();
2594 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2595 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002596 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2597 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002598 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002599 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002600 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2601 // One pointer went up.
2602 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2603 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002604
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002605 for (size_t i = 0; i < tempTouchState.windows.size();) {
2606 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002607 touchedWindow.pointerIds.reset(pointerId);
2608 if (touchedWindow.pointerIds.none()) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002609 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2610 continue;
2611 }
2612 i += 1;
2613 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002614 }
2615
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002616 // Save changes unless the action was scroll in which case the temporary touch
2617 // state was only valid for this one action.
2618 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002619 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002620 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002621 mTouchStatesByDisplay[displayId] = tempTouchState;
2622 } else {
2623 mTouchStatesByDisplay.erase(displayId);
2624 }
2625 }
2626
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002627 if (tempTouchState.windows.empty()) {
2628 mTouchStatesByDisplay.erase(displayId);
2629 }
2630
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002631 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002632}
2633
arthurhung6d4bed92021-03-17 11:59:33 +08002634void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002635 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2636 // have an explicit reason to support it.
2637 constexpr bool isStylus = false;
2638
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002639 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002640 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002641 if (dropWindow) {
2642 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002643 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002644 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002645 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002646 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002647 }
2648 mDragState.reset();
2649}
2650
2651void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002652 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002653 return;
2654 }
2655
arthurhung6d4bed92021-03-17 11:59:33 +08002656 if (!mDragState->isStartDrag) {
2657 mDragState->isStartDrag = true;
2658 mDragState->isStylusButtonDownAtStart =
2659 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2660 }
2661
Arthur Hung54745652022-04-20 07:17:41 +00002662 // Find the pointer index by id.
2663 int32_t pointerIndex = 0;
2664 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2665 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2666 if (pointerProperties.id == mDragState->pointerId) {
2667 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002668 }
Arthur Hung54745652022-04-20 07:17:41 +00002669 }
arthurhung6d4bed92021-03-17 11:59:33 +08002670
Arthur Hung54745652022-04-20 07:17:41 +00002671 if (uint32_t(pointerIndex) == entry.pointerCount) {
2672 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002673 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002674 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002675 return;
2676 }
2677
2678 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2679 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2680 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2681
2682 switch (maskedAction) {
2683 case AMOTION_EVENT_ACTION_MOVE: {
2684 // Handle the special case : stylus button no longer pressed.
2685 bool isStylusButtonDown =
2686 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2687 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2688 finishDragAndDrop(entry.displayId, x, y);
2689 return;
2690 }
2691
2692 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2693 // until we have an explicit reason to support it.
2694 constexpr bool isStylus = false;
2695
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002696 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002697 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002698 // enqueue drag exit if needed.
2699 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2700 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2701 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002702 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002703 y);
2704 }
2705 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2706 }
2707 // enqueue drag location if needed.
2708 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002709 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002710 }
2711 break;
2712 }
2713
2714 case AMOTION_EVENT_ACTION_POINTER_UP:
2715 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2716 break;
2717 }
2718 // The drag pointer is up.
2719 [[fallthrough]];
2720 case AMOTION_EVENT_ACTION_UP:
2721 finishDragAndDrop(entry.displayId, x, y);
2722 break;
2723 case AMOTION_EVENT_ACTION_CANCEL: {
2724 ALOGD("Receiving cancel when drag and drop.");
2725 sendDropWindowCommandLocked(nullptr, 0, 0);
2726 mDragState.reset();
2727 break;
2728 }
arthurhungb89ccb02020-12-30 16:19:01 +08002729 }
2730}
2731
chaviw98318de2021-05-19 16:45:23 -05002732void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002733 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002734 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002735 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002736 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002737 std::vector<InputTarget>::iterator it =
2738 std::find_if(inputTargets.begin(), inputTargets.end(),
2739 [&windowHandle](const InputTarget& inputTarget) {
2740 return inputTarget.inputChannel->getConnectionToken() ==
2741 windowHandle->getToken();
2742 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002743
chaviw98318de2021-05-19 16:45:23 -05002744 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002745
2746 if (it == inputTargets.end()) {
2747 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002748 std::shared_ptr<InputChannel> inputChannel =
2749 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002750 if (inputChannel == nullptr) {
2751 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2752 return;
2753 }
2754 inputTarget.inputChannel = inputChannel;
2755 inputTarget.flags = targetFlags;
2756 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002757 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002758 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2759 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002760 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002761 } else {
Siarhei Vishniakoua06bb552023-02-07 09:38:56 -08002762 // DisplayInfo not found for this window on display windowInfo->displayId.
2763 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002764 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002765 inputTargets.push_back(inputTarget);
2766 it = inputTargets.end() - 1;
2767 }
2768
2769 ALOG_ASSERT(it->flags == targetFlags);
2770 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2771
chaviw1ff3d1e2020-07-01 15:53:47 -07002772 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002773}
2774
Michael Wright3dd60e22019-03-27 22:06:44 +00002775void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002776 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002777 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2778 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002779
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002780 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2781 InputTarget target;
2782 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002783 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002784 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2785 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002786 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2787 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002788 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002789 target.setDefaultPointerTransform(target.displayTransform);
2790 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002791 }
2792}
2793
Robert Carrc9bf1d32020-04-13 17:21:08 -07002794/**
2795 * Indicate whether one window handle should be considered as obscuring
2796 * another window handle. We only check a few preconditions. Actually
2797 * checking the bounds is left to the caller.
2798 */
chaviw98318de2021-05-19 16:45:23 -05002799static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2800 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002801 // Compare by token so cloned layers aren't counted
2802 if (haveSameToken(windowHandle, otherHandle)) {
2803 return false;
2804 }
2805 auto info = windowHandle->getInfo();
2806 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002807 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002808 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002809 } else if (otherInfo->alpha == 0 &&
2810 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002811 // Those act as if they were invisible, so we don't need to flag them.
2812 // We do want to potentially flag touchable windows even if they have 0
2813 // opacity, since they can consume touches and alter the effects of the
2814 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002815 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002816 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2817 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002818 } else if (info->ownerUid == otherInfo->ownerUid) {
2819 // If ownerUid is the same we don't generate occlusion events as there
2820 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002821 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002822 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002823 return false;
2824 } else if (otherInfo->displayId != info->displayId) {
2825 return false;
2826 }
2827 return true;
2828}
2829
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002830/**
2831 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2832 * untrusted, one should check:
2833 *
2834 * 1. If result.hasBlockingOcclusion is true.
2835 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2836 * BLOCK_UNTRUSTED.
2837 *
2838 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2839 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2840 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2841 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2842 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2843 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2844 *
2845 * If neither of those is true, then it means the touch can be allowed.
2846 */
2847InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002848 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2849 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002850 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002851 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002852 TouchOcclusionInfo info;
2853 info.hasBlockingOcclusion = false;
2854 info.obscuringOpacity = 0;
2855 info.obscuringUid = -1;
2856 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002857 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002858 if (windowHandle == otherHandle) {
2859 break; // All future windows are below us. Exit early.
2860 }
chaviw98318de2021-05-19 16:45:23 -05002861 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002862 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2863 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002864 if (DEBUG_TOUCH_OCCLUSION) {
2865 info.debugInfo.push_back(
2866 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2867 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002868 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2869 // we perform the checks below to see if the touch can be propagated or not based on the
2870 // window's touch occlusion mode
2871 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2872 info.hasBlockingOcclusion = true;
2873 info.obscuringUid = otherInfo->ownerUid;
2874 info.obscuringPackage = otherInfo->packageName;
2875 break;
2876 }
2877 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2878 uint32_t uid = otherInfo->ownerUid;
2879 float opacity =
2880 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2881 // Given windows A and B:
2882 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2883 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2884 opacityByUid[uid] = opacity;
2885 if (opacity > info.obscuringOpacity) {
2886 info.obscuringOpacity = opacity;
2887 info.obscuringUid = uid;
2888 info.obscuringPackage = otherInfo->packageName;
2889 }
2890 }
2891 }
2892 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002893 if (DEBUG_TOUCH_OCCLUSION) {
2894 info.debugInfo.push_back(
2895 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2896 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002897 return info;
2898}
2899
chaviw98318de2021-05-19 16:45:23 -05002900std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002901 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002902 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2903 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2904 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2905 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002906 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2907 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2908 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2909 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2910 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002911 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002912 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002913}
2914
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002915bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2916 if (occlusionInfo.hasBlockingOcclusion) {
2917 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2918 occlusionInfo.obscuringUid);
2919 return false;
2920 }
2921 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2922 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2923 "%.2f, maximum allowed = %.2f)",
2924 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2925 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2926 return false;
2927 }
2928 return true;
2929}
2930
chaviw98318de2021-05-19 16:45:23 -05002931bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002932 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002934 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2935 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002936 if (windowHandle == otherHandle) {
2937 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938 }
chaviw98318de2021-05-19 16:45:23 -05002939 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002940 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002941 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942 return true;
2943 }
2944 }
2945 return false;
2946}
2947
chaviw98318de2021-05-19 16:45:23 -05002948bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002949 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002950 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2951 const WindowInfo* windowInfo = windowHandle->getInfo();
2952 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002953 if (windowHandle == otherHandle) {
2954 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002955 }
chaviw98318de2021-05-19 16:45:23 -05002956 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002957 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002958 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002959 return true;
2960 }
2961 }
2962 return false;
2963}
2964
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002965std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002966 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002967 if (applicationHandle != nullptr) {
2968 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002969 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002970 } else {
2971 return applicationHandle->getName();
2972 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002973 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002974 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002975 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002976 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002977 }
2978}
2979
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002980void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002981 if (!isUserActivityEvent(eventEntry)) {
2982 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002983 return;
2984 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002985 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002986 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002987 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002988 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002989 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002990 if (DEBUG_DISPATCH_CYCLE) {
2991 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2992 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002993 return;
2994 }
2995 }
2996
2997 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002998 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002999 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003000 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3001 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003002 return;
3003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003005 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003006 eventType = USER_ACTIVITY_EVENT_TOUCH;
3007 }
3008 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003009 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003010 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003011 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3012 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003013 return;
3014 }
3015 eventType = USER_ACTIVITY_EVENT_BUTTON;
3016 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003018 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003019 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003020 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003021 break;
3022 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003023 }
3024
Prabir Pradhancef936d2021-07-21 16:17:52 +00003025 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3026 REQUIRES(mLock) {
3027 scoped_unlock unlock(mLock);
3028 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
3029 };
3030 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003031}
3032
3033void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003034 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003035 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003036 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003037 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003038 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003039 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003040 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003041 ATRACE_NAME(message.c_str());
3042 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003043 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003044 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003045 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003046 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003047 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003048 inputTarget.getPointerInfoString().c_str());
3049 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003050
3051 // Skip this event if the connection status is not normal.
3052 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003053 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003054 if (DEBUG_DISPATCH_CYCLE) {
3055 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003056 connection->getInputChannelName().c_str(),
3057 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003058 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003059 return;
3060 }
3061
3062 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003063 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003064 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003065 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003066 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003067
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003068 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003069 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003070 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3071 logDispatchStateLocked();
3072 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3073 "target on connection "
3074 << connection->getInputChannelName() << " for "
3075 << originalMotionEntry.getDescription();
3076 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003077 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003078 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3079 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003080 if (!splitMotionEntry) {
3081 return; // split event was dropped
3082 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003083 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3084 std::string reason = std::string("reason=pointer cancel on split window");
3085 android_log_event_list(LOGTAG_INPUT_CANCEL)
3086 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3087 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003088 if (DEBUG_FOCUS) {
3089 ALOGD("channel '%s' ~ Split motion event.",
3090 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003091 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003092 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003093 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3094 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003095 return;
3096 }
3097 }
3098
3099 // Not splitting. Enqueue dispatch entries for the event as is.
3100 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3101}
3102
3103void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003104 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003105 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003106 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003107 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003108 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003109 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003110 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003111 ATRACE_NAME(message.c_str());
3112 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003113 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3114 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003115
hongzuo liu95785e22022-09-06 02:51:35 +00003116 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117
3118 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003119 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003120 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003121 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003122 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003123 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003124 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003125 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003126 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003127 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003128 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003129 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003130 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003131
3132 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003133 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003134 startDispatchCycleLocked(currentTime, connection);
3135 }
3136}
3137
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003138void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003139 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003140 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003141 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003142 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003143 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3144 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003145 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003146 ATRACE_NAME(message.c_str());
3147 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003148 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3149 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150 return;
3151 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003152
3153 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3154 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003155
3156 // This is a new event.
3157 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003158 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003159 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003161 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3162 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003163 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003165 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003166 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003167 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003168 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003169 dispatchEntry->resolvedAction = keyEntry.action;
3170 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003172 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3173 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003174 if (DEBUG_DISPATCH_CYCLE) {
3175 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3176 "event",
3177 connection->getInputChannelName().c_str());
3178 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003179 return; // skip the inconsistent event
3180 }
3181 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003182 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003184 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003185 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003186 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3187 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3188 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3189 static_cast<int32_t>(IdGenerator::Source::OTHER);
3190 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003191 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003192 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003193 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003194 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003195 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003196 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003197 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003198 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003199 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003200 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3201 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003202 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003203 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003204 }
3205 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003206 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3207 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003208 if (DEBUG_DISPATCH_CYCLE) {
3209 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3210 "enter event",
3211 connection->getInputChannelName().c_str());
3212 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003213 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3214 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003215 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3216 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003218 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003219 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3220 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3221 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003222 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003223 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3224 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003225 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003226 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003229 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3230 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003231 if (DEBUG_DISPATCH_CYCLE) {
3232 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3233 "event",
3234 connection->getInputChannelName().c_str());
3235 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003236 return; // skip the inconsistent event
3237 }
3238
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003239 dispatchEntry->resolvedEventId =
3240 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3241 ? mIdGenerator.nextId()
3242 : motionEntry.id;
3243 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3244 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3245 ") to MotionEvent(id=0x%" PRIx32 ").",
3246 motionEntry.id, dispatchEntry->resolvedEventId);
3247 ATRACE_NAME(message.c_str());
3248 }
3249
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003250 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3251 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3252 // Skip reporting pointer down outside focus to the policy.
3253 break;
3254 }
3255
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003256 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003257 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003258
3259 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003260 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003261 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003262 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003263 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3264 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003265 break;
3266 }
Chris Yef59a2f42020-10-16 12:55:26 -07003267 case EventEntry::Type::SENSOR: {
3268 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3269 break;
3270 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003271 case EventEntry::Type::CONFIGURATION_CHANGED:
3272 case EventEntry::Type::DEVICE_RESET: {
3273 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003274 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003275 break;
3276 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003277 }
3278
3279 // Remember that we are waiting for this dispatch to complete.
3280 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003281 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003282 }
3283
3284 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003285 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003286 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003287}
3288
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003289/**
3290 * This function is purely for debugging. It helps us understand where the user interaction
3291 * was taking place. For example, if user is touching launcher, we will see a log that user
3292 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3293 * We will see both launcher and wallpaper in that list.
3294 * Once the interaction with a particular set of connections starts, no new logs will be printed
3295 * until the set of interacted connections changes.
3296 *
3297 * The following items are skipped, to reduce the logspam:
3298 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3299 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3300 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3301 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3302 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003303 */
3304void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3305 const std::vector<InputTarget>& targets) {
3306 // Skip ACTION_UP events, and all events other than keys and motions
3307 if (entry.type == EventEntry::Type::KEY) {
3308 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3309 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3310 return;
3311 }
3312 } else if (entry.type == EventEntry::Type::MOTION) {
3313 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3314 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3315 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3316 return;
3317 }
3318 } else {
3319 return; // Not a key or a motion
3320 }
3321
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003322 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003323 std::vector<sp<Connection>> newConnections;
3324 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003325 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003326 continue; // Skip windows that receive ACTION_OUTSIDE
3327 }
3328
3329 sp<IBinder> token = target.inputChannel->getConnectionToken();
3330 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003331 if (connection == nullptr) {
3332 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003333 }
3334 newConnectionTokens.insert(std::move(token));
3335 newConnections.emplace_back(connection);
3336 }
3337 if (newConnectionTokens == mInteractionConnectionTokens) {
3338 return; // no change
3339 }
3340 mInteractionConnectionTokens = newConnectionTokens;
3341
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003342 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003343 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003344 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003345 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003346 std::string message = "Interaction with: " + targetList;
3347 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003348 message += "<none>";
3349 }
3350 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3351}
3352
chaviwfd6d3512019-03-25 13:23:49 -07003353void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003354 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003355 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003356 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3357 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003358 return;
3359 }
3360
Vishnu Nairc519ff72021-01-21 08:23:08 -08003361 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003362 if (focusedToken == token) {
3363 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003364 return;
3365 }
3366
Prabir Pradhancef936d2021-07-21 16:17:52 +00003367 auto command = [this, token]() REQUIRES(mLock) {
3368 scoped_unlock unlock(mLock);
3369 mPolicy->onPointerDownOutsideFocus(token);
3370 };
3371 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003372}
3373
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003374status_t InputDispatcher::publishMotionEvent(Connection& connection,
3375 DispatchEntry& dispatchEntry) const {
3376 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3377 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3378
3379 PointerCoords scaledCoords[MAX_POINTERS];
3380 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3381
3382 // Set the X and Y offset and X and Y scale depending on the input source.
3383 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003384 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003385 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3386 if (globalScaleFactor != 1.0f) {
3387 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3388 scaledCoords[i] = motionEntry.pointerCoords[i];
3389 // Don't apply window scale here since we don't want scale to affect raw
3390 // coordinates. The scale will be sent back to the client and applied
3391 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003392 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003393 }
3394 usingCoords = scaledCoords;
3395 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003396 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003397 // We don't want the dispatch target to know the coordinates
3398 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3399 scaledCoords[i].clear();
3400 }
3401 usingCoords = scaledCoords;
3402 }
3403
3404 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3405
3406 // Publish the motion event.
3407 return connection.inputPublisher
3408 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3409 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3410 std::move(hmac), dispatchEntry.resolvedAction,
3411 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3412 motionEntry.edgeFlags, motionEntry.metaState,
3413 motionEntry.buttonState, motionEntry.classification,
3414 dispatchEntry.transform, motionEntry.xPrecision,
3415 motionEntry.yPrecision, motionEntry.xCursorPosition,
3416 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3417 motionEntry.downTime, motionEntry.eventTime,
3418 motionEntry.pointerCount, motionEntry.pointerProperties,
3419 usingCoords);
3420}
3421
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003423 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003424 if (ATRACE_ENABLED()) {
3425 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003426 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003427 ATRACE_NAME(message.c_str());
3428 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003429 if (DEBUG_DISPATCH_CYCLE) {
3430 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3431 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003433 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003434 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003436 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003437 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438
3439 // Publish the event.
3440 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003441 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3442 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003443 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003444 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3445 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003446 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3447 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3448 << connection->getInputChannelName();
3449 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003450
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003451 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003452 status = connection->inputPublisher
3453 .publishKeyEvent(dispatchEntry->seq,
3454 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3455 keyEntry.source, keyEntry.displayId,
3456 std::move(hmac), dispatchEntry->resolvedAction,
3457 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3458 keyEntry.scanCode, keyEntry.metaState,
3459 keyEntry.repeatCount, keyEntry.downTime,
3460 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003461 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003462 }
3463
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003464 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003465 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3466 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3467 << connection->getInputChannelName();
3468 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003469 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003470 break;
3471 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003472
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003473 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003474 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003475 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003476 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003477 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003478 break;
3479 }
3480
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003481 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3482 const TouchModeEntry& touchModeEntry =
3483 static_cast<const TouchModeEntry&>(eventEntry);
3484 status = connection->inputPublisher
3485 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3486 touchModeEntry.inTouchMode);
3487
3488 break;
3489 }
3490
Prabir Pradhan99987712020-11-10 18:43:05 -08003491 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3492 const auto& captureEntry =
3493 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3494 status = connection->inputPublisher
3495 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003496 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003497 break;
3498 }
3499
arthurhungb89ccb02020-12-30 16:19:01 +08003500 case EventEntry::Type::DRAG: {
3501 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3502 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3503 dragEntry.id, dragEntry.x,
3504 dragEntry.y,
3505 dragEntry.isExiting);
3506 break;
3507 }
3508
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003509 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003510 case EventEntry::Type::DEVICE_RESET:
3511 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003512 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003513 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003514 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003515 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516 }
3517
3518 // Check the result.
3519 if (status) {
3520 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003521 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003523 "This is unexpected because the wait queue is empty, so the pipe "
3524 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003525 "event to it, status=%s(%d)",
3526 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3527 status);
Harry Cutts33476232023-01-30 19:57:29 +00003528 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529 } else {
3530 // Pipe is full and we are waiting for the app to finish process some events
3531 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003532 if (DEBUG_DISPATCH_CYCLE) {
3533 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3534 "waiting for the application to catch up",
3535 connection->getInputChannelName().c_str());
3536 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003537 }
3538 } else {
3539 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003540 "status=%s(%d)",
3541 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3542 status);
Harry Cutts33476232023-01-30 19:57:29 +00003543 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003544 }
3545 return;
3546 }
3547
3548 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003549 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3550 connection->outboundQueue.end(),
3551 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003552 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003553 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003554 if (connection->responsive) {
3555 mAnrTracker.insert(dispatchEntry->timeoutTime,
3556 connection->inputChannel->getConnectionToken());
3557 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003558 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559 }
3560}
3561
chaviw09c8d2d2020-08-24 15:48:26 -07003562std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3563 size_t size;
3564 switch (event.type) {
3565 case VerifiedInputEvent::Type::KEY: {
3566 size = sizeof(VerifiedKeyEvent);
3567 break;
3568 }
3569 case VerifiedInputEvent::Type::MOTION: {
3570 size = sizeof(VerifiedMotionEvent);
3571 break;
3572 }
3573 }
3574 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3575 return mHmacKeyManager.sign(start, size);
3576}
3577
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003578const std::array<uint8_t, 32> InputDispatcher::getSignature(
3579 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003580 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3581 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003582 // Only sign events up and down events as the purely move events
3583 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003584 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003585 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003586
3587 VerifiedMotionEvent verifiedEvent =
3588 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3589 verifiedEvent.actionMasked = actionMasked;
3590 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3591 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003592}
3593
3594const std::array<uint8_t, 32> InputDispatcher::getSignature(
3595 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3596 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3597 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3598 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003599 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003600}
3601
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003603 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003604 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003605 if (DEBUG_DISPATCH_CYCLE) {
3606 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3607 connection->getInputChannelName().c_str(), seq, toString(handled));
3608 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003610 if (connection->status == Connection::Status::BROKEN ||
3611 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612 return;
3613 }
3614
3615 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003616 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3617 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3618 };
3619 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620}
3621
3622void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003623 const sp<Connection>& connection,
3624 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003625 if (DEBUG_DISPATCH_CYCLE) {
3626 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3627 connection->getInputChannelName().c_str(), toString(notify));
3628 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629
3630 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003631 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003632 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003633 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003634 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003635
3636 // The connection appears to be unrecoverably broken.
3637 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003638 if (connection->status == Connection::Status::NORMAL) {
3639 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003640
3641 if (notify) {
3642 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003643 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3644 connection->getInputChannelName().c_str());
3645
3646 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003647 scoped_unlock unlock(mLock);
3648 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3649 };
3650 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003651 }
3652 }
3653}
3654
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003655void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3656 while (!queue.empty()) {
3657 DispatchEntry* dispatchEntry = queue.front();
3658 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003659 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003660 }
3661}
3662
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003663void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003665 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666 }
3667 delete dispatchEntry;
3668}
3669
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003670int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3671 std::scoped_lock _l(mLock);
3672 sp<Connection> connection = getConnectionLocked(connectionToken);
3673 if (connection == nullptr) {
3674 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3675 connectionToken.get(), events);
3676 return 0; // remove the callback
3677 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003679 bool notify;
3680 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3681 if (!(events & ALOOPER_EVENT_INPUT)) {
3682 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3683 "events=0x%x",
3684 connection->getInputChannelName().c_str(), events);
3685 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003686 }
3687
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003688 nsecs_t currentTime = now();
3689 bool gotOne = false;
3690 status_t status = OK;
3691 for (;;) {
3692 Result<InputPublisher::ConsumerResponse> result =
3693 connection->inputPublisher.receiveConsumerResponse();
3694 if (!result.ok()) {
3695 status = result.error().code();
3696 break;
3697 }
3698
3699 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3700 const InputPublisher::Finished& finish =
3701 std::get<InputPublisher::Finished>(*result);
3702 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3703 finish.consumeTime);
3704 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003705 if (shouldReportMetricsForConnection(*connection)) {
3706 const InputPublisher::Timeline& timeline =
3707 std::get<InputPublisher::Timeline>(*result);
3708 mLatencyTracker
3709 .trackGraphicsLatency(timeline.inputEventId,
3710 connection->inputChannel->getConnectionToken(),
3711 std::move(timeline.graphicsTimeline));
3712 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003713 }
3714 gotOne = true;
3715 }
3716 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003717 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003718 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003719 return 1;
3720 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003721 }
3722
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003723 notify = status != DEAD_OBJECT || !connection->monitor;
3724 if (notify) {
3725 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3726 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3727 status);
3728 }
3729 } else {
3730 // Monitor channels are never explicitly unregistered.
3731 // We do it automatically when the remote endpoint is closed so don't warn about them.
3732 const bool stillHaveWindowHandle =
3733 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3734 notify = !connection->monitor && stillHaveWindowHandle;
3735 if (notify) {
3736 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3737 connection->getInputChannelName().c_str(), events);
3738 }
3739 }
3740
3741 // Remove the channel.
3742 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3743 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744}
3745
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003746void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003747 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003748 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003749 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003750 }
3751}
3752
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003753void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003754 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003755 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003756 for (const Monitor& monitor : monitors) {
3757 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003758 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003759 }
3760}
3761
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003763 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003764 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003765 if (connection == nullptr) {
3766 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003768
3769 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770}
3771
3772void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3773 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003774 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775 return;
3776 }
3777
3778 nsecs_t currentTime = now();
3779
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003780 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003781 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003783 if (cancelationEvents.empty()) {
3784 return;
3785 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003786 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3787 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003788 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003789 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003790 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003791 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003792
Arthur Hungb3307ee2021-10-14 10:57:37 +00003793 std::string reason = std::string("reason=").append(options.reason);
3794 android_log_event_list(LOGTAG_INPUT_CANCEL)
3795 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3796
Svet Ganov5d3bc372020-01-26 23:11:07 -08003797 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003798 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003799 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3800 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003801 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003802 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003803 target.globalScaleFactor = windowInfo->globalScaleFactor;
3804 }
3805 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003806 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003807
hongzuo liu95785e22022-09-06 02:51:35 +00003808 const bool wasEmpty = connection->outboundQueue.empty();
3809
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003810 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003811 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003812 switch (cancelationEventEntry->type) {
3813 case EventEntry::Type::KEY: {
3814 logOutboundKeyDetails("cancel - ",
3815 static_cast<const KeyEntry&>(*cancelationEventEntry));
3816 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003818 case EventEntry::Type::MOTION: {
3819 logOutboundMotionDetails("cancel - ",
3820 static_cast<const MotionEntry&>(*cancelationEventEntry));
3821 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003823 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003824 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003825 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3826 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003827 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003828 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003829 break;
3830 }
3831 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003832 case EventEntry::Type::DEVICE_RESET:
3833 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003834 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003835 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003836 break;
3837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838 }
3839
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003840 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003841 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003842 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003843
hongzuo liu95785e22022-09-06 02:51:35 +00003844 // If the outbound queue was previously empty, start the dispatch cycle going.
3845 if (wasEmpty && !connection->outboundQueue.empty()) {
3846 startDispatchCycleLocked(currentTime, connection);
3847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848}
3849
Svet Ganov5d3bc372020-01-26 23:11:07 -08003850void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Arthur Hungc539dbb2022-12-08 07:45:36 +00003851 const nsecs_t downTime, const sp<Connection>& connection,
3852 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003853 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003854 return;
3855 }
3856
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003857 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003858 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003859
3860 if (downEvents.empty()) {
3861 return;
3862 }
3863
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003864 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003865 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3866 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003867 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003868
3869 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003870 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003871 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3872 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003873 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003874 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003875 target.globalScaleFactor = windowInfo->globalScaleFactor;
3876 }
3877 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00003878 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003879
hongzuo liu95785e22022-09-06 02:51:35 +00003880 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003881 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003882 switch (downEventEntry->type) {
3883 case EventEntry::Type::MOTION: {
3884 logOutboundMotionDetails("down - ",
3885 static_cast<const MotionEntry&>(*downEventEntry));
3886 break;
3887 }
3888
3889 case EventEntry::Type::KEY:
3890 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003891 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003892 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003893 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003894 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003895 case EventEntry::Type::SENSOR:
3896 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003897 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003898 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003899 break;
3900 }
3901 }
3902
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003903 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003904 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003905 }
3906
hongzuo liu95785e22022-09-06 02:51:35 +00003907 // If the outbound queue was previously empty, start the dispatch cycle going.
3908 if (wasEmpty && !connection->outboundQueue.empty()) {
3909 startDispatchCycleLocked(downTime, connection);
3910 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003911}
3912
Arthur Hungc539dbb2022-12-08 07:45:36 +00003913void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
3914 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
3915 if (windowHandle != nullptr) {
3916 sp<Connection> wallpaperConnection = getConnectionLocked(windowHandle->getToken());
3917 if (wallpaperConnection != nullptr) {
3918 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
3919 }
3920 }
3921}
3922
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003923std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003924 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
3925 nsecs_t splitDownTime) {
3926 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927
3928 uint32_t splitPointerIndexMap[MAX_POINTERS];
3929 PointerProperties splitPointerProperties[MAX_POINTERS];
3930 PointerCoords splitPointerCoords[MAX_POINTERS];
3931
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003932 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003933 uint32_t splitPointerCount = 0;
3934
3935 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003936 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003938 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003940 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003941 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3942 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3943 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003944 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003945 splitPointerCount += 1;
3946 }
3947 }
3948
3949 if (splitPointerCount != pointerIds.count()) {
3950 // This is bad. We are missing some of the pointers that we expected to deliver.
3951 // Most likely this indicates that we received an ACTION_MOVE events that has
3952 // different pointer ids than we expected based on the previous ACTION_DOWN
3953 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3954 // in this way.
3955 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003956 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003957 "a broken sequence of pointer ids from the input device: %s",
3958 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07003959 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960 }
3961
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003962 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003964 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3965 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3967 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003968 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003970 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971 if (pointerIds.count() == 1) {
3972 // The first/last pointer went down/up.
3973 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003974 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003975 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3976 ? AMOTION_EVENT_ACTION_CANCEL
3977 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978 } else {
3979 // A secondary pointer went down/up.
3980 uint32_t splitPointerIndex = 0;
3981 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3982 splitPointerIndex += 1;
3983 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003984 action = maskedAction |
3985 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986 }
3987 } else {
3988 // An unrelated pointer changed.
3989 action = AMOTION_EVENT_ACTION_MOVE;
3990 }
3991 }
3992
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003993 if (action == AMOTION_EVENT_ACTION_DOWN) {
3994 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3995 "Split motion event has mismatching downTime and eventTime for "
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08003996 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
3997 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003998 }
3999
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004000 int32_t newId = mIdGenerator.nextId();
4001 if (ATRACE_ENABLED()) {
4002 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
4003 ") to MotionEvent(id=0x%" PRIx32 ").",
4004 originalMotionEntry.id, newId);
4005 ATRACE_NAME(message.c_str());
4006 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004007 std::unique_ptr<MotionEntry> splitMotionEntry =
4008 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4009 originalMotionEntry.deviceId, originalMotionEntry.source,
4010 originalMotionEntry.displayId,
4011 originalMotionEntry.policyFlags, action,
4012 originalMotionEntry.actionButton,
4013 originalMotionEntry.flags, originalMotionEntry.metaState,
4014 originalMotionEntry.buttonState,
4015 originalMotionEntry.classification,
4016 originalMotionEntry.edgeFlags,
4017 originalMotionEntry.xPrecision,
4018 originalMotionEntry.yPrecision,
4019 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004020 originalMotionEntry.yCursorPosition, splitDownTime,
4021 splitPointerCount, splitPointerProperties,
4022 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004023
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004024 if (originalMotionEntry.injectionState) {
4025 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004026 splitMotionEntry->injectionState->refCount += 1;
4027 }
4028
4029 return splitMotionEntry;
4030}
4031
4032void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004033 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004034 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
4035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004036
Antonio Kantekf16f2832021-09-28 04:39:20 +00004037 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004038 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004039 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004040
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004041 std::unique_ptr<ConfigurationChangedEntry> newEntry =
4042 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
4043 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004044 } // release lock
4045
4046 if (needWake) {
4047 mLooper->wake();
4048 }
4049}
4050
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004051/**
4052 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004053 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4054 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4055 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4056 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4057 * potentially handle the back key presses.
4058 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4059 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004060 */
4061void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004062 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004063 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4064 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004065 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004066 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004067 }
4068 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004069 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004070 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004071 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004072 keyCode = newKeyCode;
4073 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4074 }
4075 } else if (action == AKEY_EVENT_ACTION_UP) {
4076 // In order to maintain a consistent stream of up and down events, check to see if the key
4077 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4078 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004079 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004080 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004081 auto replacementIt = mReplacedKeys.find(replacement);
4082 if (replacementIt != mReplacedKeys.end()) {
4083 keyCode = replacementIt->second;
4084 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004085 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4086 }
4087 }
4088}
4089
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004091 ALOGD_IF(debugInboundEventDetails(),
4092 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4093 ", deviceId=%d, source=%s, displayId=%" PRId32
4094 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4095 "downTime=%" PRId64,
4096 args->id, args->eventTime, args->deviceId,
4097 inputEventSourceToString(args->source).c_str(), args->displayId, args->policyFlags,
4098 KeyEvent::actionToString(args->action), args->flags, KeyEvent::getLabel(args->keyCode),
4099 args->scanCode, args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100 if (!validateKeyEvent(args->action)) {
4101 return;
4102 }
4103
4104 uint32_t policyFlags = args->policyFlags;
4105 int32_t flags = args->flags;
4106 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004107 // InputDispatcher tracks and generates key repeats on behalf of
4108 // whatever notifies it, so repeatCount should always be set to 0
4109 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4111 policyFlags |= POLICY_FLAG_VIRTUAL;
4112 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4113 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114 if (policyFlags & POLICY_FLAG_FUNCTION) {
4115 metaState |= AMETA_FUNCTION_ON;
4116 }
4117
4118 policyFlags |= POLICY_FLAG_TRUSTED;
4119
Michael Wright78f24442014-08-06 15:55:28 -07004120 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004121 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004122
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004124 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08004125 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
4126 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127
Michael Wright2b3c3302018-03-02 17:19:13 +00004128 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004130 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4131 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004132 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004133 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134
Antonio Kantekf16f2832021-09-28 04:39:20 +00004135 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136 { // acquire lock
4137 mLock.lock();
4138
4139 if (shouldSendKeyToInputFilterLocked(args)) {
4140 mLock.unlock();
4141
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004142 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004143 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4144 return; // event was consumed by the filter
4145 }
4146
4147 mLock.lock();
4148 }
4149
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004150 std::unique_ptr<KeyEntry> newEntry =
4151 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4152 args->displayId, policyFlags, args->action, flags,
4153 keyCode, args->scanCode, metaState, repeatCount,
4154 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004156 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 mLock.unlock();
4158 } // release lock
4159
4160 if (needWake) {
4161 mLooper->wake();
4162 }
4163}
4164
4165bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4166 return mInputFilterEnabled;
4167}
4168
4169void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004170 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004171 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004172 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004173 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004174 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4175 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhan96282b02023-02-24 22:36:17 +00004176 args->id, args->eventTime, args->deviceId,
4177 inputEventSourceToString(args->source).c_str(), args->displayId, args->policyFlags,
4178 MotionEvent::actionToString(args->action).c_str(), args->actionButton, args->flags,
4179 args->metaState, args->buttonState, args->edgeFlags, args->xPrecision,
4180 args->yPrecision, args->xCursorPosition, args->yCursorPosition, args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004181 for (uint32_t i = 0; i < args->pointerCount; i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004182 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4183 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
4184 i, args->pointerProperties[i].id,
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07004185 ftl::enum_string(args->pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004186 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4187 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4188 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4189 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4190 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4191 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4192 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4193 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4194 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4195 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196 }
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004197
4198 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4199 args->pointerProperties)) {
4200 LOG(ERROR) << "Invalid event: " << args->dump();
4201 return;
4202 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203
4204 uint32_t policyFlags = args->policyFlags;
4205 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004206
4207 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004208 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004209 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4210 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004211 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004212 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213
Antonio Kantekf16f2832021-09-28 04:39:20 +00004214 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004215 { // acquire lock
4216 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004217 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4218 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4219 // complete the processing of the current stroke.
4220 const auto touchStateIt = mTouchStatesByDisplay.find(args->displayId);
4221 if (touchStateIt != mTouchStatesByDisplay.end()) {
4222 const TouchState& touchState = touchStateIt->second;
4223 if (touchState.deviceId == args->deviceId && touchState.isDown()) {
4224 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4225 }
4226 }
4227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228
4229 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004230 ui::Transform displayTransform;
4231 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4232 displayTransform = it->second.transform;
4233 }
4234
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235 mLock.unlock();
4236
4237 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004238 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4239 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004240 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004241 displayTransform, args->xPrecision, args->yPrecision,
4242 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004243 args->downTime, args->eventTime, args->pointerCount,
4244 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245
4246 policyFlags |= POLICY_FLAG_FILTERED;
4247 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4248 return; // event was consumed by the filter
4249 }
4250
4251 mLock.lock();
4252 }
4253
4254 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004255 std::unique_ptr<MotionEntry> newEntry =
4256 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4257 args->source, args->displayId, policyFlags,
4258 args->action, args->actionButton, args->flags,
4259 args->metaState, args->buttonState,
4260 args->classification, args->edgeFlags,
4261 args->xPrecision, args->yPrecision,
4262 args->xCursorPosition, args->yCursorPosition,
4263 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004264 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004266 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4267 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4268 !mInputFilterEnabled) {
4269 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4270 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4271 }
4272
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004273 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274 mLock.unlock();
4275 } // release lock
4276
4277 if (needWake) {
4278 mLooper->wake();
4279 }
4280}
4281
Chris Yef59a2f42020-10-16 12:55:26 -07004282void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004283 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004284 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4285 " sensorType=%s",
4286 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004287 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004288 }
Chris Yef59a2f42020-10-16 12:55:26 -07004289
Antonio Kantekf16f2832021-09-28 04:39:20 +00004290 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004291 { // acquire lock
4292 mLock.lock();
4293
4294 // Just enqueue a new sensor event.
4295 std::unique_ptr<SensorEntry> newEntry =
4296 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
Harry Cutts33476232023-01-30 19:57:29 +00004297 args->source, /* policyFlags=*/0, args->hwTimestamp,
Chris Yef59a2f42020-10-16 12:55:26 -07004298 args->sensorType, args->accuracy,
4299 args->accuracyChanged, args->values);
4300
4301 needWake = enqueueInboundEventLocked(std::move(newEntry));
4302 mLock.unlock();
4303 } // release lock
4304
4305 if (needWake) {
4306 mLooper->wake();
4307 }
4308}
4309
Chris Yefb552902021-02-03 17:18:37 -08004310void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004311 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004312 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4313 args->deviceId, args->isOn);
4314 }
Chris Yefb552902021-02-03 17:18:37 -08004315 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4316}
4317
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004319 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320}
4321
4322void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004323 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004324 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4325 "switchMask=0x%08x",
4326 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4327 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328
4329 uint32_t policyFlags = args->policyFlags;
4330 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004331 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332}
4333
4334void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004335 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004336 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4337 args->deviceId);
4338 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339
Antonio Kantekf16f2832021-09-28 04:39:20 +00004340 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004342 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004344 std::unique_ptr<DeviceResetEntry> newEntry =
4345 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4346 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347 } // release lock
4348
4349 if (needWake) {
4350 mLooper->wake();
4351 }
4352}
4353
Prabir Pradhan7e186182020-11-10 13:56:45 -08004354void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004355 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004356 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004357 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004358 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004359
Antonio Kantekf16f2832021-09-28 04:39:20 +00004360 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004361 { // acquire lock
4362 std::scoped_lock _l(mLock);
4363 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004364 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004365 needWake = enqueueInboundEventLocked(std::move(entry));
4366 } // release lock
4367
4368 if (needWake) {
4369 mLooper->wake();
4370 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004371}
4372
Prabir Pradhan5735a322022-04-11 17:23:34 +00004373InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4374 std::optional<int32_t> targetUid,
4375 InputEventInjectionSync syncMode,
4376 std::chrono::milliseconds timeout,
4377 uint32_t policyFlags) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004378 if (debugInboundEventDetails()) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004379 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4380 "policyFlags=0x%08x",
4381 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4382 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004383 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004384 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385
Prabir Pradhan5735a322022-04-11 17:23:34 +00004386 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004388 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004389 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4390 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4391 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4392 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4393 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004394 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004395 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004396 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004397 }
4398
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004399 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004401 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004402 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4403 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004404 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004405 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004406 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004407
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004408 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004409 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4410 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4411 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004412 int32_t keyCode = incomingKey.getKeyCode();
4413 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004414 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004415 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004416 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004417 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004418 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4419 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4420 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004422 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4423 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004424 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004425
4426 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4427 android::base::Timer t;
4428 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4429 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4430 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4431 std::to_string(t.duration().count()).c_str());
4432 }
4433 }
4434
4435 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004436 std::unique_ptr<KeyEntry> injectedEntry =
4437 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004438 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004439 incomingKey.getDisplayId(), policyFlags, action,
4440 flags, keyCode, incomingKey.getScanCode(), metaState,
4441 incomingKey.getRepeatCount(),
4442 incomingKey.getDownTime());
4443 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004444 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004445 }
4446
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004447 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004448 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004449 const int32_t action = motionEvent.getAction();
4450 const bool isPointerEvent =
4451 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4452 // If a pointer event has no displayId specified, inject it to the default display.
4453 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4454 ? ADISPLAY_ID_DEFAULT
4455 : event->getDisplayId();
4456 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004457 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004458 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004459 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004460 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004461 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004462 }
4463
4464 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004465 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004466 android::base::Timer t;
4467 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4468 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4469 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4470 std::to_string(t.duration().count()).c_str());
4471 }
4472 }
4473
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004474 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4475 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4476 }
4477
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004478 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004479 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4480 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004481 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004482 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4483 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004484 displayId, policyFlags, action, actionButton,
4485 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004486 motionEvent.getButtonState(),
4487 motionEvent.getClassification(),
4488 motionEvent.getEdgeFlags(),
4489 motionEvent.getXPrecision(),
4490 motionEvent.getYPrecision(),
4491 motionEvent.getRawXCursorPosition(),
4492 motionEvent.getRawYCursorPosition(),
4493 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004494 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004495 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004496 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004497 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004498 sampleEventTimes += 1;
4499 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004500 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004501 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4502 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004503 displayId, policyFlags, action, actionButton,
4504 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004505 motionEvent.getButtonState(),
4506 motionEvent.getClassification(),
4507 motionEvent.getEdgeFlags(),
4508 motionEvent.getXPrecision(),
4509 motionEvent.getYPrecision(),
4510 motionEvent.getRawXCursorPosition(),
4511 motionEvent.getRawYCursorPosition(),
4512 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004513 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004514 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004515 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4516 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004517 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004518 }
4519 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004520 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004521
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004522 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004523 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004524 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525 }
4526
Prabir Pradhan5735a322022-04-11 17:23:34 +00004527 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004528 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004529 injectionState->injectionIsAsync = true;
4530 }
4531
4532 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004533 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534
4535 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004536 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004537 if (DEBUG_INJECTION) {
4538 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4539 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004540 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004541 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004542 }
4543
4544 mLock.unlock();
4545
4546 if (needWake) {
4547 mLooper->wake();
4548 }
4549
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004550 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004551 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004552 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004554 if (syncMode == InputEventInjectionSync::NONE) {
4555 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004556 } else {
4557 for (;;) {
4558 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004559 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004560 break;
4561 }
4562
4563 nsecs_t remainingTimeout = endTime - now();
4564 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004565 if (DEBUG_INJECTION) {
4566 ALOGD("injectInputEvent - Timed out waiting for injection result "
4567 "to become available.");
4568 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004569 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570 break;
4571 }
4572
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004573 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004574 }
4575
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004576 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4577 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004578 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004579 if (DEBUG_INJECTION) {
4580 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4581 injectionState->pendingForegroundDispatches);
4582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004583 nsecs_t remainingTimeout = endTime - now();
4584 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004585 if (DEBUG_INJECTION) {
4586 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4587 "dispatches to finish.");
4588 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004589 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004590 break;
4591 }
4592
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004593 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004594 }
4595 }
4596 }
4597
4598 injectionState->release();
4599 } // release lock
4600
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004601 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004602 LOG(DEBUG) << "injectInputEvent - Finished with result "
4603 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004604 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605
4606 return injectionResult;
4607}
4608
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004609std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004610 std::array<uint8_t, 32> calculatedHmac;
4611 std::unique_ptr<VerifiedInputEvent> result;
4612 switch (event.getType()) {
4613 case AINPUT_EVENT_TYPE_KEY: {
4614 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4615 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4616 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004617 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004618 break;
4619 }
4620 case AINPUT_EVENT_TYPE_MOTION: {
4621 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4622 VerifiedMotionEvent verifiedMotionEvent =
4623 verifiedMotionEventFromMotionEvent(motionEvent);
4624 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004625 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004626 break;
4627 }
4628 default: {
4629 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4630 return nullptr;
4631 }
4632 }
4633 if (calculatedHmac == INVALID_HMAC) {
4634 return nullptr;
4635 }
tyiu1573a672023-02-21 22:38:32 +00004636 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004637 return nullptr;
4638 }
4639 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004640}
4641
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004642void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004643 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004644 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004646 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004647 LOG(DEBUG) << "Setting input event injection result to "
4648 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004649 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004651 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004652 // Log the outcome since the injector did not wait for the injection result.
4653 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004654 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004655 ALOGV("Asynchronous input event injection succeeded.");
4656 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004657 case InputEventInjectionResult::TARGET_MISMATCH:
4658 ALOGV("Asynchronous input event injection target mismatch.");
4659 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004660 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004661 ALOGW("Asynchronous input event injection failed.");
4662 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004663 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004664 ALOGW("Asynchronous input event injection timed out.");
4665 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004666 case InputEventInjectionResult::PENDING:
4667 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4668 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004669 }
4670 }
4671
4672 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004673 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004674 }
4675}
4676
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004677void InputDispatcher::transformMotionEntryForInjectionLocked(
4678 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004679 // Input injection works in the logical display coordinate space, but the input pipeline works
4680 // display space, so we need to transform the injected events accordingly.
4681 const auto it = mDisplayInfos.find(entry.displayId);
4682 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004683 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004684
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004685 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4686 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4687 const vec2 cursor =
4688 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4689 {entry.xCursorPosition, entry.yCursorPosition});
4690 entry.xCursorPosition = cursor.x;
4691 entry.yCursorPosition = cursor.y;
4692 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004693 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004694 entry.pointerCoords[i] =
4695 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4696 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004697 }
4698}
4699
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004700void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4701 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702 if (injectionState) {
4703 injectionState->pendingForegroundDispatches += 1;
4704 }
4705}
4706
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004707void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4708 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004709 if (injectionState) {
4710 injectionState->pendingForegroundDispatches -= 1;
4711
4712 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004713 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004714 }
4715 }
4716}
4717
chaviw98318de2021-05-19 16:45:23 -05004718const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004719 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004720 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004721 auto it = mWindowHandlesByDisplay.find(displayId);
4722 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004723}
4724
chaviw98318de2021-05-19 16:45:23 -05004725sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004726 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004727 if (windowHandleToken == nullptr) {
4728 return nullptr;
4729 }
4730
Arthur Hungb92218b2018-08-14 12:00:21 +08004731 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004732 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4733 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004734 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004735 return windowHandle;
4736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004737 }
4738 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004739 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740}
4741
chaviw98318de2021-05-19 16:45:23 -05004742sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4743 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004744 if (windowHandleToken == nullptr) {
4745 return nullptr;
4746 }
4747
chaviw98318de2021-05-19 16:45:23 -05004748 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004749 if (windowHandle->getToken() == windowHandleToken) {
4750 return windowHandle;
4751 }
4752 }
4753 return nullptr;
4754}
4755
chaviw98318de2021-05-19 16:45:23 -05004756sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4757 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004758 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004759 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4760 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004761 if (handle->getId() == windowHandle->getId() &&
4762 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004763 if (windowHandle->getInfo()->displayId != it.first) {
4764 ALOGE("Found window %s in display %" PRId32
4765 ", but it should belong to display %" PRId32,
4766 windowHandle->getName().c_str(), it.first,
4767 windowHandle->getInfo()->displayId);
4768 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004769 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004771 }
4772 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004773 return nullptr;
4774}
4775
chaviw98318de2021-05-19 16:45:23 -05004776sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004777 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4778 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004779}
4780
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004781ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4782 auto displayInfoIt = mDisplayInfos.find(displayId);
4783 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4784 : kIdentityTransform;
4785}
4786
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004787bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4788 const MotionEntry& motionEntry) const {
4789 const WindowInfo& info = *window->getInfo();
4790
4791 // Skip spy window targets that are not valid for targeted injection.
4792 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004793 return false;
4794 }
4795
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004796 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4797 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4798 return false;
4799 }
4800
4801 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4802 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4803 window->getName().c_str());
4804 return false;
4805 }
4806
4807 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004808 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004809 ALOGW("Not sending touch to %s because there's no corresponding connection",
4810 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004811 return false;
4812 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004813
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004814 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004815 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004816 return false;
4817 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004818
4819 // Drop events that can't be trusted due to occlusion
4820 const auto [x, y] = resolveTouchedPosition(motionEntry);
4821 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4822 if (!isTouchTrustedLocked(occlusionInfo)) {
4823 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004824 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004825 for (const auto& log : occlusionInfo.debugInfo) {
4826 ALOGD("%s", log.c_str());
4827 }
4828 }
4829 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4830 occlusionInfo.obscuringUid);
4831 return false;
4832 }
4833
4834 // Drop touch events if requested by input feature
4835 if (shouldDropInput(motionEntry, window)) {
4836 return false;
4837 }
4838
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004839 return true;
4840}
4841
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004842std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4843 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004844 auto connectionIt = mConnectionsByToken.find(token);
4845 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004846 return nullptr;
4847 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004848 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004849}
4850
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004851void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004852 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4853 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004854 // Remove all handles on a display if there are no windows left.
4855 mWindowHandlesByDisplay.erase(displayId);
4856 return;
4857 }
4858
4859 // Since we compare the pointer of input window handles across window updates, we need
4860 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004861 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4862 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4863 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004864 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004865 }
4866
chaviw98318de2021-05-19 16:45:23 -05004867 std::vector<sp<WindowInfoHandle>> newHandles;
4868 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004869 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004870 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004871 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004872 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004873 const bool canReceiveInput =
4874 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4875 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004876 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004877 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004878 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004879 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004880 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004881 }
4882
4883 if (info->displayId != displayId) {
4884 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4885 handle->getName().c_str(), displayId, info->displayId);
4886 continue;
4887 }
4888
Robert Carredd13602020-04-13 17:24:34 -07004889 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4890 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004891 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004892 oldHandle->updateFrom(handle);
4893 newHandles.push_back(oldHandle);
4894 } else {
4895 newHandles.push_back(handle);
4896 }
4897 }
4898
4899 // Insert or replace
4900 mWindowHandlesByDisplay[displayId] = newHandles;
4901}
4902
Arthur Hung72d8dc32020-03-28 00:48:39 +00004903void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004904 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004905 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004906 { // acquire lock
4907 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004908 for (const auto& [displayId, handles] : handlesPerDisplay) {
4909 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004910 }
4911 }
4912 // Wake up poll loop since it may need to make new input dispatching choices.
4913 mLooper->wake();
4914}
4915
Arthur Hungb92218b2018-08-14 12:00:21 +08004916/**
4917 * Called from InputManagerService, update window handle list by displayId that can receive input.
4918 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4919 * If set an empty list, remove all handles from the specific display.
4920 * For focused handle, check if need to change and send a cancel event to previous one.
4921 * For removed handle, check if need to send a cancel event if already in touch.
4922 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004923void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004924 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004925 if (DEBUG_FOCUS) {
4926 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004927 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004928 windowList += iwh->getName() + " ";
4929 }
4930 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932
Prabir Pradhand65552b2021-10-07 11:23:50 -07004933 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004934 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004935 const WindowInfo& info = *window->getInfo();
4936
4937 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004938 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004939 if (noInputWindow && window->getToken() != nullptr) {
4940 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4941 window->getName().c_str());
4942 window->releaseChannel();
4943 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004944
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004945 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004946 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4947 !info.inputConfig.test(
4948 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004949 "%s has feature SPY, but is not a trusted overlay.",
4950 window->getName().c_str());
4951
Prabir Pradhand65552b2021-10-07 11:23:50 -07004952 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004953 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4954 !info.inputConfig.test(
4955 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004956 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4957 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004958 }
4959
Arthur Hung72d8dc32020-03-28 00:48:39 +00004960 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004961 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004962
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004963 // Save the old windows' orientation by ID before it gets updated.
4964 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004965 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004966 oldWindowOrientations.emplace(handle->getId(),
4967 handle->getInfo()->transform.getOrientation());
4968 }
4969
chaviw98318de2021-05-19 16:45:23 -05004970 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004971
chaviw98318de2021-05-19 16:45:23 -05004972 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004973
Vishnu Nairc519ff72021-01-21 08:23:08 -08004974 std::optional<FocusResolver::FocusChanges> changes =
4975 mFocusResolver.setInputWindows(displayId, windowHandles);
4976 if (changes) {
4977 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004978 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004979
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004980 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4981 mTouchStatesByDisplay.find(displayId);
4982 if (stateIt != mTouchStatesByDisplay.end()) {
4983 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004984 for (size_t i = 0; i < state.windows.size();) {
4985 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004986 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004987 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004988 ALOGD("Touched window was removed: %s in display %" PRId32,
4989 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004990 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004991 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004992 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4993 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004994 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00004995 "touched window was removed");
4996 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004997 // Since we are about to drop the touch, cancel the events for the wallpaper as
4998 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004999 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005000 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5001 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005002 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005003 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005005 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005006 state.windows.erase(state.windows.begin() + i);
5007 } else {
5008 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005009 }
5010 }
arthurhungb89ccb02020-12-30 16:19:01 +08005011
arthurhung6d4bed92021-03-17 11:59:33 +08005012 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005013 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005014 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005015 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005016 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005017 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5018 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005019 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005020 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005021 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005022
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005023 // Determine if the orientation of any of the input windows have changed, and cancel all
5024 // pointer events if necessary.
5025 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
5026 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
5027 if (newWindowHandle != nullptr &&
5028 newWindowHandle->getInfo()->transform.getOrientation() !=
5029 oldWindowOrientations[oldWindowHandle->getId()]) {
5030 std::shared_ptr<InputChannel> inputChannel =
5031 getInputChannelLocked(newWindowHandle->getToken());
5032 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005033 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005034 "touched window's orientation changed");
5035 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005036 }
5037 }
5038 }
5039
Arthur Hung72d8dc32020-03-28 00:48:39 +00005040 // Release information for windows that are no longer present.
5041 // This ensures that unused input channels are released promptly.
5042 // Otherwise, they might stick around until the window handle is destroyed
5043 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005044 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005045 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005046 if (DEBUG_FOCUS) {
5047 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005048 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005049 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005050 }
chaviw291d88a2019-02-14 10:33:58 -08005051 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005052}
5053
5054void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005055 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005056 if (DEBUG_FOCUS) {
5057 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5058 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5059 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005060 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005061 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005062 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005063 } // release lock
5064
5065 // Wake up poll loop since it may need to make new input dispatching choices.
5066 mLooper->wake();
5067}
5068
Vishnu Nair599f1412021-06-21 10:39:58 -07005069void InputDispatcher::setFocusedApplicationLocked(
5070 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5071 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5072 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5073
5074 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5075 return; // This application is already focused. No need to wake up or change anything.
5076 }
5077
5078 // Set the new application handle.
5079 if (inputApplicationHandle != nullptr) {
5080 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5081 } else {
5082 mFocusedApplicationHandlesByDisplay.erase(displayId);
5083 }
5084
5085 // No matter what the old focused application was, stop waiting on it because it is
5086 // no longer focused.
5087 resetNoFocusedWindowTimeoutLocked();
5088}
5089
Tiger Huang721e26f2018-07-24 22:26:19 +08005090/**
5091 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5092 * the display not specified.
5093 *
5094 * We track any unreleased events for each window. If a window loses the ability to receive the
5095 * released event, we will send a cancel event to it. So when the focused display is changed, we
5096 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5097 * display. The display-specified events won't be affected.
5098 */
5099void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005100 if (DEBUG_FOCUS) {
5101 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5102 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005103 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005104 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005105
5106 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005107 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005108 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005109 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005110 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005111 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005112 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005113 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005114 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005115 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005116 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005117 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5118 }
5119 }
5120 mFocusedDisplayId = displayId;
5121
Chris Ye3c2d6f52020-08-09 10:39:48 -07005122 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005123 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005124 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005125
Vishnu Nairad321cd2020-08-20 16:40:21 -07005126 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005127 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005128 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005129 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005130 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005131 }
5132 }
5133 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005134 } // release lock
5135
5136 // Wake up poll loop since it may need to make new input dispatching choices.
5137 mLooper->wake();
5138}
5139
Michael Wrightd02c5b62014-02-10 15:10:22 -08005140void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005141 if (DEBUG_FOCUS) {
5142 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5143 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005144
5145 bool changed;
5146 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005147 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005148
5149 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5150 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005151 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005152 }
5153
5154 if (mDispatchEnabled && !enabled) {
5155 resetAndDropEverythingLocked("dispatcher is being disabled");
5156 }
5157
5158 mDispatchEnabled = enabled;
5159 mDispatchFrozen = frozen;
5160 changed = true;
5161 } else {
5162 changed = false;
5163 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005164 } // release lock
5165
5166 if (changed) {
5167 // Wake up poll loop since it may need to make new input dispatching choices.
5168 mLooper->wake();
5169 }
5170}
5171
5172void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005173 if (DEBUG_FOCUS) {
5174 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5175 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176
5177 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005178 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005179
5180 if (mInputFilterEnabled == enabled) {
5181 return;
5182 }
5183
5184 mInputFilterEnabled = enabled;
5185 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5186 } // release lock
5187
5188 // Wake up poll loop since there might be work to do to drop everything.
5189 mLooper->wake();
5190}
5191
Antonio Kanteka042c022022-07-06 16:51:07 -07005192bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5193 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005194 bool needWake = false;
5195 {
5196 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005197 ALOGD_IF(DEBUG_TOUCH_MODE,
5198 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5199 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5200 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5201 mTouchModePerDisplay.count(displayId) == 0
5202 ? "not set"
5203 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5204
Antonio Kantek15beb512022-06-13 22:35:41 +00005205 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5206 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005207 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005208 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005209 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005210 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5211 !recentWindowsAreOwnedByLocked(pid, uid)) {
5212 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5213 "window nor none of the previously interacted window",
5214 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005215 return false;
5216 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005217 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005218 mTouchModePerDisplay[displayId] = inTouchMode;
5219 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5220 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005221 needWake = enqueueInboundEventLocked(std::move(entry));
5222 } // release lock
5223
5224 if (needWake) {
5225 mLooper->wake();
5226 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005227 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005228}
5229
Antonio Kantek48710e42022-03-24 14:19:30 -07005230bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5231 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5232 if (focusedToken == nullptr) {
5233 return false;
5234 }
5235 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5236 return isWindowOwnedBy(windowHandle, pid, uid);
5237}
5238
5239bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5240 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5241 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5242 const sp<WindowInfoHandle> windowHandle =
5243 getWindowHandleLocked(connectionToken);
5244 return isWindowOwnedBy(windowHandle, pid, uid);
5245 }) != mInteractionConnectionTokens.end();
5246}
5247
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005248void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5249 if (opacity < 0 || opacity > 1) {
5250 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5251 return;
5252 }
5253
5254 std::scoped_lock lock(mLock);
5255 mMaximumObscuringOpacityForTouch = opacity;
5256}
5257
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005258std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5259InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005260 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5261 for (TouchedWindow& w : state.windows) {
5262 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005263 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005264 }
5265 }
5266 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005267 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005268}
5269
arthurhungb89ccb02020-12-30 16:19:01 +08005270bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5271 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005272 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005273 if (DEBUG_FOCUS) {
5274 ALOGD("Trivial transfer to same window.");
5275 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005276 return true;
5277 }
5278
Michael Wrightd02c5b62014-02-10 15:10:22 -08005279 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005280 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005281
Arthur Hungabbb9d82021-09-01 14:52:30 +00005282 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005283 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005284 if (state == nullptr || touchedWindow == nullptr) {
5285 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005286 return false;
5287 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005288
Arthur Hungabbb9d82021-09-01 14:52:30 +00005289 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5290 if (toWindowHandle == nullptr) {
5291 ALOGW("Cannot transfer focus because to window not found.");
5292 return false;
5293 }
5294
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005295 if (DEBUG_FOCUS) {
5296 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005297 touchedWindow->windowHandle->getName().c_str(),
5298 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005299 }
5300
Arthur Hungabbb9d82021-09-01 14:52:30 +00005301 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005302 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005303 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005304 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005305 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005306
Arthur Hungabbb9d82021-09-01 14:52:30 +00005307 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005308 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005309 ftl::Flags<InputTarget::Flags> newTargetFlags =
5310 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005311 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005312 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005313 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005314 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005315
Arthur Hungabbb9d82021-09-01 14:52:30 +00005316 // Store the dragging window.
5317 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005318 if (pointerIds.count() != 1) {
5319 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5320 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005321 return false;
5322 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005323 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005324 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005325 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005326 }
5327
Arthur Hungabbb9d82021-09-01 14:52:30 +00005328 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005329 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5330 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005331 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005332 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005333 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005334 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005335 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005336 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005337 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5338 newTargetFlags);
5339
5340 // Check if the wallpaper window should deliver the corresponding event.
5341 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5342 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005343 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005344 } // release lock
5345
5346 // Wake up poll loop since it may need to make new input dispatching choices.
5347 mLooper->wake();
5348 return true;
5349}
5350
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005351/**
5352 * Get the touched foreground window on the given display.
5353 * Return null if there are no windows touched on that display, or if more than one foreground
5354 * window is being touched.
5355 */
5356sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5357 auto stateIt = mTouchStatesByDisplay.find(displayId);
5358 if (stateIt == mTouchStatesByDisplay.end()) {
5359 ALOGI("No touch state on display %" PRId32, displayId);
5360 return nullptr;
5361 }
5362
5363 const TouchState& state = stateIt->second;
5364 sp<WindowInfoHandle> touchedForegroundWindow;
5365 // If multiple foreground windows are touched, return nullptr
5366 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005367 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005368 if (touchedForegroundWindow != nullptr) {
5369 ALOGI("Two or more foreground windows: %s and %s",
5370 touchedForegroundWindow->getName().c_str(),
5371 window.windowHandle->getName().c_str());
5372 return nullptr;
5373 }
5374 touchedForegroundWindow = window.windowHandle;
5375 }
5376 }
5377 return touchedForegroundWindow;
5378}
5379
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005380// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005381bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005382 sp<IBinder> fromToken;
5383 { // acquire lock
5384 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005385 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005386 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005387 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5388 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005389 return false;
5390 }
5391
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005392 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5393 if (from == nullptr) {
5394 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5395 return false;
5396 }
5397
5398 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005399 } // release lock
5400
5401 return transferTouchFocus(fromToken, destChannelToken);
5402}
5403
Michael Wrightd02c5b62014-02-10 15:10:22 -08005404void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005405 if (DEBUG_FOCUS) {
5406 ALOGD("Resetting and dropping all events (%s).", reason);
5407 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408
Michael Wrightfb04fd52022-11-24 22:31:11 +00005409 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410 synthesizeCancelationEventsForAllConnectionsLocked(options);
5411
5412 resetKeyRepeatLocked();
5413 releasePendingEventLocked();
5414 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005415 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005416
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005417 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005418 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005419 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005420}
5421
5422void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005423 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005424 dumpDispatchStateLocked(dump);
5425
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005426 std::istringstream stream(dump);
5427 std::string line;
5428
5429 while (std::getline(stream, line, '\n')) {
5430 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005431 }
5432}
5433
Prabir Pradhan99987712020-11-10 18:43:05 -08005434std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5435 std::string dump;
5436
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005437 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5438 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005439
5440 std::string windowName = "None";
5441 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005442 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005443 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5444 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5445 : "token has capture without window";
5446 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005447 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005448
5449 return dump;
5450}
5451
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005452void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005453 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5454 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5455 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005456 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005457
Tiger Huang721e26f2018-07-24 22:26:19 +08005458 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5459 dump += StringPrintf(INDENT "FocusedApplications:\n");
5460 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5461 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005462 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005463 const std::chrono::duration timeout =
5464 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005465 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005466 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005467 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005468 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005469 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005470 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005471 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005472
Vishnu Nairc519ff72021-01-21 08:23:08 -08005473 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005474 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005475
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005476 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005477 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005478 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005479 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5480 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005481 }
5482 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005483 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005484 }
5485
arthurhung6d4bed92021-03-17 11:59:33 +08005486 if (mDragState) {
5487 dump += StringPrintf(INDENT "DragState:\n");
5488 mDragState->dump(dump, INDENT2);
5489 }
5490
Arthur Hungb92218b2018-08-14 12:00:21 +08005491 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005492 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5493 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5494 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5495 const auto& displayInfo = it->second;
5496 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5497 displayInfo.logicalHeight);
5498 displayInfo.transform.dump(dump, "transform", INDENT4);
5499 } else {
5500 dump += INDENT2 "No DisplayInfo found!\n";
5501 }
5502
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005503 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005504 dump += INDENT2 "Windows:\n";
5505 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005506 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5507 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005508
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005509 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005510 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005511 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005512 "applicationInfo.name=%s, "
5513 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005514 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005515 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005516 windowInfo->displayId,
5517 windowInfo->inputConfig.string().c_str(),
5518 windowInfo->alpha, windowInfo->frameLeft,
5519 windowInfo->frameTop, windowInfo->frameRight,
5520 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005521 windowInfo->applicationInfo.name.c_str(),
5522 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005523 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005524 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005525 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005526 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005527 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005528 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005529 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005530 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005531 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005532 }
5533 } else {
5534 dump += INDENT2 "Windows: <none>\n";
5535 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005536 }
5537 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005538 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005539 }
5540
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005541 if (!mGlobalMonitorsByDisplay.empty()) {
5542 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5543 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005544 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005545 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005546 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005547 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005548 }
5549
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005550 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005551
5552 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005553 if (!mRecentQueue.empty()) {
5554 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005555 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005556 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005557 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005558 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005559 }
5560 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005561 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562 }
5563
5564 // Dump event currently being dispatched.
5565 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005566 dump += INDENT "PendingEvent:\n";
5567 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005568 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005569 dump += StringPrintf(", age=%" PRId64 "ms\n",
5570 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005571 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005572 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005573 }
5574
5575 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005576 if (!mInboundQueue.empty()) {
5577 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005578 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005579 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005580 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005581 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005582 }
5583 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005584 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005585 }
5586
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005587 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005588 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005589 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005590 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005591 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005592 }
5593 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005594 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005595 }
5596
Prabir Pradhancef936d2021-07-21 16:17:52 +00005597 if (!mCommandQueue.empty()) {
5598 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5599 } else {
5600 dump += INDENT "CommandQueue: <empty>\n";
5601 }
5602
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005603 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005604 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005605 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005606 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005607 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005608 connection->inputChannel->getFd().get(),
5609 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005610 connection->getWindowName().c_str(),
5611 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005612 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005613
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005614 if (!connection->outboundQueue.empty()) {
5615 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5616 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005617 dump += dumpQueue(connection->outboundQueue, currentTime);
5618
Michael Wrightd02c5b62014-02-10 15:10:22 -08005619 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005620 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005621 }
5622
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005623 if (!connection->waitQueue.empty()) {
5624 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5625 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005626 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005627 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005628 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005629 }
5630 }
5631 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005632 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005633 }
5634
5635 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005636 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5637 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005638 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005639 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005640 }
5641
Antonio Kantek15beb512022-06-13 22:35:41 +00005642 if (!mTouchModePerDisplay.empty()) {
5643 dump += INDENT "TouchModePerDisplay:\n";
5644 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5645 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5646 std::to_string(touchMode).c_str());
5647 }
5648 } else {
5649 dump += INDENT "TouchModePerDisplay: <none>\n";
5650 }
5651
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005652 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005653 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5654 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5655 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005656 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005657 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005658}
5659
Michael Wright3dd60e22019-03-27 22:06:44 +00005660void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5661 const size_t numMonitors = monitors.size();
5662 for (size_t i = 0; i < numMonitors; i++) {
5663 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005664 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005665 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5666 dump += "\n";
5667 }
5668}
5669
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005670class LooperEventCallback : public LooperCallback {
5671public:
5672 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5673 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5674
5675private:
5676 std::function<int(int events)> mCallback;
5677};
5678
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005679Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005680 if (DEBUG_CHANNEL_CREATION) {
5681 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5682 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005683
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005684 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005685 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005686 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005687
5688 if (result) {
5689 return base::Error(result) << "Failed to open input channel pair with name " << name;
5690 }
5691
Michael Wrightd02c5b62014-02-10 15:10:22 -08005692 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005693 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005694 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005695 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005696 sp<Connection> connection =
Harry Cutts33476232023-01-30 19:57:29 +00005697 sp<Connection>::make(std::move(serverChannel), /*monitor=*/false, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005698
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005699 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5700 ALOGE("Created a new connection, but the token %p is already known", token.get());
5701 }
5702 mConnectionsByToken.emplace(token, connection);
5703
5704 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5705 this, std::placeholders::_1, token);
5706
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005707 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5708 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005709 } // release lock
5710
5711 // Wake the looper because some connections have changed.
5712 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005713 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005714}
5715
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005716Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005717 const std::string& name,
5718 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005719 std::shared_ptr<InputChannel> serverChannel;
5720 std::unique_ptr<InputChannel> clientChannel;
5721 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5722 if (result) {
5723 return base::Error(result) << "Failed to open input channel pair with name " << name;
5724 }
5725
Michael Wright3dd60e22019-03-27 22:06:44 +00005726 { // acquire lock
5727 std::scoped_lock _l(mLock);
5728
5729 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005730 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5731 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005732 }
5733
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005734 sp<Connection> connection =
Harry Cutts33476232023-01-30 19:57:29 +00005735 sp<Connection>::make(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005736 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005737 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005738
5739 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5740 ALOGE("Created a new connection, but the token %p is already known", token.get());
5741 }
5742 mConnectionsByToken.emplace(token, connection);
5743 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5744 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005745
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005746 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005747
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005748 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5749 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005750 }
Garfield Tan15601662020-09-22 15:32:38 -07005751
Michael Wright3dd60e22019-03-27 22:06:44 +00005752 // Wake the looper because some connections have changed.
5753 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005754 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005755}
5756
Garfield Tan15601662020-09-22 15:32:38 -07005757status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005758 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005759 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005760
Harry Cutts33476232023-01-30 19:57:29 +00005761 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005762 if (status) {
5763 return status;
5764 }
5765 } // release lock
5766
5767 // Wake the poll loop because removing the connection may have changed the current
5768 // synchronization state.
5769 mLooper->wake();
5770 return OK;
5771}
5772
Garfield Tan15601662020-09-22 15:32:38 -07005773status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5774 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005775 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005776 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005777 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005778 return BAD_VALUE;
5779 }
5780
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005781 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005782
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005784 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005785 }
5786
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005787 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005788
5789 nsecs_t currentTime = now();
5790 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5791
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005792 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005793 return OK;
5794}
5795
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005796void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005797 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5798 auto& [displayId, monitors] = *it;
5799 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5800 return monitor.inputChannel->getConnectionToken() == connectionToken;
5801 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005802
Michael Wright3dd60e22019-03-27 22:06:44 +00005803 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005804 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005805 } else {
5806 ++it;
5807 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005808 }
5809}
5810
Michael Wright3dd60e22019-03-27 22:06:44 +00005811status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005812 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005813 return pilferPointersLocked(token);
5814}
Michael Wright3dd60e22019-03-27 22:06:44 +00005815
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005816status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005817 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5818 if (!requestingChannel) {
5819 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5820 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005821 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005822
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005823 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005824 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.none()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005825 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5826 " Ignoring.");
5827 return BAD_VALUE;
5828 }
5829
5830 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005831 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005832 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005833 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005834 "input channel stole pointer stream");
5835 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005836 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005837 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005838 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005839 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005840 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005841 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005842 if (channel != nullptr && channel->getConnectionToken() != token) {
5843 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5844 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5845 canceledWindows += channel->getName();
5846 }
5847 }
5848 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5849 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5850 canceledWindows.c_str());
5851
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005852 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005853 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005854 window.pilferedPointerIds |= window.pointerIds;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005855
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005856 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005857 return OK;
5858}
5859
Prabir Pradhan99987712020-11-10 18:43:05 -08005860void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5861 { // acquire lock
5862 std::scoped_lock _l(mLock);
5863 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005864 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005865 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5866 windowHandle != nullptr ? windowHandle->getName().c_str()
5867 : "token without window");
5868 }
5869
Vishnu Nairc519ff72021-01-21 08:23:08 -08005870 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005871 if (focusedToken != windowToken) {
5872 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5873 enabled ? "enable" : "disable");
5874 return;
5875 }
5876
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005877 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005878 ALOGW("Ignoring request to %s Pointer Capture: "
5879 "window has %s requested pointer capture.",
5880 enabled ? "enable" : "disable", enabled ? "already" : "not");
5881 return;
5882 }
5883
Christine Franksb768bb42021-11-29 12:11:31 -08005884 if (enabled) {
5885 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5886 mIneligibleDisplaysForPointerCapture.end(),
5887 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5888 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5889 return;
5890 }
5891 }
5892
Prabir Pradhan99987712020-11-10 18:43:05 -08005893 setPointerCaptureLocked(enabled);
5894 } // release lock
5895
5896 // Wake the thread to process command entries.
5897 mLooper->wake();
5898}
5899
Christine Franksb768bb42021-11-29 12:11:31 -08005900void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5901 { // acquire lock
5902 std::scoped_lock _l(mLock);
5903 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5904 if (!isEligible) {
5905 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5906 }
5907 } // release lock
5908}
5909
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005910std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5911 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005912 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005913 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005914 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005915 }
5916 }
5917 }
5918 return std::nullopt;
5919}
5920
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005921sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005922 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005923 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005924 }
5925
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005926 for (const auto& [token, connection] : mConnectionsByToken) {
5927 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005928 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005929 }
5930 }
Robert Carr4e670e52018-08-15 13:26:12 -07005931
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005932 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005933}
5934
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005935std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5936 sp<Connection> connection = getConnectionLocked(connectionToken);
5937 if (connection == nullptr) {
5938 return "<nullptr>";
5939 }
5940 return connection->getInputChannelName();
5941}
5942
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005943void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005944 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005945 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005946}
5947
Prabir Pradhancef936d2021-07-21 16:17:52 +00005948void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5949 const sp<Connection>& connection, uint32_t seq,
5950 bool handled, nsecs_t consumeTime) {
5951 // Handle post-event policy actions.
5952 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5953 if (dispatchEntryIt == connection->waitQueue.end()) {
5954 return;
5955 }
5956 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5957 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5958 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5959 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5960 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5961 }
5962 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5963 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5964 connection->inputChannel->getConnectionToken(),
5965 dispatchEntry->deliveryTime, consumeTime, finishTime);
5966 }
5967
5968 bool restartEvent;
5969 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5970 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5971 restartEvent =
5972 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5973 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5974 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5975 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5976 handled);
5977 } else {
5978 restartEvent = false;
5979 }
5980
5981 // Dequeue the event and start the next cycle.
5982 // Because the lock might have been released, it is possible that the
5983 // contents of the wait queue to have been drained, so we need to double-check
5984 // a few things.
5985 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5986 if (dispatchEntryIt != connection->waitQueue.end()) {
5987 dispatchEntry = *dispatchEntryIt;
5988 connection->waitQueue.erase(dispatchEntryIt);
5989 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5990 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5991 if (!connection->responsive) {
5992 connection->responsive = isConnectionResponsive(*connection);
5993 if (connection->responsive) {
5994 // The connection was unresponsive, and now it's responsive.
5995 processConnectionResponsiveLocked(*connection);
5996 }
5997 }
5998 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005999 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006000 connection->outboundQueue.push_front(dispatchEntry);
6001 traceOutboundQueueLength(*connection);
6002 } else {
6003 releaseDispatchEntry(dispatchEntry);
6004 }
6005 }
6006
6007 // Start the next dispatch cycle for this connection.
6008 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006009}
6010
Prabir Pradhancef936d2021-07-21 16:17:52 +00006011void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6012 const sp<IBinder>& newToken) {
6013 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6014 scoped_unlock unlock(mLock);
6015 mPolicy->notifyFocusChanged(oldToken, newToken);
6016 };
6017 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006018}
6019
Prabir Pradhancef936d2021-07-21 16:17:52 +00006020void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6021 auto command = [this, token, x, y]() REQUIRES(mLock) {
6022 scoped_unlock unlock(mLock);
6023 mPolicy->notifyDropWindow(token, x, y);
6024 };
6025 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006026}
6027
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006028void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
6029 if (connection == nullptr) {
6030 LOG_ALWAYS_FATAL("Caller must check for nullness");
6031 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006032 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6033 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006034 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006035 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006036 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006037 return;
6038 }
6039 /**
6040 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6041 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6042 * has changed. This could cause newer entries to time out before the already dispatched
6043 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6044 * processes the events linearly. So providing information about the oldest entry seems to be
6045 * most useful.
6046 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006047 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006048 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6049 std::string reason =
6050 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006051 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006052 ns2ms(currentWait),
6053 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006054 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006055 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006056
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006057 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6058
6059 // Stop waking up for events on this connection, it is already unresponsive
6060 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006061}
6062
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006063void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6064 std::string reason =
6065 StringPrintf("%s does not have a focused window", application->getName().c_str());
6066 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006067
Prabir Pradhancef936d2021-07-21 16:17:52 +00006068 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
6069 scoped_unlock unlock(mLock);
6070 mPolicy->notifyNoFocusedWindowAnr(application);
6071 };
6072 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006073}
6074
chaviw98318de2021-05-19 16:45:23 -05006075void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006076 const std::string& reason) {
6077 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6078 updateLastAnrStateLocked(windowLabel, reason);
6079}
6080
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006081void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6082 const std::string& reason) {
6083 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006084 updateLastAnrStateLocked(windowLabel, reason);
6085}
6086
6087void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6088 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006089 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006090 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006091 struct tm tm;
6092 localtime_r(&t, &tm);
6093 char timestr[64];
6094 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006095 mLastAnrState.clear();
6096 mLastAnrState += INDENT "ANR:\n";
6097 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006098 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6099 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006100 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006101}
6102
Prabir Pradhancef936d2021-07-21 16:17:52 +00006103void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6104 KeyEntry& entry) {
6105 const KeyEvent event = createKeyEvent(entry);
6106 nsecs_t delay = 0;
6107 { // release lock
6108 scoped_unlock unlock(mLock);
6109 android::base::Timer t;
6110 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
6111 entry.policyFlags);
6112 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6113 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6114 std::to_string(t.duration().count()).c_str());
6115 }
6116 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006117
6118 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006119 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006120 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006121 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006122 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006123 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006124 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006125 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006126}
6127
Prabir Pradhancef936d2021-07-21 16:17:52 +00006128void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006129 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006130 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006131 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006132 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006133 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006134 };
6135 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006136}
6137
Prabir Pradhanedd96402022-02-15 01:46:16 -08006138void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6139 std::optional<int32_t> pid) {
6140 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006141 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006142 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006143 };
6144 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006145}
6146
6147/**
6148 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6149 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6150 * command entry to the command queue.
6151 */
6152void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6153 std::string reason) {
6154 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006155 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006156 if (connection.monitor) {
6157 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6158 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006159 pid = findMonitorPidByTokenLocked(connectionToken);
6160 } else {
6161 // The connection is a window
6162 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6163 reason.c_str());
6164 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6165 if (handle != nullptr) {
6166 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006167 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006168 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006169 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006170}
6171
6172/**
6173 * Tell the policy that a connection has become responsive so that it can stop ANR.
6174 */
6175void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6176 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006177 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006178 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006179 pid = findMonitorPidByTokenLocked(connectionToken);
6180 } else {
6181 // The connection is a window
6182 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6183 if (handle != nullptr) {
6184 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006185 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006186 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006187 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006188}
6189
Prabir Pradhancef936d2021-07-21 16:17:52 +00006190bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006191 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006192 KeyEntry& keyEntry, bool handled) {
6193 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006194 if (!handled) {
6195 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006196 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006197 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006198 return false;
6199 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006200
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006201 // Get the fallback key state.
6202 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006203 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006204 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006205 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006206 connection->inputState.removeFallbackKey(originalKeyCode);
6207 }
6208
6209 if (handled || !dispatchEntry->hasForegroundTarget()) {
6210 // If the application handles the original key for which we previously
6211 // generated a fallback or if the window is not a foreground window,
6212 // then cancel the associated fallback key, if any.
6213 if (fallbackKeyCode != -1) {
6214 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006215 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6216 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6217 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6218 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6219 keyEntry.policyFlags);
6220 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006221 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006222 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006223
6224 mLock.unlock();
6225
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006226 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006227 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006228
6229 mLock.lock();
6230
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006231 // Cancel the fallback key.
6232 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006233 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006234 "application handled the original non-fallback key "
6235 "or is no longer a foreground target, "
6236 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006237 options.keyCode = fallbackKeyCode;
6238 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006239 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006240 connection->inputState.removeFallbackKey(originalKeyCode);
6241 }
6242 } else {
6243 // If the application did not handle a non-fallback key, first check
6244 // that we are in a good state to perform unhandled key event processing
6245 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006246 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006247 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006248 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6249 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6250 "since this is not an initial down. "
6251 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6252 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6253 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006254 return false;
6255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006256
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006257 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006258 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6259 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6260 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6261 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6262 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006263 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006264
6265 mLock.unlock();
6266
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006267 bool fallback =
6268 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006269 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006270
6271 mLock.lock();
6272
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006273 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006274 connection->inputState.removeFallbackKey(originalKeyCode);
6275 return false;
6276 }
6277
6278 // Latch the fallback keycode for this key on an initial down.
6279 // The fallback keycode cannot change at any other point in the lifecycle.
6280 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006281 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006282 fallbackKeyCode = event.getKeyCode();
6283 } else {
6284 fallbackKeyCode = AKEYCODE_UNKNOWN;
6285 }
6286 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6287 }
6288
6289 ALOG_ASSERT(fallbackKeyCode != -1);
6290
6291 // Cancel the fallback key if the policy decides not to send it anymore.
6292 // We will continue to dispatch the key to the policy but we will no
6293 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006294 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6295 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006296 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6297 if (fallback) {
6298 ALOGD("Unhandled key event: Policy requested to send key %d"
6299 "as a fallback for %d, but on the DOWN it had requested "
6300 "to send %d instead. Fallback canceled.",
6301 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6302 } else {
6303 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6304 "but on the DOWN it had requested to send %d. "
6305 "Fallback canceled.",
6306 originalKeyCode, fallbackKeyCode);
6307 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006308 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006309
Michael Wrightfb04fd52022-11-24 22:31:11 +00006310 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006311 "canceling fallback, policy no longer desires it");
6312 options.keyCode = fallbackKeyCode;
6313 synthesizeCancelationEventsForConnectionLocked(connection, options);
6314
6315 fallback = false;
6316 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006317 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006318 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006319 }
6320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006321
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006322 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6323 {
6324 std::string msg;
6325 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6326 connection->inputState.getFallbackKeys();
6327 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6328 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6329 }
6330 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6331 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006332 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006333 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006334
6335 if (fallback) {
6336 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006337 keyEntry.eventTime = event.getEventTime();
6338 keyEntry.deviceId = event.getDeviceId();
6339 keyEntry.source = event.getSource();
6340 keyEntry.displayId = event.getDisplayId();
6341 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6342 keyEntry.keyCode = fallbackKeyCode;
6343 keyEntry.scanCode = event.getScanCode();
6344 keyEntry.metaState = event.getMetaState();
6345 keyEntry.repeatCount = event.getRepeatCount();
6346 keyEntry.downTime = event.getDownTime();
6347 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006348
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006349 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6350 ALOGD("Unhandled key event: Dispatching fallback key. "
6351 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6352 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6353 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006354 return true; // restart the event
6355 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006356 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6357 ALOGD("Unhandled key event: No fallback key.");
6358 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006359
6360 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006361 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006362 }
6363 }
6364 return false;
6365}
6366
Prabir Pradhancef936d2021-07-21 16:17:52 +00006367bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006368 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006369 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006370 return false;
6371}
6372
Michael Wrightd02c5b62014-02-10 15:10:22 -08006373void InputDispatcher::traceInboundQueueLengthLocked() {
6374 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006375 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006376 }
6377}
6378
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006379void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006380 if (ATRACE_ENABLED()) {
6381 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006382 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6383 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006384 }
6385}
6386
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006387void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006388 if (ATRACE_ENABLED()) {
6389 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006390 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6391 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006392 }
6393}
6394
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006395void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006396 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006397
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006398 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006399 dumpDispatchStateLocked(dump);
6400
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006401 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006402 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006403 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006404 }
6405}
6406
6407void InputDispatcher::monitor() {
6408 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006409 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006410 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006411 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006412}
6413
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006414/**
6415 * Wake up the dispatcher and wait until it processes all events and commands.
6416 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6417 * this method can be safely called from any thread, as long as you've ensured that
6418 * the work you are interested in completing has already been queued.
6419 */
6420bool InputDispatcher::waitForIdle() {
6421 /**
6422 * Timeout should represent the longest possible time that a device might spend processing
6423 * events and commands.
6424 */
6425 constexpr std::chrono::duration TIMEOUT = 100ms;
6426 std::unique_lock lock(mLock);
6427 mLooper->wake();
6428 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6429 return result == std::cv_status::no_timeout;
6430}
6431
Vishnu Naire798b472020-07-23 13:52:21 -07006432/**
6433 * Sets focus to the window identified by the token. This must be called
6434 * after updating any input window handles.
6435 *
6436 * Params:
6437 * request.token - input channel token used to identify the window that should gain focus.
6438 * request.focusedToken - the token that the caller expects currently to be focused. If the
6439 * specified token does not match the currently focused window, this request will be dropped.
6440 * If the specified focused token matches the currently focused window, the call will succeed.
6441 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6442 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6443 * when requesting the focus change. This determines which request gets
6444 * precedence if there is a focus change request from another source such as pointer down.
6445 */
Vishnu Nair958da932020-08-21 17:12:37 -07006446void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6447 { // acquire lock
6448 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006449 std::optional<FocusResolver::FocusChanges> changes =
6450 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6451 if (changes) {
6452 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006453 }
6454 } // release lock
6455 // Wake up poll loop since it may need to make new input dispatching choices.
6456 mLooper->wake();
6457}
6458
Vishnu Nairc519ff72021-01-21 08:23:08 -08006459void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6460 if (changes.oldFocus) {
6461 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006462 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006463 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006464 "focus left window");
6465 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006466 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006467 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006468 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006469 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006470 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006471 }
6472
Prabir Pradhan99987712020-11-10 18:43:05 -08006473 // If a window has pointer capture, then it must have focus. We need to ensure that this
6474 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6475 // If the window loses focus before it loses pointer capture, then the window can be in a state
6476 // where it has pointer capture but not focus, violating the contract. Therefore we must
6477 // dispatch the pointer capture event before the focus event. Since focus events are added to
6478 // the front of the queue (above), we add the pointer capture event to the front of the queue
6479 // after the focus events are added. This ensures the pointer capture event ends up at the
6480 // front.
6481 disablePointerCaptureForcedLocked();
6482
Vishnu Nairc519ff72021-01-21 08:23:08 -08006483 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006484 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006485 }
6486}
Vishnu Nair958da932020-08-21 17:12:37 -07006487
Prabir Pradhan99987712020-11-10 18:43:05 -08006488void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006489 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006490 return;
6491 }
6492
6493 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6494
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006495 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006496 setPointerCaptureLocked(false);
6497 }
6498
6499 if (!mWindowTokenWithPointerCapture) {
6500 // No need to send capture changes because no window has capture.
6501 return;
6502 }
6503
6504 if (mPendingEvent != nullptr) {
6505 // Move the pending event to the front of the queue. This will give the chance
6506 // for the pending event to be dropped if it is a captured event.
6507 mInboundQueue.push_front(mPendingEvent);
6508 mPendingEvent = nullptr;
6509 }
6510
6511 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006512 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006513 mInboundQueue.push_front(std::move(entry));
6514}
6515
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006516void InputDispatcher::setPointerCaptureLocked(bool enable) {
6517 mCurrentPointerCaptureRequest.enable = enable;
6518 mCurrentPointerCaptureRequest.seq++;
6519 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006520 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006521 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006522 };
6523 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006524}
6525
Vishnu Nair599f1412021-06-21 10:39:58 -07006526void InputDispatcher::displayRemoved(int32_t displayId) {
6527 { // acquire lock
6528 std::scoped_lock _l(mLock);
6529 // Set an empty list to remove all handles from the specific display.
6530 setInputWindowsLocked(/* window handles */ {}, displayId);
6531 setFocusedApplicationLocked(displayId, nullptr);
6532 // Call focus resolver to clean up stale requests. This must be called after input windows
6533 // have been removed for the removed display.
6534 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006535 // Reset pointer capture eligibility, regardless of previous state.
6536 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006537 // Remove the associated touch mode state.
6538 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006539 } // release lock
6540
6541 // Wake up poll loop since it may need to make new input dispatching choices.
6542 mLooper->wake();
6543}
6544
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006545void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6546 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006547 // The listener sends the windows as a flattened array. Separate the windows by display for
6548 // more convenient parsing.
6549 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006550 for (const auto& info : windowInfos) {
6551 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006552 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006553 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006554
6555 { // acquire lock
6556 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006557
6558 // Ensure that we have an entry created for all existing displays so that if a displayId has
6559 // no windows, we can tell that the windows were removed from the display.
6560 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6561 handlesPerDisplay[displayId];
6562 }
6563
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006564 mDisplayInfos.clear();
6565 for (const auto& displayInfo : displayInfos) {
6566 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6567 }
6568
6569 for (const auto& [displayId, handles] : handlesPerDisplay) {
6570 setInputWindowsLocked(handles, displayId);
6571 }
6572 }
6573 // Wake up poll loop since it may need to make new input dispatching choices.
6574 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006575}
6576
Vishnu Nair062a8672021-09-03 16:07:44 -07006577bool InputDispatcher::shouldDropInput(
6578 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006579 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6580 (windowHandle->getInfo()->inputConfig.test(
6581 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006582 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006583 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6584 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006585 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006586 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006587 windowHandle->getInfo()->displayId);
6588 return true;
6589 }
6590 return false;
6591}
6592
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006593void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6594 const std::vector<gui::WindowInfo>& windowInfos,
6595 const std::vector<DisplayInfo>& displayInfos) {
6596 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6597}
6598
Arthur Hungdfd528e2021-12-08 13:23:04 +00006599void InputDispatcher::cancelCurrentTouch() {
6600 {
6601 std::scoped_lock _l(mLock);
6602 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006603 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006604 "cancel current touch");
6605 synthesizeCancelationEventsForAllConnectionsLocked(options);
6606
6607 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006608 }
6609 // Wake up poll loop since there might be work to do.
6610 mLooper->wake();
6611}
6612
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006613void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6614 std::scoped_lock _l(mLock);
6615 mMonitorDispatchingTimeout = timeout;
6616}
6617
Arthur Hungc539dbb2022-12-08 07:45:36 +00006618void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6619 const sp<WindowInfoHandle>& oldWindowHandle,
6620 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006621 TouchState& state, int32_t pointerId,
6622 std::vector<InputTarget>& targets) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006623 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6624 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006625 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6626 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6627 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6628 newWindowHandle->getInfo()->inputConfig.test(
6629 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6630 const sp<WindowInfoHandle> oldWallpaper =
6631 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6632 const sp<WindowInfoHandle> newWallpaper =
6633 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6634 if (oldWallpaper == newWallpaper) {
6635 return;
6636 }
6637
6638 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006639 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6640 addWindowTargetLocked(oldWallpaper,
6641 oldTouchedWindow.targetFlags |
6642 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6643 pointerIds, oldTouchedWindow.firstDownTimeInTarget, targets);
6644 state.removeTouchedPointerFromWindow(pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006645 }
6646
6647 if (newWallpaper != nullptr) {
6648 state.addOrUpdateWindow(newWallpaper,
6649 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6650 InputTarget::Flags::WINDOW_IS_OBSCURED |
6651 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6652 pointerIds);
6653 }
6654}
6655
6656void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6657 ftl::Flags<InputTarget::Flags> newTargetFlags,
6658 const sp<WindowInfoHandle> fromWindowHandle,
6659 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006660 TouchState& state,
6661 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006662 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6663 fromWindowHandle->getInfo()->inputConfig.test(
6664 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6665 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6666 toWindowHandle->getInfo()->inputConfig.test(
6667 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6668
6669 const sp<WindowInfoHandle> oldWallpaper =
6670 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6671 const sp<WindowInfoHandle> newWallpaper =
6672 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6673 if (oldWallpaper == newWallpaper) {
6674 return;
6675 }
6676
6677 if (oldWallpaper != nullptr) {
6678 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6679 "transferring touch focus to another window");
6680 state.removeWindowByToken(oldWallpaper->getToken());
6681 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6682 }
6683
6684 if (newWallpaper != nullptr) {
6685 nsecs_t downTimeInTarget = now();
6686 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6687 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6688 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6689 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6690 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
6691 sp<Connection> wallpaperConnection = getConnectionLocked(newWallpaper->getToken());
6692 if (wallpaperConnection != nullptr) {
6693 sp<Connection> toConnection = getConnectionLocked(toWindowHandle->getToken());
6694 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6695 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6696 wallpaperFlags);
6697 }
6698 }
6699}
6700
6701sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6702 const sp<WindowInfoHandle>& windowHandle) const {
6703 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6704 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6705 bool foundWindow = false;
6706 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6707 if (!foundWindow && otherHandle != windowHandle) {
6708 continue;
6709 }
6710 if (windowHandle == otherHandle) {
6711 foundWindow = true;
6712 continue;
6713 }
6714
6715 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6716 return otherHandle;
6717 }
6718 }
6719 return nullptr;
6720}
6721
Garfield Tane84e6f92019-08-29 17:28:41 -07006722} // namespace android::inputdispatcher