blob: 0f7991ae09d84a9d29e1937a2335a99aee136e90 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Siarhei Vishniakoud010b012023-01-18 15:00:53 -080023#include <android-base/logging.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080024#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080025#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050026#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070027#include <binder/Binder.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080028#include <ftl/enum.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070029#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050030#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070031#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080032#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080033#include <input/PrintTools.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070034#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010035#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070036#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080037
Michael Wright44753b12020-07-08 13:48:11 +010038#include <cerrno>
39#include <cinttypes>
40#include <climits>
41#include <cstddef>
42#include <ctime>
43#include <queue>
44#include <sstream>
45
46#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000047#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070048#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010049
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#define INDENT " "
51#define INDENT2 " "
52#define INDENT3 " "
53#define INDENT4 " "
54
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080055using namespace android::ftl::flag_operators;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080056using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000057using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080058using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070059using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050060using android::gui::FocusRequest;
61using android::gui::TouchOcclusionMode;
62using android::gui::WindowInfo;
63using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080064using android::os::InputEventInjectionResult;
65using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080066
Garfield Tane84e6f92019-08-29 17:28:41 -070067namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080068
Prabir Pradhancef936d2021-07-21 16:17:52 +000069namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000070// Temporarily releases a held mutex for the lifetime of the instance.
71// Named to match std::scoped_lock
72class scoped_unlock {
73public:
74 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
75 ~scoped_unlock() { mMutex.lock(); }
76
77private:
78 std::mutex& mMutex;
79};
80
Michael Wrightd02c5b62014-02-10 15:10:22 -080081// Default input dispatching timeout if there is no focused application or paused window
82// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080083const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
84 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
85 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080086
87// Amount of time to allow for all pending events to be processed when an app switch
88// key is on the way. This is used to preempt input dispatch and drop input events
89// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000090constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080092const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080093
Michael Wrightd02c5b62014-02-10 15:10:22 -080094// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000095constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
96
97// Log a warning when an interception call takes longer than this to process.
98constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700100// Additional key latency in case a connection is still processing some motion events.
101// This will help with the case when a user touched a button that opens a new window,
102// and gives us the chance to dispatch the key to this new window.
103constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
104
Michael Wrightd02c5b62014-02-10 15:10:22 -0800105// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000106constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
107
Antonio Kantekea47acb2021-12-23 12:41:25 -0800108// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000109constexpr int LOGTAG_INPUT_INTERACTION = 62000;
110constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000111constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000112
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000113const ui::Transform kIdentityTransform;
114
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000115inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800116 return systemTime(SYSTEM_TIME_MONOTONIC);
117}
118
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000119inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800120 return value ? "true" : "false";
121}
122
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000123inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000124 if (binder == nullptr) {
125 return "<null>";
126 }
127 return StringPrintf("%p", binder.get());
128}
129
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000130inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700131 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
132 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800133}
134
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000135bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800136 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700137 case AKEY_EVENT_ACTION_DOWN:
138 case AKEY_EVENT_ACTION_UP:
139 return true;
140 default:
141 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800142 }
143}
144
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000145bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700146 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800147 ALOGE("Key event has invalid action code 0x%x", action);
148 return false;
149 }
150 return true;
151}
152
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000153bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800154 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700155 case AMOTION_EVENT_ACTION_DOWN:
156 case AMOTION_EVENT_ACTION_UP:
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800157 return pointerCount == 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700158 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700159 case AMOTION_EVENT_ACTION_HOVER_ENTER:
160 case AMOTION_EVENT_ACTION_HOVER_MOVE:
161 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800162 return pointerCount >= 1;
163 case AMOTION_EVENT_ACTION_CANCEL:
164 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700165 case AMOTION_EVENT_ACTION_SCROLL:
166 return true;
167 case AMOTION_EVENT_ACTION_POINTER_DOWN:
168 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800169 const int32_t index = MotionEvent::getActionIndex(action);
170 return index >= 0 && index < pointerCount && pointerCount > 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700171 }
172 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
173 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
174 return actionButton != 0;
175 default:
176 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177 }
178}
179
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000180int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500181 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
182}
183
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000184bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
185 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700186 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800187 ALOGE("Motion event has invalid action code 0x%x", action);
188 return false;
189 }
190 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800191 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %zu.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700192 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800193 return false;
194 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800195 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800196 for (size_t i = 0; i < pointerCount; i++) {
197 int32_t id = pointerProperties[i].id;
198 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700199 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
200 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800201 return false;
202 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800203 if (pointerIdBits.test(id)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800204 ALOGE("Motion event has duplicate pointer id %d", id);
205 return false;
206 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800207 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800208 }
209 return true;
210}
211
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000212std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800213 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000214 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800215 }
216
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000217 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 bool first = true;
219 Region::const_iterator cur = region.begin();
220 Region::const_iterator const tail = region.end();
221 while (cur != tail) {
222 if (first) {
223 first = false;
224 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800225 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800227 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800228 cur++;
229 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000230 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800231}
232
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000233std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500234 constexpr size_t maxEntries = 50; // max events to print
235 constexpr size_t skipBegin = maxEntries / 2;
236 const size_t skipEnd = queue.size() - maxEntries / 2;
237 // skip from maxEntries / 2 ... size() - maxEntries/2
238 // only print from 0 .. skipBegin and then from skipEnd .. size()
239
240 std::string dump;
241 for (size_t i = 0; i < queue.size(); i++) {
242 const DispatchEntry& entry = *queue[i];
243 if (i >= skipBegin && i < skipEnd) {
244 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
245 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
246 continue;
247 }
248 dump.append(INDENT4);
249 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800250 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
251 "ms",
252 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500253 ns2ms(currentTime - entry.eventEntry->eventTime));
254 if (entry.deliveryTime != 0) {
255 // This entry was delivered, so add information on how long we've been waiting
256 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
257 }
258 dump.append("\n");
259 }
260 return dump;
261}
262
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700263/**
264 * Find the entry in std::unordered_map by key, and return it.
265 * If the entry is not found, return a default constructed entry.
266 *
267 * Useful when the entries are vectors, since an empty vector will be returned
268 * if the entry is not found.
269 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
270 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700271template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000272V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700273 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700274 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800275}
276
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000277bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700278 if (first == second) {
279 return true;
280 }
281
282 if (first == nullptr || second == nullptr) {
283 return false;
284 }
285
286 return first->getToken() == second->getToken();
287}
288
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000289bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000290 if (first == nullptr || second == nullptr) {
291 return false;
292 }
293 return first->applicationInfo.token != nullptr &&
294 first->applicationInfo.token == second->applicationInfo.token;
295}
296
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800297template <typename T>
298size_t firstMarkedBit(T set) {
299 // TODO: replace with std::countr_zero from <bit> when that's available
300 LOG_ALWAYS_FATAL_IF(set.none());
301 size_t i = 0;
302 while (!set.test(i)) {
303 i++;
304 }
305 return i;
306}
307
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800308std::unique_ptr<DispatchEntry> createDispatchEntry(
309 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
310 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700311 if (inputTarget.useDefaultPointerTransform()) {
312 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700313 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700314 inputTarget.displayTransform,
315 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000316 }
317
318 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
319 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
320
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700321 std::vector<PointerCoords> pointerCoords;
322 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000323
324 // Use the first pointer information to normalize all other pointers. This could be any pointer
325 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700326 // uses the transform for the normalized pointer.
327 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800328 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700329 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000330
331 // Iterate through all pointers in the event to normalize against the first.
332 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
333 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
334 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700335 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000336
337 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700338 // First, apply the current pointer's transform to update the coordinates into
339 // window space.
340 pointerCoords[pointerIndex].transform(currTransform);
341 // Next, apply the inverse transform of the normalized coordinates so the
342 // current coordinates are transformed into the normalized coordinate space.
343 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000344 }
345
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700346 std::unique_ptr<MotionEntry> combinedMotionEntry =
347 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
348 motionEntry.deviceId, motionEntry.source,
349 motionEntry.displayId, motionEntry.policyFlags,
350 motionEntry.action, motionEntry.actionButton,
351 motionEntry.flags, motionEntry.metaState,
352 motionEntry.buttonState, motionEntry.classification,
353 motionEntry.edgeFlags, motionEntry.xPrecision,
354 motionEntry.yPrecision, motionEntry.xCursorPosition,
355 motionEntry.yCursorPosition, motionEntry.downTime,
356 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000357 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000358
359 if (motionEntry.injectionState) {
360 combinedMotionEntry->injectionState = motionEntry.injectionState;
361 combinedMotionEntry->injectionState->refCount += 1;
362 }
363
364 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700365 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700366 firstPointerTransform, inputTarget.displayTransform,
367 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000368 return dispatchEntry;
369}
370
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000371status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
372 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700373 std::unique_ptr<InputChannel> uniqueServerChannel;
374 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
375
376 serverChannel = std::move(uniqueServerChannel);
377 return result;
378}
379
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500380template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000381bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500382 if (lhs == nullptr && rhs == nullptr) {
383 return true;
384 }
385 if (lhs == nullptr || rhs == nullptr) {
386 return false;
387 }
388 return *lhs == *rhs;
389}
390
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000391KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000392 KeyEvent event;
393 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
394 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
395 entry.repeatCount, entry.downTime, entry.eventTime);
396 return event;
397}
398
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000399bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000400 // Do not keep track of gesture monitors. They receive every event and would disproportionately
401 // affect the statistics.
402 if (connection.monitor) {
403 return false;
404 }
405 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
406 if (!connection.responsive) {
407 return false;
408 }
409 return true;
410}
411
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000412bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000413 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
414 const int32_t& inputEventId = eventEntry.id;
415 if (inputEventId != dispatchEntry.resolvedEventId) {
416 // Event was transmuted
417 return false;
418 }
419 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
420 return false;
421 }
422 // Only track latency for events that originated from hardware
423 if (eventEntry.isSynthesized()) {
424 return false;
425 }
426 const EventEntry::Type& inputEventEntryType = eventEntry.type;
427 if (inputEventEntryType == EventEntry::Type::KEY) {
428 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
429 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
430 return false;
431 }
432 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
433 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
434 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
435 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
436 return false;
437 }
438 } else {
439 // Not a key or a motion
440 return false;
441 }
442 if (!shouldReportMetricsForConnection(connection)) {
443 return false;
444 }
445 return true;
446}
447
Prabir Pradhancef936d2021-07-21 16:17:52 +0000448/**
449 * Connection is responsive if it has no events in the waitQueue that are older than the
450 * current time.
451 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000452bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000453 const nsecs_t currentTime = now();
454 for (const DispatchEntry* entry : connection.waitQueue) {
455 if (entry->timeoutTime < currentTime) {
456 return false;
457 }
458 }
459 return true;
460}
461
Antonio Kantekf16f2832021-09-28 04:39:20 +0000462// Returns true if the event type passed as argument represents a user activity.
463bool isUserActivityEvent(const EventEntry& eventEntry) {
464 switch (eventEntry.type) {
465 case EventEntry::Type::FOCUS:
466 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
467 case EventEntry::Type::DRAG:
468 case EventEntry::Type::TOUCH_MODE_CHANGED:
469 case EventEntry::Type::SENSOR:
470 case EventEntry::Type::CONFIGURATION_CHANGED:
471 return false;
472 case EventEntry::Type::DEVICE_RESET:
473 case EventEntry::Type::KEY:
474 case EventEntry::Type::MOTION:
475 return true;
476 }
477}
478
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800479// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000480bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000481 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800482 const auto inputConfig = windowInfo.inputConfig;
483 if (windowInfo.displayId != displayId ||
484 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800485 return false;
486 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700487 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800488 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800489 return false;
490 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000491
492 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
493 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
494 // the window. Points on the right and bottom edges should not be inside the window, so we need
495 // to be careful about performing a hit test when the display is rotated, since the "right" and
496 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
497 // logical display in which WM determined the bounds. Perform the hit test in the logical
498 // display space to ensure these edges are considered correctly in all orientations.
499 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
500 const auto p = displayTransform.transform(x, y);
501 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800502 return false;
503 }
504 return true;
505}
506
Prabir Pradhand65552b2021-10-07 11:23:50 -0700507bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
508 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000509 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700510}
511
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800512// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000513// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
514// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
515// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800516// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000517bool canReceiveForegroundTouches(const WindowInfo& info) {
518 // A non-touchable window can still receive touch events (e.g. in the case of
519 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
520 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
521}
522
Antonio Kantek48710e42022-03-24 14:19:30 -0700523bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
524 if (windowHandle == nullptr) {
525 return false;
526 }
527 const WindowInfo* windowInfo = windowHandle->getInfo();
528 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
529 return true;
530 }
531 return false;
532}
533
Prabir Pradhan5735a322022-04-11 17:23:34 +0000534// Checks targeted injection using the window's owner's uid.
535// Returns an empty string if an entry can be sent to the given window, or an error message if the
536// entry is a targeted injection whose uid target doesn't match the window owner.
537std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
538 const EventEntry& entry) {
539 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
540 // The event was not injected, or the injected event does not target a window.
541 return {};
542 }
543 const int32_t uid = *entry.injectionState->targetUid;
544 if (window == nullptr) {
545 return StringPrintf("No valid window target for injection into uid %d.", uid);
546 }
547 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
548 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
549 "owned by uid %d.",
550 uid, window->getName().c_str(), window->getInfo()->ownerUid);
551 }
552 return {};
553}
554
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000555std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700556 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
557 // Always dispatch mouse events to cursor position.
558 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000559 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700560 }
561
562 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000563 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
564 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700565}
566
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700567std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
568 if (eventEntry.type == EventEntry::Type::KEY) {
569 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
570 return keyEntry.downTime;
571 } else if (eventEntry.type == EventEntry::Type::MOTION) {
572 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
573 return motionEntry.downTime;
574 }
575 return std::nullopt;
576}
577
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000578/**
579 * Compare the old touch state to the new touch state, and generate the corresponding touched
580 * windows (== input targets).
581 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
582 * If the pointer just entered the new window, produce HOVER_ENTER.
583 * For pointers remaining in the window, produce HOVER_MOVE.
584 */
585std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
586 const TouchState& newTouchState,
587 const MotionEntry& entry) {
588 std::vector<TouchedWindow> out;
589 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
590 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
591 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
592 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
593 // Not a hover event - don't need to do anything
594 return out;
595 }
596
597 // We should consider all hovering pointers here. But for now, just use the first one
598 const int32_t pointerId = entry.pointerProperties[0].id;
599
600 std::set<sp<WindowInfoHandle>> oldWindows;
601 if (oldState != nullptr) {
602 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
603 }
604
605 std::set<sp<WindowInfoHandle>> newWindows =
606 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
607
608 // If the pointer is no longer in the new window set, send HOVER_EXIT.
609 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
610 if (newWindows.find(oldWindow) == newWindows.end()) {
611 TouchedWindow touchedWindow;
612 touchedWindow.windowHandle = oldWindow;
613 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800614 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000615 out.push_back(touchedWindow);
616 }
617 }
618
619 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
620 TouchedWindow touchedWindow;
621 touchedWindow.windowHandle = newWindow;
622 if (oldWindows.find(newWindow) == oldWindows.end()) {
623 // Any windows that have this pointer now, and didn't have it before, should get
624 // HOVER_ENTER
625 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
626 } else {
627 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
628 LOG_ALWAYS_FATAL_IF(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE);
629 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
630 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800631 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000632 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
633 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
634 }
635 out.push_back(touchedWindow);
636 }
637 return out;
638}
639
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800640template <typename T>
641std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
642 left.insert(left.end(), right.begin(), right.end());
643 return left;
644}
645
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000646} // namespace
647
Michael Wrightd02c5b62014-02-10 15:10:22 -0800648// --- InputDispatcher ---
649
Garfield Tan00f511d2019-06-12 16:55:40 -0700650InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800651 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
652
653InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
654 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700655 : mPolicy(policy),
656 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700657 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800658 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700659 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700660 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700661 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800662 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700663 mDispatchEnabled(false),
664 mDispatchFrozen(false),
665 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100666 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000667 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800668 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800669 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000670 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000671 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700672 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800673 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700675 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700676#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700677 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700678#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700679 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680 policy->getDispatcherConfiguration(&mConfig);
681}
682
683InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000684 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800685
Prabir Pradhancef936d2021-07-21 16:17:52 +0000686 resetKeyRepeatLocked();
687 releasePendingEventLocked();
688 drainInboundQueueLocked();
689 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800690
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000691 while (!mConnectionsByToken.empty()) {
692 sp<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000693 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800694 }
695}
696
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700697status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700698 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700699 return ALREADY_EXISTS;
700 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700701 mThread = std::make_unique<InputThread>(
702 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
703 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700704}
705
706status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700707 if (mThread && mThread->isCallingThread()) {
708 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700709 return INVALID_OPERATION;
710 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700711 mThread.reset();
712 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700713}
714
Michael Wrightd02c5b62014-02-10 15:10:22 -0800715void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700716 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800717 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800718 std::scoped_lock _l(mLock);
719 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800720
721 // Run a dispatch loop if there are no pending commands.
722 // The dispatch loop might enqueue commands to run afterwards.
723 if (!haveCommandsLocked()) {
724 dispatchOnceInnerLocked(&nextWakeupTime);
725 }
726
727 // Run all pending commands if there are any.
728 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000729 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700730 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800731 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800732
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700733 // If we are still waiting for ack on some events,
734 // we might have to wake up earlier to check if an app is anr'ing.
735 const nsecs_t nextAnrCheck = processAnrsLocked();
736 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
737
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800738 // We are about to enter an infinitely long sleep, because we have no commands or
739 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700740 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800741 mDispatcherEnteredIdle.notify_all();
742 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800743 } // release lock
744
745 // Wait for callback or timeout or wake. (make sure we round up, not down)
746 nsecs_t currentTime = now();
747 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
748 mLooper->pollOnce(timeoutMillis);
749}
750
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700751/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500752 * Raise ANR if there is no focused window.
753 * Before the ANR is raised, do a final state check:
754 * 1. The currently focused application must be the same one we are waiting for.
755 * 2. Ensure we still don't have a focused window.
756 */
757void InputDispatcher::processNoFocusedWindowAnrLocked() {
758 // Check if the application that we are waiting for is still focused.
759 std::shared_ptr<InputApplicationHandle> focusedApplication =
760 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
761 if (focusedApplication == nullptr ||
762 focusedApplication->getApplicationToken() !=
763 mAwaitedFocusedApplication->getApplicationToken()) {
764 // Unexpected because we should have reset the ANR timer when focused application changed
765 ALOGE("Waited for a focused window, but focused application has already changed to %s",
766 focusedApplication->getName().c_str());
767 return; // The focused application has changed.
768 }
769
chaviw98318de2021-05-19 16:45:23 -0500770 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500771 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
772 if (focusedWindowHandle != nullptr) {
773 return; // We now have a focused window. No need for ANR.
774 }
775 onAnrLocked(mAwaitedFocusedApplication);
776}
777
778/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700779 * Check if any of the connections' wait queues have events that are too old.
780 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
781 * Return the time at which we should wake up next.
782 */
783nsecs_t InputDispatcher::processAnrsLocked() {
784 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700785 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700786 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
787 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
788 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500789 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700790 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500791 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700792 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700793 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500794 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700795 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
796 }
797 }
798
799 // Check if any connection ANRs are due
800 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
801 if (currentTime < nextAnrCheck) { // most likely scenario
802 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
803 }
804
805 // If we reached here, we have an unresponsive connection.
806 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
807 if (connection == nullptr) {
808 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
809 return nextAnrCheck;
810 }
811 connection->responsive = false;
812 // Stop waking up for this unresponsive connection
813 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000814 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700815 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700816}
817
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800818std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
819 const sp<Connection>& connection) {
820 if (connection->monitor) {
821 return mMonitorDispatchingTimeout;
822 }
823 const sp<WindowInfoHandle> window =
824 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700825 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500826 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700827 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500828 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700829}
830
Michael Wrightd02c5b62014-02-10 15:10:22 -0800831void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
832 nsecs_t currentTime = now();
833
Jeff Browndc5992e2014-04-11 01:27:26 -0700834 // Reset the key repeat timer whenever normal dispatch is suspended while the
835 // device is in a non-interactive state. This is to ensure that we abort a key
836 // repeat if the device is just coming out of sleep.
837 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838 resetKeyRepeatLocked();
839 }
840
841 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
842 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100843 if (DEBUG_FOCUS) {
844 ALOGD("Dispatch frozen. Waiting some more.");
845 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800846 return;
847 }
848
849 // Optimize latency of app switches.
850 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
851 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
852 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
853 if (mAppSwitchDueTime < *nextWakeupTime) {
854 *nextWakeupTime = mAppSwitchDueTime;
855 }
856
857 // Ready to start a new event.
858 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700859 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700860 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861 if (isAppSwitchDue) {
862 // The inbound queue is empty so the app switch key we were waiting
863 // for will never arrive. Stop waiting for it.
864 resetPendingAppSwitchLocked(false);
865 isAppSwitchDue = false;
866 }
867
868 // Synthesize a key repeat if appropriate.
869 if (mKeyRepeatState.lastKeyEntry) {
870 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
871 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
872 } else {
873 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
874 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
875 }
876 }
877 }
878
879 // Nothing to do if there is no pending event.
880 if (!mPendingEvent) {
881 return;
882 }
883 } else {
884 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700885 mPendingEvent = mInboundQueue.front();
886 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887 traceInboundQueueLengthLocked();
888 }
889
890 // Poke user activity for this event.
891 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700892 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 }
895
896 // Now we have an event to dispatch.
897 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700898 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700900 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700902 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800903 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700904 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 }
906
907 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700908 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909 }
910
911 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700912 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700913 const ConfigurationChangedEntry& typedEntry =
914 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700915 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700916 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700917 break;
918 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800919
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700920 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700921 const DeviceResetEntry& typedEntry =
922 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700923 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700924 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700925 break;
926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100928 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700929 std::shared_ptr<FocusEntry> typedEntry =
930 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100931 dispatchFocusLocked(currentTime, typedEntry);
932 done = true;
933 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
934 break;
935 }
936
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700937 case EventEntry::Type::TOUCH_MODE_CHANGED: {
938 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
939 dispatchTouchModeChangeLocked(currentTime, typedEntry);
940 done = true;
941 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
942 break;
943 }
944
Prabir Pradhan99987712020-11-10 18:43:05 -0800945 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
946 const auto typedEntry =
947 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
948 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
949 done = true;
950 break;
951 }
952
arthurhungb89ccb02020-12-30 16:19:01 +0800953 case EventEntry::Type::DRAG: {
954 std::shared_ptr<DragEntry> typedEntry =
955 std::static_pointer_cast<DragEntry>(mPendingEvent);
956 dispatchDragLocked(currentTime, typedEntry);
957 done = true;
958 break;
959 }
960
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700961 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700962 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700963 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700964 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700965 resetPendingAppSwitchLocked(true);
966 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700967 } else if (dropReason == DropReason::NOT_DROPPED) {
968 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700969 }
970 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700971 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700972 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700973 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700974 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
975 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700976 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700977 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700978 break;
979 }
980
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700981 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700982 std::shared_ptr<MotionEntry> motionEntry =
983 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700984 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
985 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700987 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700988 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700989 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700990 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
991 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700992 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700993 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700994 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800995 }
Chris Yef59a2f42020-10-16 12:55:26 -0700996
997 case EventEntry::Type::SENSOR: {
998 std::shared_ptr<SensorEntry> sensorEntry =
999 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1000 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1001 dropReason = DropReason::APP_SWITCH;
1002 }
1003 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1004 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1005 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1006 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1007 dropReason = DropReason::STALE;
1008 }
1009 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1010 done = true;
1011 break;
1012 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001013 }
1014
1015 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001016 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001017 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018 }
Michael Wright3a981722015-06-10 15:26:13 +01001019 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020
1021 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001022 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023 }
1024}
1025
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001026bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1027 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1028}
1029
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001030/**
1031 * Return true if the events preceding this incoming motion event should be dropped
1032 * Return false otherwise (the default behaviour)
1033 */
1034bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001035 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001036 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001037
1038 // Optimize case where the current application is unresponsive and the user
1039 // decides to touch a window in a different application.
1040 // If the application takes too long to catch up then we drop all events preceding
1041 // the touch into the other window.
1042 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001043 const int32_t displayId = motionEntry.displayId;
1044 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001045 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001046
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001047 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001048 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001049 touchedWindowHandle->getApplicationToken() !=
1050 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001051 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001052 ALOGI("Pruning input queue because user touched a different application while waiting "
1053 "for %s",
1054 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001055 return true;
1056 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001057
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001058 // Alternatively, maybe there's a spy window that could handle this event.
1059 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1060 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1061 for (const auto& windowHandle : touchedSpies) {
1062 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001063 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001064 // This spy window could take more input. Drop all events preceding this
1065 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001066 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001067 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001068 mAwaitedFocusedApplication->getName().c_str());
1069 return true;
1070 }
1071 }
1072 }
1073
1074 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1075 // yet been processed by some connections, the dispatcher will wait for these motion
1076 // events to be processed before dispatching the key event. This is because these motion events
1077 // may cause a new window to be launched, which the user might expect to receive focus.
1078 // To prevent waiting forever for such events, just send the key to the currently focused window
1079 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1080 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1081 "just send the pending key event to the focused window.");
1082 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001083 }
1084 return false;
1085}
1086
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001087bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001088 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001089 mInboundQueue.push_back(std::move(newEntry));
1090 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091 traceInboundQueueLengthLocked();
1092
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001093 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001094 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001095 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1096 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001097 // Optimize app switch latency.
1098 // If the application takes too long to catch up then we drop all events preceding
1099 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001100 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001101 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001102 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001103 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001104 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001105 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001106 if (DEBUG_APP_SWITCH) {
1107 ALOGD("App switch is pending!");
1108 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001109 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001110 mAppSwitchSawKeyDown = false;
1111 needWake = true;
1112 }
1113 }
1114 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001115
1116 // If a new up event comes in, and the pending event with same key code has been asked
1117 // to try again later because of the policy. We have to reset the intercept key wake up
1118 // time for it may have been handled in the policy and could be dropped.
1119 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1120 mPendingEvent->type == EventEntry::Type::KEY) {
1121 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1122 if (pendingKey.keyCode == keyEntry.keyCode &&
1123 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001124 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1125 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001126 pendingKey.interceptKeyWakeupTime = 0;
1127 needWake = true;
1128 }
1129 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001130 break;
1131 }
1132
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001133 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001134 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1135 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001136 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1137 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001138 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001140 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001142 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001143 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1144 break;
1145 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001146 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001147 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001148 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001149 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001150 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1151 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001152 // nothing to do
1153 break;
1154 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155 }
1156
1157 return needWake;
1158}
1159
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001160void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001161 // Do not store sensor event in recent queue to avoid flooding the queue.
1162 if (entry->type != EventEntry::Type::SENSOR) {
1163 mRecentQueue.push_back(entry);
1164 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001165 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001166 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167 }
1168}
1169
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001170std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001171InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001172 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001174 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001175 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001176 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001177 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001178 continue;
1179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001181 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001182 if (!info.isSpy() &&
1183 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001184 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001185 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001186
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001187 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1188 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001189 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001190 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 }
1192 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001193 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194}
1195
Prabir Pradhand65552b2021-10-07 11:23:50 -07001196std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001197 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001198 // Traverse windows from front to back and gather the touched spy windows.
1199 std::vector<sp<WindowInfoHandle>> spyWindows;
1200 const auto& windowHandles = getWindowHandlesLocked(displayId);
1201 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1202 const WindowInfo& info = *windowHandle->getInfo();
1203
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001204 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001205 continue;
1206 }
1207 if (!info.isSpy()) {
1208 // The first touched non-spy window was found, so return the spy windows touched so far.
1209 return spyWindows;
1210 }
1211 spyWindows.push_back(windowHandle);
1212 }
1213 return spyWindows;
1214}
1215
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001216void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 const char* reason;
1218 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001219 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001220 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001221 ALOGD("Dropped event because policy consumed it.");
1222 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001223 reason = "inbound event was dropped because the policy consumed it";
1224 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001225 case DropReason::DISABLED:
1226 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001227 ALOGI("Dropped event because input dispatch is disabled.");
1228 }
1229 reason = "inbound event was dropped because input dispatch is disabled";
1230 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001231 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001232 ALOGI("Dropped event because of pending overdue app switch.");
1233 reason = "inbound event was dropped because of pending overdue app switch";
1234 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001235 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001236 ALOGI("Dropped event because the current application is not responding and the user "
1237 "has started interacting with a different application.");
1238 reason = "inbound event was dropped because the current application is not responding "
1239 "and the user has started interacting with a different application";
1240 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001241 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001242 ALOGI("Dropped event because it is stale.");
1243 reason = "inbound event was dropped because it is stale";
1244 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001245 case DropReason::NO_POINTER_CAPTURE:
1246 ALOGI("Dropped event because there is no window with Pointer Capture.");
1247 reason = "inbound event was dropped because there is no window with Pointer Capture";
1248 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001249 case DropReason::NOT_DROPPED: {
1250 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001251 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253 }
1254
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001255 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001256 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001257 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001259 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001261 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001262 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1263 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001264 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001265 synthesizeCancelationEventsForAllConnectionsLocked(options);
1266 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001267 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1268 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001269 synthesizeCancelationEventsForAllConnectionsLocked(options);
1270 }
1271 break;
1272 }
Chris Yef59a2f42020-10-16 12:55:26 -07001273 case EventEntry::Type::SENSOR: {
1274 break;
1275 }
arthurhungb89ccb02020-12-30 16:19:01 +08001276 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1277 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001278 break;
1279 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001280 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001281 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001282 case EventEntry::Type::CONFIGURATION_CHANGED:
1283 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001284 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001285 break;
1286 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001287 }
1288}
1289
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001290static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001291 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1292 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293}
1294
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001295bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1296 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1297 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1298 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299}
1300
1301bool InputDispatcher::isAppSwitchPendingLocked() {
Colin Cross5b799302022-10-18 21:52:41 -07001302 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303}
1304
1305void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001306 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001308 if (DEBUG_APP_SWITCH) {
1309 if (handled) {
1310 ALOGD("App switch has arrived.");
1311 } else {
1312 ALOGD("App switch was abandoned.");
1313 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001314 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315}
1316
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001318 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001319}
1320
Prabir Pradhancef936d2021-07-21 16:17:52 +00001321bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001322 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 return false;
1324 }
1325
1326 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001327 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001328 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001329 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1330 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001331 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332 return true;
1333}
1334
Prabir Pradhancef936d2021-07-21 16:17:52 +00001335void InputDispatcher::postCommandLocked(Command&& command) {
1336 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337}
1338
1339void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001340 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001341 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001342 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343 releaseInboundEventLocked(entry);
1344 }
1345 traceInboundQueueLengthLocked();
1346}
1347
1348void InputDispatcher::releasePendingEventLocked() {
1349 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001350 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001351 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352 }
1353}
1354
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001355void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001357 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001358 if (DEBUG_DISPATCH_CYCLE) {
1359 ALOGD("Injected inbound event was dropped.");
1360 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001361 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 }
1363 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001364 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365 }
1366 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001367}
1368
1369void InputDispatcher::resetKeyRepeatLocked() {
1370 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001371 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001372 }
1373}
1374
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001375std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1376 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377
Michael Wright2e732952014-09-24 13:26:59 -07001378 uint32_t policyFlags = entry->policyFlags &
1379 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001381 std::shared_ptr<KeyEntry> newEntry =
1382 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1383 entry->source, entry->displayId, policyFlags, entry->action,
1384 entry->flags, entry->keyCode, entry->scanCode,
1385 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001387 newEntry->syntheticRepeat = true;
1388 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001390 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001391}
1392
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001393bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001394 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001395 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1396 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1397 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001398
1399 // Reset key repeating in case a keyboard device was added or removed or something.
1400 resetKeyRepeatLocked();
1401
1402 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001403 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1404 scoped_unlock unlock(mLock);
1405 mPolicy->notifyConfigurationChanged(eventTime);
1406 };
1407 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408 return true;
1409}
1410
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001411bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1412 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001413 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1414 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1415 entry.deviceId);
1416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417
liushenxiang42232912021-05-21 20:24:09 +08001418 // Reset key repeating in case a keyboard device was disabled or enabled.
1419 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1420 resetKeyRepeatLocked();
1421 }
1422
Michael Wrightfb04fd52022-11-24 22:31:11 +00001423 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001424 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001425 synthesizeCancelationEventsForAllConnectionsLocked(options);
1426 return true;
1427}
1428
Vishnu Nairad321cd2020-08-20 16:40:21 -07001429void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001430 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001431 if (mPendingEvent != nullptr) {
1432 // Move the pending event to the front of the queue. This will give the chance
1433 // for the pending event to get dispatched to the newly focused window
1434 mInboundQueue.push_front(mPendingEvent);
1435 mPendingEvent = nullptr;
1436 }
1437
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001438 std::unique_ptr<FocusEntry> focusEntry =
1439 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1440 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001441
1442 // This event should go to the front of the queue, but behind all other focus events
1443 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001444 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001445 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001446 [](const std::shared_ptr<EventEntry>& event) {
1447 return event->type == EventEntry::Type::FOCUS;
1448 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001449
1450 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001451 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001452}
1453
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001454void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001455 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001456 if (channel == nullptr) {
1457 return; // Window has gone away
1458 }
1459 InputTarget target;
1460 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001461 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001462 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001463 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1464 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001465 std::string reason = std::string("reason=").append(entry->reason);
1466 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001467 dispatchEventLocked(currentTime, entry, {target});
1468}
1469
Prabir Pradhan99987712020-11-10 18:43:05 -08001470void InputDispatcher::dispatchPointerCaptureChangedLocked(
1471 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1472 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001473 dropReason = DropReason::NOT_DROPPED;
1474
Prabir Pradhan99987712020-11-10 18:43:05 -08001475 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001476 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001477
1478 if (entry->pointerCaptureRequest.enable) {
1479 // Enable Pointer Capture.
1480 if (haveWindowWithPointerCapture &&
1481 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001482 // This can happen if pointer capture is disabled and re-enabled before we notify the
1483 // app of the state change, so there is no need to notify the app.
1484 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1485 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001486 }
1487 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001488 // This can happen if a window requests capture and immediately releases capture.
1489 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001490 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001491 return;
1492 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001493 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1494 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1495 return;
1496 }
1497
Vishnu Nairc519ff72021-01-21 08:23:08 -08001498 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001499 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1500 mWindowTokenWithPointerCapture = token;
1501 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001502 // Disable Pointer Capture.
1503 // We do not check if the sequence number matches for requests to disable Pointer Capture
1504 // for two reasons:
1505 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1506 // to disable capture with the same sequence number: one generated by
1507 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1508 // Capture being disabled in InputReader.
1509 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1510 // actual Pointer Capture state that affects events being generated by input devices is
1511 // in InputReader.
1512 if (!haveWindowWithPointerCapture) {
1513 // Pointer capture was already forcefully disabled because of focus change.
1514 dropReason = DropReason::NOT_DROPPED;
1515 return;
1516 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001517 token = mWindowTokenWithPointerCapture;
1518 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001519 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001520 setPointerCaptureLocked(false);
1521 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001522 }
1523
1524 auto channel = getInputChannelLocked(token);
1525 if (channel == nullptr) {
1526 // Window has gone away, clean up Pointer Capture state.
1527 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001528 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001529 setPointerCaptureLocked(false);
1530 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001531 return;
1532 }
1533 InputTarget target;
1534 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001535 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001536 entry->dispatchInProgress = true;
1537 dispatchEventLocked(currentTime, entry, {target});
1538
1539 dropReason = DropReason::NOT_DROPPED;
1540}
1541
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001542void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1543 const std::shared_ptr<TouchModeEntry>& entry) {
1544 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001545 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001546 if (windowHandles.empty()) {
1547 return;
1548 }
1549 const std::vector<InputTarget> inputTargets =
1550 getInputTargetsFromWindowHandlesLocked(windowHandles);
1551 if (inputTargets.empty()) {
1552 return;
1553 }
1554 entry->dispatchInProgress = true;
1555 dispatchEventLocked(currentTime, entry, inputTargets);
1556}
1557
1558std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1559 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1560 std::vector<InputTarget> inputTargets;
1561 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001562 const sp<IBinder>& token = handle->getToken();
1563 if (token == nullptr) {
1564 continue;
1565 }
1566 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1567 if (channel == nullptr) {
1568 continue; // Window has gone away
1569 }
1570 InputTarget target;
1571 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001572 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001573 inputTargets.push_back(target);
1574 }
1575 return inputTargets;
1576}
1577
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001578bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001579 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001581 if (!entry->dispatchInProgress) {
1582 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1583 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1584 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1585 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001586 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 // We have seen two identical key downs in a row which indicates that the device
1588 // driver is automatically generating key repeats itself. We take note of the
1589 // repeat here, but we disable our own next key repeat timer since it is clear that
1590 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001591 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1592 // Make sure we don't get key down from a different device. If a different
1593 // device Id has same key pressed down, the new device Id will replace the
1594 // current one to hold the key repeat with repeat count reset.
1595 // In the future when got a KEY_UP on the device id, drop it and do not
1596 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1598 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001599 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 } else {
1601 // Not a repeat. Save key down state in case we do see a repeat later.
1602 resetKeyRepeatLocked();
1603 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1604 }
1605 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001606 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1607 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001608 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001609 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001610 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1611 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001612 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613 resetKeyRepeatLocked();
1614 }
1615
1616 if (entry->repeatCount == 1) {
1617 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1618 } else {
1619 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1620 }
1621
1622 entry->dispatchInProgress = true;
1623
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001624 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625 }
1626
1627 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001628 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629 if (currentTime < entry->interceptKeyWakeupTime) {
1630 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1631 *nextWakeupTime = entry->interceptKeyWakeupTime;
1632 }
1633 return false; // wait until next wakeup
1634 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001635 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 entry->interceptKeyWakeupTime = 0;
1637 }
1638
1639 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001640 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001642 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001643 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001644
1645 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1646 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1647 };
1648 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 return false; // wait for the command to run
1650 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001651 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001653 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001654 if (*dropReason == DropReason::NOT_DROPPED) {
1655 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656 }
1657 }
1658
1659 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001660 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001661 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001662 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1663 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001664 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665 return true;
1666 }
1667
1668 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001669 InputEventInjectionResult injectionResult;
1670 sp<WindowInfoHandle> focusedWindow =
1671 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1672 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001673 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 return false;
1675 }
1676
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001677 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001678 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679 return true;
1680 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001681 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1682
1683 std::vector<InputTarget> inputTargets;
1684 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001685 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001686 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001687
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001688 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001689 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690
1691 // Dispatch the key.
1692 dispatchEventLocked(currentTime, entry, inputTargets);
1693 return true;
1694}
1695
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001696void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001697 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1698 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1699 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1700 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1701 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1702 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1703 entry.metaState, entry.repeatCount, entry.downTime);
1704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001705}
1706
Prabir Pradhancef936d2021-07-21 16:17:52 +00001707void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1708 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001709 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001710 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1711 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1712 "source=0x%x, sensorType=%s",
1713 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001714 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001715 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001716 auto command = [this, entry]() REQUIRES(mLock) {
1717 scoped_unlock unlock(mLock);
1718
1719 if (entry->accuracyChanged) {
1720 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1721 }
1722 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1723 entry->hwTimestamp, entry->values);
1724 };
1725 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001726}
1727
1728bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001729 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1730 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001731 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001732 }
Chris Yef59a2f42020-10-16 12:55:26 -07001733 { // acquire lock
1734 std::scoped_lock _l(mLock);
1735
1736 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1737 std::shared_ptr<EventEntry> entry = *it;
1738 if (entry->type == EventEntry::Type::SENSOR) {
1739 it = mInboundQueue.erase(it);
1740 releaseInboundEventLocked(entry);
1741 }
1742 }
1743 }
1744 return true;
1745}
1746
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001747bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001748 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001749 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001751 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752 entry->dispatchInProgress = true;
1753
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001754 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 }
1756
1757 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001758 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001759 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001760 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1761 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762 return true;
1763 }
1764
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001765 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766
1767 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001768 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769
1770 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001771 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772 if (isPointerEvent) {
1773 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001774
1775 if (mDragState &&
1776 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1777 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1778 pilferPointersLocked(mDragState->dragWindow->getToken());
1779 }
1780
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001781 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001782 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001783 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001784 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1785 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001786 } else {
1787 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001788 sp<WindowInfoHandle> focusedWindow =
1789 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1790 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1791 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1792 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001793 InputTarget::Flags::FOREGROUND |
1794 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001795 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001796 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001798 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 return false;
1800 }
1801
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001802 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001803 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001804 return true;
1805 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001806 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001807 CancelationOptions::Mode mode(
1808 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1809 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001810 CancelationOptions options(mode, "input event injection failed");
1811 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 return true;
1813 }
1814
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001815 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001816 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001817
1818 // Dispatch the motion.
1819 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001820 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001821 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 synthesizeCancelationEventsForAllConnectionsLocked(options);
1823 }
1824 dispatchEventLocked(currentTime, entry, inputTargets);
1825 return true;
1826}
1827
chaviw98318de2021-05-19 16:45:23 -05001828void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001829 bool isExiting, const int32_t rawX,
1830 const int32_t rawY) {
1831 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001832 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001833 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1834 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001835
1836 enqueueInboundEventLocked(std::move(dragEntry));
1837}
1838
1839void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1840 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1841 if (channel == nullptr) {
1842 return; // Window has gone away
1843 }
1844 InputTarget target;
1845 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001846 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001847 entry->dispatchInProgress = true;
1848 dispatchEventLocked(currentTime, entry, {target});
1849}
1850
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001851void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001852 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001853 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001854 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001855 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001856 "metaState=0x%x, buttonState=0x%x,"
1857 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001858 prefix, entry.eventTime, entry.deviceId,
1859 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1860 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1861 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1862 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001864 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001865 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001866 "x=%f, y=%f, pressure=%f, size=%f, "
1867 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1868 "orientation=%f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001869 i, entry.pointerProperties[i].id,
1870 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001871 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1872 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1873 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1874 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1875 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1876 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1877 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1878 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1879 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1880 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882}
1883
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001884void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1885 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001886 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001887 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001888 if (DEBUG_DISPATCH_CYCLE) {
1889 ALOGD("dispatchEventToCurrentInputTargets");
1890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001891
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001892 updateInteractionTokensLocked(*eventEntry, inputTargets);
1893
Michael Wrightd02c5b62014-02-10 15:10:22 -08001894 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1895
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001896 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001898 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001899 sp<Connection> connection =
1900 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001901 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001902 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001904 if (DEBUG_FOCUS) {
1905 ALOGD("Dropping event delivery to target with channel '%s' because it "
1906 "is no longer registered with the input dispatcher.",
1907 inputTarget.inputChannel->getName().c_str());
1908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909 }
1910 }
1911}
1912
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001913void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1914 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1915 // If the policy decides to close the app, we will get a channel removal event via
1916 // unregisterInputChannel, and will clean up the connection that way. We are already not
1917 // sending new pointers to the connection when it blocked, but focused events will continue to
1918 // pile up.
1919 ALOGW("Canceling events for %s because it is unresponsive",
1920 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001921 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001922 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001923 "application not responding");
1924 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 }
1926}
1927
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001928void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001929 if (DEBUG_FOCUS) {
1930 ALOGD("Resetting ANR timeouts.");
1931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932
1933 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001934 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001935 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936}
1937
Tiger Huang721e26f2018-07-24 22:26:19 +08001938/**
1939 * Get the display id that the given event should go to. If this event specifies a valid display id,
1940 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1941 * Focused display is the display that the user most recently interacted with.
1942 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001943int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001944 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001945 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001946 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001947 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1948 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001949 break;
1950 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001951 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001952 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1953 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001954 break;
1955 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001956 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001957 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001958 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001959 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001960 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001961 case EventEntry::Type::SENSOR:
1962 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001963 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001964 return ADISPLAY_ID_NONE;
1965 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001966 }
1967 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1968}
1969
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001970bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1971 const char* focusedWindowName) {
1972 if (mAnrTracker.empty()) {
1973 // already processed all events that we waited for
1974 mKeyIsWaitingForEventsTimeout = std::nullopt;
1975 return false;
1976 }
1977
1978 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1979 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001980 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001981 mKeyIsWaitingForEventsTimeout = currentTime +
1982 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1983 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001984 return true;
1985 }
1986
1987 // We still have pending events, and already started the timer
1988 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1989 return true; // Still waiting
1990 }
1991
1992 // Waited too long, and some connection still hasn't processed all motions
1993 // Just send the key to the focused window
1994 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1995 focusedWindowName);
1996 mKeyIsWaitingForEventsTimeout = std::nullopt;
1997 return false;
1998}
1999
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002000sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2001 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2002 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002003 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002004 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005
Tiger Huang721e26f2018-07-24 22:26:19 +08002006 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002007 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002008 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002009 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2010
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011 // If there is no currently focused window and no focused application
2012 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002013 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2014 ALOGI("Dropping %s event because there is no focused window or focused application in "
2015 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002016 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002017 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018 }
2019
Vishnu Nair062a8672021-09-03 16:07:44 -07002020 // Drop key events if requested by input feature
2021 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002022 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002023 }
2024
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002025 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2026 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2027 // start interacting with another application via touch (app switch). This code can be removed
2028 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2029 // an app is expected to have a focused window.
2030 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2031 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2032 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002033 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2034 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2035 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002036 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002037 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002038 ALOGW("Waiting because no window has focus but %s may eventually add a "
2039 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002040 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002041 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002042 outInjectionResult = InputEventInjectionResult::PENDING;
2043 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002044 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2045 // Already raised ANR. Drop the event
2046 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002047 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002048 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002049 } else {
2050 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002051 outInjectionResult = InputEventInjectionResult::PENDING;
2052 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002053 }
2054 }
2055
2056 // we have a valid, non-null focused window
2057 resetNoFocusedWindowTimeoutLocked();
2058
Prabir Pradhan5735a322022-04-11 17:23:34 +00002059 // Verify targeted injection.
2060 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2061 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002062 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2063 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 }
2065
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002066 if (focusedWindowHandle->getInfo()->inputConfig.test(
2067 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002068 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002069 outInjectionResult = InputEventInjectionResult::PENDING;
2070 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002071 }
2072
2073 // If the event is a key event, then we must wait for all previous events to
2074 // complete before delivering it because previous events may have the
2075 // side-effect of transferring focus to a different window and we want to
2076 // ensure that the following keys are sent to the new window.
2077 //
2078 // Suppose the user touches a button in a window then immediately presses "A".
2079 // If the button causes a pop-up window to appear then we want to ensure that
2080 // the "A" key is delivered to the new pop-up window. This is because users
2081 // often anticipate pending UI changes when typing on a keyboard.
2082 // To obtain this behavior, we must serialize key events with respect to all
2083 // prior input events.
2084 if (entry.type == EventEntry::Type::KEY) {
2085 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2086 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002087 outInjectionResult = InputEventInjectionResult::PENDING;
2088 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090 }
2091
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002092 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2093 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094}
2095
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002096/**
2097 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2098 * that are currently unresponsive.
2099 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002100std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2101 const std::vector<Monitor>& monitors) const {
2102 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002103 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002104 [this](const Monitor& monitor) REQUIRES(mLock) {
2105 sp<Connection> connection =
2106 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002107 if (connection == nullptr) {
2108 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002109 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002110 return false;
2111 }
2112 if (!connection->responsive) {
2113 ALOGW("Unresponsive monitor %s will not get the new gesture",
2114 connection->inputChannel->getName().c_str());
2115 return false;
2116 }
2117 return true;
2118 });
2119 return responsiveMonitors;
2120}
2121
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002122/**
2123 * In general, touch should be always split between windows. Some exceptions:
2124 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2125 * from the same device, *and* the window that's receiving the current pointer does not support
2126 * split touch.
2127 * 2. Don't split mouse events
2128 */
2129bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2130 const MotionEntry& entry) const {
2131 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2132 // We should never split mouse events
2133 return false;
2134 }
2135 for (const TouchedWindow& touchedWindow : touchState.windows) {
2136 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2137 // Spy windows should not affect whether or not touch is split.
2138 continue;
2139 }
2140 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2141 continue;
2142 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002143 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2144 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2145 // Wallpaper window should not affect whether or not touch is split
2146 continue;
2147 }
2148
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002149 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2150 // being sent there. For now, use deviceId from touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002151 if (entry.deviceId == touchState.deviceId && touchedWindow.pointerIds.any()) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002152 return false;
2153 }
2154 }
2155 return true;
2156}
2157
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002158std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002159 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2160 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002161 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002163 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164 // For security reasons, we defer updating the touch state until we are sure that
2165 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002166 const int32_t displayId = entry.displayId;
2167 const int32_t action = entry.action;
2168 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169
2170 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002171 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002173 // Copy current touch state into tempTouchState.
2174 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2175 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002176 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002177 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002178 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2179 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002180 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002181 }
2182
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002183 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002184 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002185 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002186
2187 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2188 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2189 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002190 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2191 // touchable windows.
2192 const bool wasDown = oldState != nullptr && oldState->isDown();
2193 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2194 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
2195 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002196 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002197
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002198 // If pointers are already down, let's finish the current gesture and ignore the new events
2199 // from another device. However, if the new event is a down event, let's cancel the current
2200 // touch and let the new one take over.
2201 if (switchedDevice && wasDown && !isDown) {
2202 LOG(INFO) << "Dropping event because a pointer for device " << oldState->deviceId
2203 << " is already down in display " << displayId << ": " << entry.getDescription();
2204 // TODO(b/211379801): test multiple simultaneous input streams.
2205 outInjectionResult = InputEventInjectionResult::FAILED;
2206 return {}; // wrong device
2207 }
2208
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002210 // If a new gesture is starting, clear the touch state completely.
2211 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002212 tempTouchState.deviceId = entry.deviceId;
2213 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002215 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002216 ALOGI("Dropping move event because a pointer for a different device is already active "
2217 "in display %" PRId32,
2218 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002219 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002220 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002221 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222 }
2223
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002224 if (isHoverAction) {
2225 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2226 // all of the existing hovering pointers and recompute.
2227 tempTouchState.clearHoveringPointers();
2228 }
2229
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2231 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002232 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002233 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002234 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2235 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002236 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002237 auto [newTouchedWindowHandle, outsideTargets] =
2238 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002239
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002240 if (isDown) {
2241 targets += outsideTargets;
2242 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002244 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002245 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002247 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002248 }
2249
Prabir Pradhan5735a322022-04-11 17:23:34 +00002250 // Verify targeted injection.
2251 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2252 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002253 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002254 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002255 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002256 }
2257
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002258 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002259 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002260 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2261 // New window supports splitting, but we should never split mouse events.
2262 isSplit = !isFromMouse;
2263 } else if (isSplit) {
2264 // New window does not support splitting but we have already split events.
2265 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002266 newTouchedWindowHandle = nullptr;
2267 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002268 } else {
2269 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002270 // be delivered to a new window which supports split touch. Pointers from a mouse device
2271 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002272 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002273 }
2274
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002275 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002276 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002277 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002278 // Process the foreground window first so that it is the first to receive the event.
2279 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002280 }
2281
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002282 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002283 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2284 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002285 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002286 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002287 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002288 }
2289
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002290 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002291 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002292 continue;
2293 }
2294
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002295 if (isHoverAction) {
2296 const int32_t pointerId = entry.pointerProperties[0].id;
2297 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2298 // Pointer left. Remove it
2299 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2300 } else {
2301 // The "windowHandle" is the target of this hovering pointer.
2302 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId,
2303 pointerId);
2304 }
2305 }
2306
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002307 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002308 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002309
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002310 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2311 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002312 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002313 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002314
2315 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002316 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002317 }
2318 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002319 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002320 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002321 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002322 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002323
2324 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002325 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002326 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002327 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002328 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002329
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002330 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2331 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2332
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002333 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2334 // still add a window to the touch state. We should avoid doing that, but some of the
2335 // later checks ("at least one foreground window") rely on this in order to dispatch
2336 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002337 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002338 isDownOrPointerDown
2339 ? std::make_optional(entry.eventTime)
2340 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002341
2342 // If this is the pointer going down and the touched window has a wallpaper
2343 // then also add the touched wallpaper windows so they are locked in for the duration
2344 // of the touch gesture.
2345 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2346 // engine only supports touch events. We would need to add a mechanism similar
2347 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002348 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002349 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2350 windowHandle->getInfo()->inputConfig.test(
2351 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2352 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2353 if (wallpaper != nullptr) {
2354 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2355 InputTarget::Flags::WINDOW_IS_OBSCURED |
2356 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2357 InputTarget::Flags::DISPATCH_AS_IS;
2358 if (isSplit) {
2359 wallpaperFlags |= InputTarget::Flags::SPLIT;
2360 }
2361 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2362 entry.eventTime);
2363 }
2364 }
2365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002367
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002368 // If a window is already pilfering some pointers, give it this new pointer as well and
2369 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2370 // which is a specific behaviour that we want.
2371 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2372 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002373 if (touchedWindow.pointerIds.test(pointerId) &&
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002374 touchedWindow.pilferedPointerIds.count() > 0) {
2375 // This window is already pilfering some pointers, and this new pointer is also
2376 // going to it. Therefore, take over this pointer and don't give it to anyone
2377 // else.
2378 touchedWindow.pilferedPointerIds.set(pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002379 }
2380 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002381
2382 // Restrict all pilfered pointers to the pilfering windows.
2383 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384 } else {
2385 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2386
2387 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002388 if (!tempTouchState.isDown()) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002389 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2390 "dropped the pointer down event in display "
2391 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002392 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002393 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 }
2395
arthurhung6d4bed92021-03-17 11:59:33 +08002396 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002397
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002399 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002400 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002401 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002402 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002403 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002404 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002405 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002406
Prabir Pradhan5735a322022-04-11 17:23:34 +00002407 // Verify targeted injection.
2408 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2409 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002410 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002411 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002412 }
2413
Vishnu Nair062a8672021-09-03 16:07:44 -07002414 // Drop touch events if requested by input feature
2415 if (newTouchedWindowHandle != nullptr &&
2416 shouldDropInput(entry, newTouchedWindowHandle)) {
2417 newTouchedWindowHandle = nullptr;
2418 }
2419
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002420 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2421 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002422 if (DEBUG_FOCUS) {
2423 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2424 oldTouchedWindowHandle->getName().c_str(),
2425 newTouchedWindowHandle->getName().c_str(), displayId);
2426 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002427 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002428 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002429 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002430 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002431
2432 const TouchedWindow& touchedWindow =
2433 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2434 addWindowTargetLocked(oldTouchedWindowHandle,
2435 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
2436 touchedWindow.firstDownTimeInTarget, targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437
2438 // Make a slippery entrance into the new window.
2439 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002440 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441 }
2442
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002443 ftl::Flags<InputTarget::Flags> targetFlags =
2444 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002445 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002446 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002447 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002449 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002450 }
2451 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002452 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002453 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002454 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002455 }
2456
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002457 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2458 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002459
2460 // Check if the wallpaper window should deliver the corresponding event.
2461 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002462 tempTouchState, pointerId, targets);
2463 tempTouchState.removeTouchedPointerFromWindow(pointerId, oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464 }
2465 }
Arthur Hung96483742022-11-15 03:30:48 +00002466
2467 // Update the pointerIds for non-splittable when it received pointer down.
2468 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2469 // If no split, we suppose all touched windows should receive pointer down.
2470 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2471 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2472 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2473 // Ignore drag window for it should just track one pointer.
2474 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2475 continue;
2476 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002477 touchedWindow.pointerIds.set(entry.pointerProperties[pointerIndex].id);
Arthur Hung96483742022-11-15 03:30:48 +00002478 }
2479 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002480 }
2481
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002482 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002483 {
2484 std::vector<TouchedWindow> hoveringWindows =
2485 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2486 for (const TouchedWindow& touchedWindow : hoveringWindows) {
2487 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2488 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2489 targets);
2490 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491 }
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002492 // Ensure that we have at least one foreground window or at least one window that cannot be a
2493 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2494 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2495 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002496 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2497 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002498 return !canReceiveForegroundTouches(
2499 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002500 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002501 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002502 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2503 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002504 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002505 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002506 }
2507
Prabir Pradhan5735a322022-04-11 17:23:34 +00002508 // Ensure that all touched windows are valid for injection.
2509 if (entry.injectionState != nullptr) {
2510 std::string errs;
2511 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002512 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002513 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2514 // dispatched to any uid, since the coords will be zeroed out later.
2515 continue;
2516 }
2517 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2518 if (err) errs += "\n - " + *err;
2519 }
2520 if (!errs.empty()) {
2521 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2522 "%d:%s",
2523 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002524 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002525 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002526 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002527 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002528
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002529 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2530 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002531 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002532 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002533 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002534 if (foregroundWindowHandle) {
2535 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002536 for (InputTarget& target : targets) {
2537 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2538 sp<WindowInfoHandle> targetWindow =
2539 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2540 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2541 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002543 }
2544 }
2545 }
2546 }
2547
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002548 // Success! Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002549 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002550 if (touchedWindow.pointerIds.none() && !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002551 // Windows with hovering pointers are getting persisted inside TouchState.
2552 // Do not send this event to those windows.
2553 continue;
2554 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002555 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2556 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2557 targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002558 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002559
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002560 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002561 // Drop the outside or hover touch windows since we will not care about them
2562 // in the next iteration.
2563 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002566 if (switchedDevice) {
2567 if (DEBUG_FOCUS) {
2568 ALOGD("Conflicting pointer actions: Switched to a different device.");
2569 }
2570 *outConflictingPointerActions = true;
2571 }
2572
2573 if (isHoverAction) {
2574 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002575 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002576 ALOGD_IF(DEBUG_FOCUS,
2577 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002578 *outConflictingPointerActions = true;
2579 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002580 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2581 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2582 tempTouchState.deviceId = entry.deviceId;
2583 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002584 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002585 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2586 // Pointer went up.
2587 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002588 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002589 // All pointers up or canceled.
2590 tempTouchState.reset();
2591 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2592 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002593 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2594 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002595 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002596 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002597 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2598 // One pointer went up.
2599 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2600 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002601
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002602 for (size_t i = 0; i < tempTouchState.windows.size();) {
2603 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002604 touchedWindow.pointerIds.reset(pointerId);
2605 if (touchedWindow.pointerIds.none()) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002606 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2607 continue;
2608 }
2609 i += 1;
2610 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002611 }
2612
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002613 // Save changes unless the action was scroll in which case the temporary touch
2614 // state was only valid for this one action.
2615 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002616 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002617 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002618 mTouchStatesByDisplay[displayId] = tempTouchState;
2619 } else {
2620 mTouchStatesByDisplay.erase(displayId);
2621 }
2622 }
2623
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002624 if (tempTouchState.windows.empty()) {
2625 mTouchStatesByDisplay.erase(displayId);
2626 }
2627
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002628 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002629}
2630
arthurhung6d4bed92021-03-17 11:59:33 +08002631void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002632 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2633 // have an explicit reason to support it.
2634 constexpr bool isStylus = false;
2635
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002636 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002637 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002638 if (dropWindow) {
2639 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002640 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002641 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002642 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002643 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002644 }
2645 mDragState.reset();
2646}
2647
2648void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002649 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002650 return;
2651 }
2652
arthurhung6d4bed92021-03-17 11:59:33 +08002653 if (!mDragState->isStartDrag) {
2654 mDragState->isStartDrag = true;
2655 mDragState->isStylusButtonDownAtStart =
2656 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2657 }
2658
Arthur Hung54745652022-04-20 07:17:41 +00002659 // Find the pointer index by id.
2660 int32_t pointerIndex = 0;
2661 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2662 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2663 if (pointerProperties.id == mDragState->pointerId) {
2664 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002665 }
Arthur Hung54745652022-04-20 07:17:41 +00002666 }
arthurhung6d4bed92021-03-17 11:59:33 +08002667
Arthur Hung54745652022-04-20 07:17:41 +00002668 if (uint32_t(pointerIndex) == entry.pointerCount) {
2669 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002670 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002671 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002672 return;
2673 }
2674
2675 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2676 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2677 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2678
2679 switch (maskedAction) {
2680 case AMOTION_EVENT_ACTION_MOVE: {
2681 // Handle the special case : stylus button no longer pressed.
2682 bool isStylusButtonDown =
2683 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2684 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2685 finishDragAndDrop(entry.displayId, x, y);
2686 return;
2687 }
2688
2689 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2690 // until we have an explicit reason to support it.
2691 constexpr bool isStylus = false;
2692
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002693 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002694 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002695 // enqueue drag exit if needed.
2696 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2697 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2698 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002699 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002700 y);
2701 }
2702 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2703 }
2704 // enqueue drag location if needed.
2705 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002706 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002707 }
2708 break;
2709 }
2710
2711 case AMOTION_EVENT_ACTION_POINTER_UP:
2712 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2713 break;
2714 }
2715 // The drag pointer is up.
2716 [[fallthrough]];
2717 case AMOTION_EVENT_ACTION_UP:
2718 finishDragAndDrop(entry.displayId, x, y);
2719 break;
2720 case AMOTION_EVENT_ACTION_CANCEL: {
2721 ALOGD("Receiving cancel when drag and drop.");
2722 sendDropWindowCommandLocked(nullptr, 0, 0);
2723 mDragState.reset();
2724 break;
2725 }
arthurhungb89ccb02020-12-30 16:19:01 +08002726 }
2727}
2728
chaviw98318de2021-05-19 16:45:23 -05002729void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002730 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002731 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002732 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002733 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002734 std::vector<InputTarget>::iterator it =
2735 std::find_if(inputTargets.begin(), inputTargets.end(),
2736 [&windowHandle](const InputTarget& inputTarget) {
2737 return inputTarget.inputChannel->getConnectionToken() ==
2738 windowHandle->getToken();
2739 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002740
chaviw98318de2021-05-19 16:45:23 -05002741 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002742
2743 if (it == inputTargets.end()) {
2744 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002745 std::shared_ptr<InputChannel> inputChannel =
2746 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002747 if (inputChannel == nullptr) {
2748 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2749 return;
2750 }
2751 inputTarget.inputChannel = inputChannel;
2752 inputTarget.flags = targetFlags;
2753 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002754 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002755 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2756 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002757 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002758 } else {
Siarhei Vishniakoua06bb552023-02-07 09:38:56 -08002759 // DisplayInfo not found for this window on display windowInfo->displayId.
2760 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002761 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002762 inputTargets.push_back(inputTarget);
2763 it = inputTargets.end() - 1;
2764 }
2765
2766 ALOG_ASSERT(it->flags == targetFlags);
2767 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2768
chaviw1ff3d1e2020-07-01 15:53:47 -07002769 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770}
2771
Michael Wright3dd60e22019-03-27 22:06:44 +00002772void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002773 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002774 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2775 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002776
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002777 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2778 InputTarget target;
2779 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002780 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002781 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2782 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002783 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2784 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002785 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002786 target.setDefaultPointerTransform(target.displayTransform);
2787 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788 }
2789}
2790
Robert Carrc9bf1d32020-04-13 17:21:08 -07002791/**
2792 * Indicate whether one window handle should be considered as obscuring
2793 * another window handle. We only check a few preconditions. Actually
2794 * checking the bounds is left to the caller.
2795 */
chaviw98318de2021-05-19 16:45:23 -05002796static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2797 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002798 // Compare by token so cloned layers aren't counted
2799 if (haveSameToken(windowHandle, otherHandle)) {
2800 return false;
2801 }
2802 auto info = windowHandle->getInfo();
2803 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002804 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002805 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002806 } else if (otherInfo->alpha == 0 &&
2807 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002808 // Those act as if they were invisible, so we don't need to flag them.
2809 // We do want to potentially flag touchable windows even if they have 0
2810 // opacity, since they can consume touches and alter the effects of the
2811 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002812 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002813 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2814 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002815 } else if (info->ownerUid == otherInfo->ownerUid) {
2816 // If ownerUid is the same we don't generate occlusion events as there
2817 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002818 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002819 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002820 return false;
2821 } else if (otherInfo->displayId != info->displayId) {
2822 return false;
2823 }
2824 return true;
2825}
2826
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002827/**
2828 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2829 * untrusted, one should check:
2830 *
2831 * 1. If result.hasBlockingOcclusion is true.
2832 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2833 * BLOCK_UNTRUSTED.
2834 *
2835 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2836 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2837 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2838 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2839 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2840 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2841 *
2842 * If neither of those is true, then it means the touch can be allowed.
2843 */
2844InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002845 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2846 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002847 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002848 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002849 TouchOcclusionInfo info;
2850 info.hasBlockingOcclusion = false;
2851 info.obscuringOpacity = 0;
2852 info.obscuringUid = -1;
2853 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002854 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002855 if (windowHandle == otherHandle) {
2856 break; // All future windows are below us. Exit early.
2857 }
chaviw98318de2021-05-19 16:45:23 -05002858 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002859 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2860 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002861 if (DEBUG_TOUCH_OCCLUSION) {
2862 info.debugInfo.push_back(
2863 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2864 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002865 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2866 // we perform the checks below to see if the touch can be propagated or not based on the
2867 // window's touch occlusion mode
2868 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2869 info.hasBlockingOcclusion = true;
2870 info.obscuringUid = otherInfo->ownerUid;
2871 info.obscuringPackage = otherInfo->packageName;
2872 break;
2873 }
2874 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2875 uint32_t uid = otherInfo->ownerUid;
2876 float opacity =
2877 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2878 // Given windows A and B:
2879 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2880 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2881 opacityByUid[uid] = opacity;
2882 if (opacity > info.obscuringOpacity) {
2883 info.obscuringOpacity = opacity;
2884 info.obscuringUid = uid;
2885 info.obscuringPackage = otherInfo->packageName;
2886 }
2887 }
2888 }
2889 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002890 if (DEBUG_TOUCH_OCCLUSION) {
2891 info.debugInfo.push_back(
2892 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2893 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002894 return info;
2895}
2896
chaviw98318de2021-05-19 16:45:23 -05002897std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002898 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002899 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2900 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2901 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2902 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002903 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2904 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2905 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2906 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2907 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002908 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002909 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002910}
2911
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002912bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2913 if (occlusionInfo.hasBlockingOcclusion) {
2914 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2915 occlusionInfo.obscuringUid);
2916 return false;
2917 }
2918 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2919 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2920 "%.2f, maximum allowed = %.2f)",
2921 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2922 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2923 return false;
2924 }
2925 return true;
2926}
2927
chaviw98318de2021-05-19 16:45:23 -05002928bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002931 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2932 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002933 if (windowHandle == otherHandle) {
2934 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002935 }
chaviw98318de2021-05-19 16:45:23 -05002936 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002937 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002938 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002939 return true;
2940 }
2941 }
2942 return false;
2943}
2944
chaviw98318de2021-05-19 16:45:23 -05002945bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002946 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002947 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2948 const WindowInfo* windowInfo = windowHandle->getInfo();
2949 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002950 if (windowHandle == otherHandle) {
2951 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002952 }
chaviw98318de2021-05-19 16:45:23 -05002953 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002954 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002955 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002956 return true;
2957 }
2958 }
2959 return false;
2960}
2961
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002962std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002963 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002964 if (applicationHandle != nullptr) {
2965 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002966 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002967 } else {
2968 return applicationHandle->getName();
2969 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002970 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002971 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002973 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002974 }
2975}
2976
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002977void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002978 if (!isUserActivityEvent(eventEntry)) {
2979 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002980 return;
2981 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002982 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002983 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002984 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002985 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002986 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002987 if (DEBUG_DISPATCH_CYCLE) {
2988 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2989 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002990 return;
2991 }
2992 }
2993
2994 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002995 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002996 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002997 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2998 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002999 return;
3000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003001
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003002 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003003 eventType = USER_ACTIVITY_EVENT_TOUCH;
3004 }
3005 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003006 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003007 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003008 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3009 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003010 return;
3011 }
3012 eventType = USER_ACTIVITY_EVENT_BUTTON;
3013 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003015 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003016 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003017 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003018 break;
3019 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003020 }
3021
Prabir Pradhancef936d2021-07-21 16:17:52 +00003022 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3023 REQUIRES(mLock) {
3024 scoped_unlock unlock(mLock);
3025 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
3026 };
3027 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003028}
3029
3030void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003031 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003032 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003033 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003034 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003035 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003036 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003037 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003038 ATRACE_NAME(message.c_str());
3039 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003040 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003041 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003042 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003043 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003044 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003045 inputTarget.getPointerInfoString().c_str());
3046 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047
3048 // Skip this event if the connection status is not normal.
3049 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003050 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003051 if (DEBUG_DISPATCH_CYCLE) {
3052 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003053 connection->getInputChannelName().c_str(),
3054 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056 return;
3057 }
3058
3059 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003060 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003061 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003062 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003063 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003064
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003065 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003066 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003067 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3068 logDispatchStateLocked();
3069 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3070 "target on connection "
3071 << connection->getInputChannelName() << " for "
3072 << originalMotionEntry.getDescription();
3073 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003074 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003075 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3076 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003077 if (!splitMotionEntry) {
3078 return; // split event was dropped
3079 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003080 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3081 std::string reason = std::string("reason=pointer cancel on split window");
3082 android_log_event_list(LOGTAG_INPUT_CANCEL)
3083 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3084 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003085 if (DEBUG_FOCUS) {
3086 ALOGD("channel '%s' ~ Split motion event.",
3087 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003088 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003089 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003090 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3091 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003092 return;
3093 }
3094 }
3095
3096 // Not splitting. Enqueue dispatch entries for the event as is.
3097 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3098}
3099
3100void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003101 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003102 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003103 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003104 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003105 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003106 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003107 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003108 ATRACE_NAME(message.c_str());
3109 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003110 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3111 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003112
hongzuo liu95785e22022-09-06 02:51:35 +00003113 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003114
3115 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003116 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003117 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003118 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003119 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003120 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003121 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003122 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003123 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003124 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003125 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003126 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003127 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128
3129 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003130 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003131 startDispatchCycleLocked(currentTime, connection);
3132 }
3133}
3134
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003135void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003136 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003137 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003138 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003139 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003140 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3141 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003142 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003143 ATRACE_NAME(message.c_str());
3144 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003145 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3146 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 return;
3148 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003149
3150 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3151 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152
3153 // This is a new event.
3154 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003155 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003156 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003158 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3159 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003160 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003162 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003163 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003164 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003165 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003166 dispatchEntry->resolvedAction = keyEntry.action;
3167 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003169 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3170 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003171 if (DEBUG_DISPATCH_CYCLE) {
3172 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3173 "event",
3174 connection->getInputChannelName().c_str());
3175 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003176 return; // skip the inconsistent event
3177 }
3178 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003181 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003182 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003183 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3184 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3185 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3186 static_cast<int32_t>(IdGenerator::Source::OTHER);
3187 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003188 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003189 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003190 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003191 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003192 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003193 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003194 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003195 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003196 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003197 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3198 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003199 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003200 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003201 }
3202 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003203 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3204 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003205 if (DEBUG_DISPATCH_CYCLE) {
3206 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3207 "enter event",
3208 connection->getInputChannelName().c_str());
3209 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003210 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3211 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003212 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3213 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003215 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003216 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3217 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3218 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003219 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003220 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3221 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003222 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003223 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3224 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003226 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3227 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003228 if (DEBUG_DISPATCH_CYCLE) {
3229 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3230 "event",
3231 connection->getInputChannelName().c_str());
3232 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003233 return; // skip the inconsistent event
3234 }
3235
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003236 dispatchEntry->resolvedEventId =
3237 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3238 ? mIdGenerator.nextId()
3239 : motionEntry.id;
3240 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3241 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3242 ") to MotionEvent(id=0x%" PRIx32 ").",
3243 motionEntry.id, dispatchEntry->resolvedEventId);
3244 ATRACE_NAME(message.c_str());
3245 }
3246
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003247 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3248 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3249 // Skip reporting pointer down outside focus to the policy.
3250 break;
3251 }
3252
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003253 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003254 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003255
3256 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003258 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003259 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003260 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3261 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003262 break;
3263 }
Chris Yef59a2f42020-10-16 12:55:26 -07003264 case EventEntry::Type::SENSOR: {
3265 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3266 break;
3267 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003268 case EventEntry::Type::CONFIGURATION_CHANGED:
3269 case EventEntry::Type::DEVICE_RESET: {
3270 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003271 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003272 break;
3273 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003274 }
3275
3276 // Remember that we are waiting for this dispatch to complete.
3277 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003278 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003279 }
3280
3281 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003282 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003283 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003284}
3285
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003286/**
3287 * This function is purely for debugging. It helps us understand where the user interaction
3288 * was taking place. For example, if user is touching launcher, we will see a log that user
3289 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3290 * We will see both launcher and wallpaper in that list.
3291 * Once the interaction with a particular set of connections starts, no new logs will be printed
3292 * until the set of interacted connections changes.
3293 *
3294 * The following items are skipped, to reduce the logspam:
3295 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3296 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3297 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3298 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3299 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003300 */
3301void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3302 const std::vector<InputTarget>& targets) {
3303 // Skip ACTION_UP events, and all events other than keys and motions
3304 if (entry.type == EventEntry::Type::KEY) {
3305 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3306 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3307 return;
3308 }
3309 } else if (entry.type == EventEntry::Type::MOTION) {
3310 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3311 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3312 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3313 return;
3314 }
3315 } else {
3316 return; // Not a key or a motion
3317 }
3318
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003319 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003320 std::vector<sp<Connection>> newConnections;
3321 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003322 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003323 continue; // Skip windows that receive ACTION_OUTSIDE
3324 }
3325
3326 sp<IBinder> token = target.inputChannel->getConnectionToken();
3327 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003328 if (connection == nullptr) {
3329 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003330 }
3331 newConnectionTokens.insert(std::move(token));
3332 newConnections.emplace_back(connection);
3333 }
3334 if (newConnectionTokens == mInteractionConnectionTokens) {
3335 return; // no change
3336 }
3337 mInteractionConnectionTokens = newConnectionTokens;
3338
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003339 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003340 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003341 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003342 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003343 std::string message = "Interaction with: " + targetList;
3344 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003345 message += "<none>";
3346 }
3347 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3348}
3349
chaviwfd6d3512019-03-25 13:23:49 -07003350void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003351 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003352 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003353 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3354 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003355 return;
3356 }
3357
Vishnu Nairc519ff72021-01-21 08:23:08 -08003358 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003359 if (focusedToken == token) {
3360 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003361 return;
3362 }
3363
Prabir Pradhancef936d2021-07-21 16:17:52 +00003364 auto command = [this, token]() REQUIRES(mLock) {
3365 scoped_unlock unlock(mLock);
3366 mPolicy->onPointerDownOutsideFocus(token);
3367 };
3368 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369}
3370
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003371status_t InputDispatcher::publishMotionEvent(Connection& connection,
3372 DispatchEntry& dispatchEntry) const {
3373 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3374 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3375
3376 PointerCoords scaledCoords[MAX_POINTERS];
3377 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3378
3379 // Set the X and Y offset and X and Y scale depending on the input source.
3380 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003381 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003382 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3383 if (globalScaleFactor != 1.0f) {
3384 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3385 scaledCoords[i] = motionEntry.pointerCoords[i];
3386 // Don't apply window scale here since we don't want scale to affect raw
3387 // coordinates. The scale will be sent back to the client and applied
3388 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003389 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003390 }
3391 usingCoords = scaledCoords;
3392 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003393 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003394 // We don't want the dispatch target to know the coordinates
3395 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3396 scaledCoords[i].clear();
3397 }
3398 usingCoords = scaledCoords;
3399 }
3400
3401 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3402
3403 // Publish the motion event.
3404 return connection.inputPublisher
3405 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3406 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3407 std::move(hmac), dispatchEntry.resolvedAction,
3408 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3409 motionEntry.edgeFlags, motionEntry.metaState,
3410 motionEntry.buttonState, motionEntry.classification,
3411 dispatchEntry.transform, motionEntry.xPrecision,
3412 motionEntry.yPrecision, motionEntry.xCursorPosition,
3413 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3414 motionEntry.downTime, motionEntry.eventTime,
3415 motionEntry.pointerCount, motionEntry.pointerProperties,
3416 usingCoords);
3417}
3418
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003420 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003421 if (ATRACE_ENABLED()) {
3422 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003423 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003424 ATRACE_NAME(message.c_str());
3425 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003426 if (DEBUG_DISPATCH_CYCLE) {
3427 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3428 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003429
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003430 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003431 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003433 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003434 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435
3436 // Publish the event.
3437 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003438 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3439 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003440 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003441 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3442 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003443 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3444 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3445 << connection->getInputChannelName();
3446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003447
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003448 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003449 status = connection->inputPublisher
3450 .publishKeyEvent(dispatchEntry->seq,
3451 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3452 keyEntry.source, keyEntry.displayId,
3453 std::move(hmac), dispatchEntry->resolvedAction,
3454 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3455 keyEntry.scanCode, keyEntry.metaState,
3456 keyEntry.repeatCount, keyEntry.downTime,
3457 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003458 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459 }
3460
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003461 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003462 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3463 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3464 << connection->getInputChannelName();
3465 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003466 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003467 break;
3468 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003469
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003470 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003471 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003472 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003473 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003474 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003475 break;
3476 }
3477
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003478 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3479 const TouchModeEntry& touchModeEntry =
3480 static_cast<const TouchModeEntry&>(eventEntry);
3481 status = connection->inputPublisher
3482 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3483 touchModeEntry.inTouchMode);
3484
3485 break;
3486 }
3487
Prabir Pradhan99987712020-11-10 18:43:05 -08003488 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3489 const auto& captureEntry =
3490 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3491 status = connection->inputPublisher
3492 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003493 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003494 break;
3495 }
3496
arthurhungb89ccb02020-12-30 16:19:01 +08003497 case EventEntry::Type::DRAG: {
3498 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3499 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3500 dragEntry.id, dragEntry.x,
3501 dragEntry.y,
3502 dragEntry.isExiting);
3503 break;
3504 }
3505
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003506 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003507 case EventEntry::Type::DEVICE_RESET:
3508 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003509 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003510 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003511 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003512 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513 }
3514
3515 // Check the result.
3516 if (status) {
3517 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003518 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003519 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003520 "This is unexpected because the wait queue is empty, so the pipe "
3521 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003522 "event to it, status=%s(%d)",
3523 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3524 status);
Harry Cutts33476232023-01-30 19:57:29 +00003525 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526 } else {
3527 // Pipe is full and we are waiting for the app to finish process some events
3528 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003529 if (DEBUG_DISPATCH_CYCLE) {
3530 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3531 "waiting for the application to catch up",
3532 connection->getInputChannelName().c_str());
3533 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534 }
3535 } else {
3536 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003537 "status=%s(%d)",
3538 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3539 status);
Harry Cutts33476232023-01-30 19:57:29 +00003540 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003541 }
3542 return;
3543 }
3544
3545 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003546 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3547 connection->outboundQueue.end(),
3548 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003549 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003550 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003551 if (connection->responsive) {
3552 mAnrTracker.insert(dispatchEntry->timeoutTime,
3553 connection->inputChannel->getConnectionToken());
3554 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003555 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003556 }
3557}
3558
chaviw09c8d2d2020-08-24 15:48:26 -07003559std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3560 size_t size;
3561 switch (event.type) {
3562 case VerifiedInputEvent::Type::KEY: {
3563 size = sizeof(VerifiedKeyEvent);
3564 break;
3565 }
3566 case VerifiedInputEvent::Type::MOTION: {
3567 size = sizeof(VerifiedMotionEvent);
3568 break;
3569 }
3570 }
3571 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3572 return mHmacKeyManager.sign(start, size);
3573}
3574
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003575const std::array<uint8_t, 32> InputDispatcher::getSignature(
3576 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003577 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3578 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003579 // Only sign events up and down events as the purely move events
3580 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003581 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003582 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003583
3584 VerifiedMotionEvent verifiedEvent =
3585 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3586 verifiedEvent.actionMasked = actionMasked;
3587 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3588 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003589}
3590
3591const std::array<uint8_t, 32> InputDispatcher::getSignature(
3592 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3593 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3594 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3595 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003596 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003597}
3598
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003600 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003601 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003602 if (DEBUG_DISPATCH_CYCLE) {
3603 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3604 connection->getInputChannelName().c_str(), seq, toString(handled));
3605 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003607 if (connection->status == Connection::Status::BROKEN ||
3608 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 return;
3610 }
3611
3612 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003613 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3614 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3615 };
3616 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617}
3618
3619void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003620 const sp<Connection>& connection,
3621 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003622 if (DEBUG_DISPATCH_CYCLE) {
3623 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3624 connection->getInputChannelName().c_str(), toString(notify));
3625 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626
3627 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003628 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003629 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003630 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003631 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632
3633 // The connection appears to be unrecoverably broken.
3634 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003635 if (connection->status == Connection::Status::NORMAL) {
3636 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637
3638 if (notify) {
3639 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003640 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3641 connection->getInputChannelName().c_str());
3642
3643 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003644 scoped_unlock unlock(mLock);
3645 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3646 };
3647 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648 }
3649 }
3650}
3651
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003652void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3653 while (!queue.empty()) {
3654 DispatchEntry* dispatchEntry = queue.front();
3655 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003656 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003657 }
3658}
3659
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003660void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003662 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003663 }
3664 delete dispatchEntry;
3665}
3666
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003667int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3668 std::scoped_lock _l(mLock);
3669 sp<Connection> connection = getConnectionLocked(connectionToken);
3670 if (connection == nullptr) {
3671 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3672 connectionToken.get(), events);
3673 return 0; // remove the callback
3674 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003675
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003676 bool notify;
3677 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3678 if (!(events & ALOOPER_EVENT_INPUT)) {
3679 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3680 "events=0x%x",
3681 connection->getInputChannelName().c_str(), events);
3682 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683 }
3684
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003685 nsecs_t currentTime = now();
3686 bool gotOne = false;
3687 status_t status = OK;
3688 for (;;) {
3689 Result<InputPublisher::ConsumerResponse> result =
3690 connection->inputPublisher.receiveConsumerResponse();
3691 if (!result.ok()) {
3692 status = result.error().code();
3693 break;
3694 }
3695
3696 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3697 const InputPublisher::Finished& finish =
3698 std::get<InputPublisher::Finished>(*result);
3699 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3700 finish.consumeTime);
3701 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003702 if (shouldReportMetricsForConnection(*connection)) {
3703 const InputPublisher::Timeline& timeline =
3704 std::get<InputPublisher::Timeline>(*result);
3705 mLatencyTracker
3706 .trackGraphicsLatency(timeline.inputEventId,
3707 connection->inputChannel->getConnectionToken(),
3708 std::move(timeline.graphicsTimeline));
3709 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003710 }
3711 gotOne = true;
3712 }
3713 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003714 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003715 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716 return 1;
3717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003718 }
3719
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003720 notify = status != DEAD_OBJECT || !connection->monitor;
3721 if (notify) {
3722 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3723 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3724 status);
3725 }
3726 } else {
3727 // Monitor channels are never explicitly unregistered.
3728 // We do it automatically when the remote endpoint is closed so don't warn about them.
3729 const bool stillHaveWindowHandle =
3730 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3731 notify = !connection->monitor && stillHaveWindowHandle;
3732 if (notify) {
3733 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3734 connection->getInputChannelName().c_str(), events);
3735 }
3736 }
3737
3738 // Remove the channel.
3739 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3740 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003741}
3742
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003743void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003745 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003746 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003747 }
3748}
3749
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003750void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003751 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003752 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003753 for (const Monitor& monitor : monitors) {
3754 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003755 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003756 }
3757}
3758
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003760 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003761 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003762 if (connection == nullptr) {
3763 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003765
3766 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767}
3768
3769void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3770 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003771 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772 return;
3773 }
3774
3775 nsecs_t currentTime = now();
3776
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003777 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003778 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003780 if (cancelationEvents.empty()) {
3781 return;
3782 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003783 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3784 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003785 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003786 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003787 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003788 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003789
Arthur Hungb3307ee2021-10-14 10:57:37 +00003790 std::string reason = std::string("reason=").append(options.reason);
3791 android_log_event_list(LOGTAG_INPUT_CANCEL)
3792 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3793
Svet Ganov5d3bc372020-01-26 23:11:07 -08003794 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003795 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003796 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3797 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003798 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003799 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003800 target.globalScaleFactor = windowInfo->globalScaleFactor;
3801 }
3802 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003803 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003804
hongzuo liu95785e22022-09-06 02:51:35 +00003805 const bool wasEmpty = connection->outboundQueue.empty();
3806
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003807 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003808 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003809 switch (cancelationEventEntry->type) {
3810 case EventEntry::Type::KEY: {
3811 logOutboundKeyDetails("cancel - ",
3812 static_cast<const KeyEntry&>(*cancelationEventEntry));
3813 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003815 case EventEntry::Type::MOTION: {
3816 logOutboundMotionDetails("cancel - ",
3817 static_cast<const MotionEntry&>(*cancelationEventEntry));
3818 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003820 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003821 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003822 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3823 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003824 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003825 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003826 break;
3827 }
3828 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003829 case EventEntry::Type::DEVICE_RESET:
3830 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003831 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003832 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003833 break;
3834 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835 }
3836
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003837 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003838 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003840
hongzuo liu95785e22022-09-06 02:51:35 +00003841 // If the outbound queue was previously empty, start the dispatch cycle going.
3842 if (wasEmpty && !connection->outboundQueue.empty()) {
3843 startDispatchCycleLocked(currentTime, connection);
3844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003845}
3846
Svet Ganov5d3bc372020-01-26 23:11:07 -08003847void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Arthur Hungc539dbb2022-12-08 07:45:36 +00003848 const nsecs_t downTime, const sp<Connection>& connection,
3849 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003850 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003851 return;
3852 }
3853
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003854 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003855 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003856
3857 if (downEvents.empty()) {
3858 return;
3859 }
3860
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003861 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003862 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3863 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003864 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003865
3866 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003867 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003868 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3869 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003870 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003871 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003872 target.globalScaleFactor = windowInfo->globalScaleFactor;
3873 }
3874 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00003875 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003876
hongzuo liu95785e22022-09-06 02:51:35 +00003877 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003878 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003879 switch (downEventEntry->type) {
3880 case EventEntry::Type::MOTION: {
3881 logOutboundMotionDetails("down - ",
3882 static_cast<const MotionEntry&>(*downEventEntry));
3883 break;
3884 }
3885
3886 case EventEntry::Type::KEY:
3887 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003888 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003889 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003890 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003891 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003892 case EventEntry::Type::SENSOR:
3893 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003894 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003895 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003896 break;
3897 }
3898 }
3899
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003900 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003901 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003902 }
3903
hongzuo liu95785e22022-09-06 02:51:35 +00003904 // If the outbound queue was previously empty, start the dispatch cycle going.
3905 if (wasEmpty && !connection->outboundQueue.empty()) {
3906 startDispatchCycleLocked(downTime, connection);
3907 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003908}
3909
Arthur Hungc539dbb2022-12-08 07:45:36 +00003910void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
3911 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
3912 if (windowHandle != nullptr) {
3913 sp<Connection> wallpaperConnection = getConnectionLocked(windowHandle->getToken());
3914 if (wallpaperConnection != nullptr) {
3915 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
3916 }
3917 }
3918}
3919
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003920std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003921 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
3922 nsecs_t splitDownTime) {
3923 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924
3925 uint32_t splitPointerIndexMap[MAX_POINTERS];
3926 PointerProperties splitPointerProperties[MAX_POINTERS];
3927 PointerCoords splitPointerCoords[MAX_POINTERS];
3928
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003929 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003930 uint32_t splitPointerCount = 0;
3931
3932 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003933 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003934 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003935 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003937 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3939 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3940 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003941 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003942 splitPointerCount += 1;
3943 }
3944 }
3945
3946 if (splitPointerCount != pointerIds.count()) {
3947 // This is bad. We are missing some of the pointers that we expected to deliver.
3948 // Most likely this indicates that we received an ACTION_MOVE events that has
3949 // different pointer ids than we expected based on the previous ACTION_DOWN
3950 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3951 // in this way.
3952 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003953 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003954 "a broken sequence of pointer ids from the input device: %s",
3955 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07003956 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 }
3958
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003959 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003961 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3962 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3964 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003965 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003967 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968 if (pointerIds.count() == 1) {
3969 // The first/last pointer went down/up.
3970 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003971 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003972 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3973 ? AMOTION_EVENT_ACTION_CANCEL
3974 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 } else {
3976 // A secondary pointer went down/up.
3977 uint32_t splitPointerIndex = 0;
3978 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3979 splitPointerIndex += 1;
3980 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003981 action = maskedAction |
3982 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983 }
3984 } else {
3985 // An unrelated pointer changed.
3986 action = AMOTION_EVENT_ACTION_MOVE;
3987 }
3988 }
3989
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003990 if (action == AMOTION_EVENT_ACTION_DOWN) {
3991 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3992 "Split motion event has mismatching downTime and eventTime for "
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08003993 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
3994 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003995 }
3996
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003997 int32_t newId = mIdGenerator.nextId();
3998 if (ATRACE_ENABLED()) {
3999 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
4000 ") to MotionEvent(id=0x%" PRIx32 ").",
4001 originalMotionEntry.id, newId);
4002 ATRACE_NAME(message.c_str());
4003 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004004 std::unique_ptr<MotionEntry> splitMotionEntry =
4005 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4006 originalMotionEntry.deviceId, originalMotionEntry.source,
4007 originalMotionEntry.displayId,
4008 originalMotionEntry.policyFlags, action,
4009 originalMotionEntry.actionButton,
4010 originalMotionEntry.flags, originalMotionEntry.metaState,
4011 originalMotionEntry.buttonState,
4012 originalMotionEntry.classification,
4013 originalMotionEntry.edgeFlags,
4014 originalMotionEntry.xPrecision,
4015 originalMotionEntry.yPrecision,
4016 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004017 originalMotionEntry.yCursorPosition, splitDownTime,
4018 splitPointerCount, splitPointerProperties,
4019 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004020
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004021 if (originalMotionEntry.injectionState) {
4022 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004023 splitMotionEntry->injectionState->refCount += 1;
4024 }
4025
4026 return splitMotionEntry;
4027}
4028
4029void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004030 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004031 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
4032 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033
Antonio Kantekf16f2832021-09-28 04:39:20 +00004034 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004035 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004036 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004038 std::unique_ptr<ConfigurationChangedEntry> newEntry =
4039 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
4040 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004041 } // release lock
4042
4043 if (needWake) {
4044 mLooper->wake();
4045 }
4046}
4047
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004048/**
4049 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004050 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4051 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4052 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4053 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4054 * potentially handle the back key presses.
4055 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4056 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004057 */
4058void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004059 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004060 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4061 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004062 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004063 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004064 }
4065 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004066 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004067 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004068 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004069 keyCode = newKeyCode;
4070 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4071 }
4072 } else if (action == AKEY_EVENT_ACTION_UP) {
4073 // In order to maintain a consistent stream of up and down events, check to see if the key
4074 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4075 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004076 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004077 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004078 auto replacementIt = mReplacedKeys.find(replacement);
4079 if (replacementIt != mReplacedKeys.end()) {
4080 keyCode = replacementIt->second;
4081 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004082 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4083 }
4084 }
4085}
4086
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004088 ALOGD_IF(debugInboundEventDetails(),
4089 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4090 ", deviceId=%d, source=%s, displayId=%" PRId32
4091 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4092 "downTime=%" PRId64,
4093 args->id, args->eventTime, args->deviceId,
4094 inputEventSourceToString(args->source).c_str(), args->displayId, args->policyFlags,
4095 KeyEvent::actionToString(args->action), args->flags, KeyEvent::getLabel(args->keyCode),
4096 args->scanCode, args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 if (!validateKeyEvent(args->action)) {
4098 return;
4099 }
4100
4101 uint32_t policyFlags = args->policyFlags;
4102 int32_t flags = args->flags;
4103 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004104 // InputDispatcher tracks and generates key repeats on behalf of
4105 // whatever notifies it, so repeatCount should always be set to 0
4106 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4108 policyFlags |= POLICY_FLAG_VIRTUAL;
4109 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4110 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111 if (policyFlags & POLICY_FLAG_FUNCTION) {
4112 metaState |= AMETA_FUNCTION_ON;
4113 }
4114
4115 policyFlags |= POLICY_FLAG_TRUSTED;
4116
Michael Wright78f24442014-08-06 15:55:28 -07004117 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004118 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004119
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004121 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08004122 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
4123 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124
Michael Wright2b3c3302018-03-02 17:19:13 +00004125 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004127 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4128 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004129 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004130 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131
Antonio Kantekf16f2832021-09-28 04:39:20 +00004132 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133 { // acquire lock
4134 mLock.lock();
4135
4136 if (shouldSendKeyToInputFilterLocked(args)) {
4137 mLock.unlock();
4138
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004139 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4141 return; // event was consumed by the filter
4142 }
4143
4144 mLock.lock();
4145 }
4146
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004147 std::unique_ptr<KeyEntry> newEntry =
4148 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4149 args->displayId, policyFlags, args->action, flags,
4150 keyCode, args->scanCode, metaState, repeatCount,
4151 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004153 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154 mLock.unlock();
4155 } // release lock
4156
4157 if (needWake) {
4158 mLooper->wake();
4159 }
4160}
4161
4162bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4163 return mInputFilterEnabled;
4164}
4165
4166void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004167 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004168 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004169 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004170 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004171 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4172 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhan96282b02023-02-24 22:36:17 +00004173 args->id, args->eventTime, args->deviceId,
4174 inputEventSourceToString(args->source).c_str(), args->displayId, args->policyFlags,
4175 MotionEvent::actionToString(args->action).c_str(), args->actionButton, args->flags,
4176 args->metaState, args->buttonState, args->edgeFlags, args->xPrecision,
4177 args->yPrecision, args->xCursorPosition, args->yCursorPosition, args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004178 for (uint32_t i = 0; i < args->pointerCount; i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004179 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4180 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
4181 i, args->pointerProperties[i].id,
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07004182 ftl::enum_string(args->pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004183 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4184 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4185 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4186 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4187 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4188 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4189 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4190 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4191 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4192 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193 }
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004194
4195 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4196 args->pointerProperties)) {
4197 LOG(ERROR) << "Invalid event: " << args->dump();
4198 return;
4199 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200
4201 uint32_t policyFlags = args->policyFlags;
4202 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004203
4204 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004205 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004206 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4207 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004208 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004209 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004210
Antonio Kantekf16f2832021-09-28 04:39:20 +00004211 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212 { // acquire lock
4213 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004214 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4215 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4216 // complete the processing of the current stroke.
4217 const auto touchStateIt = mTouchStatesByDisplay.find(args->displayId);
4218 if (touchStateIt != mTouchStatesByDisplay.end()) {
4219 const TouchState& touchState = touchStateIt->second;
4220 if (touchState.deviceId == args->deviceId && touchState.isDown()) {
4221 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4222 }
4223 }
4224 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225
4226 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004227 ui::Transform displayTransform;
4228 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4229 displayTransform = it->second.transform;
4230 }
4231
Michael Wrightd02c5b62014-02-10 15:10:22 -08004232 mLock.unlock();
4233
4234 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004235 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4236 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004237 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004238 displayTransform, args->xPrecision, args->yPrecision,
4239 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004240 args->downTime, args->eventTime, args->pointerCount,
4241 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242
4243 policyFlags |= POLICY_FLAG_FILTERED;
4244 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4245 return; // event was consumed by the filter
4246 }
4247
4248 mLock.lock();
4249 }
4250
4251 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004252 std::unique_ptr<MotionEntry> newEntry =
4253 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4254 args->source, args->displayId, policyFlags,
4255 args->action, args->actionButton, args->flags,
4256 args->metaState, args->buttonState,
4257 args->classification, args->edgeFlags,
4258 args->xPrecision, args->yPrecision,
4259 args->xCursorPosition, args->yCursorPosition,
4260 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004261 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004263 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4264 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4265 !mInputFilterEnabled) {
4266 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4267 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4268 }
4269
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004270 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271 mLock.unlock();
4272 } // release lock
4273
4274 if (needWake) {
4275 mLooper->wake();
4276 }
4277}
4278
Chris Yef59a2f42020-10-16 12:55:26 -07004279void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004280 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004281 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4282 " sensorType=%s",
4283 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004284 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004285 }
Chris Yef59a2f42020-10-16 12:55:26 -07004286
Antonio Kantekf16f2832021-09-28 04:39:20 +00004287 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004288 { // acquire lock
4289 mLock.lock();
4290
4291 // Just enqueue a new sensor event.
4292 std::unique_ptr<SensorEntry> newEntry =
4293 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
Harry Cutts33476232023-01-30 19:57:29 +00004294 args->source, /* policyFlags=*/0, args->hwTimestamp,
Chris Yef59a2f42020-10-16 12:55:26 -07004295 args->sensorType, args->accuracy,
4296 args->accuracyChanged, args->values);
4297
4298 needWake = enqueueInboundEventLocked(std::move(newEntry));
4299 mLock.unlock();
4300 } // release lock
4301
4302 if (needWake) {
4303 mLooper->wake();
4304 }
4305}
4306
Chris Yefb552902021-02-03 17:18:37 -08004307void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004308 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004309 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4310 args->deviceId, args->isOn);
4311 }
Chris Yefb552902021-02-03 17:18:37 -08004312 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4313}
4314
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004316 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317}
4318
4319void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004320 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004321 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4322 "switchMask=0x%08x",
4323 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4324 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325
4326 uint32_t policyFlags = args->policyFlags;
4327 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004328 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329}
4330
4331void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004332 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004333 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4334 args->deviceId);
4335 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336
Antonio Kantekf16f2832021-09-28 04:39:20 +00004337 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004339 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004341 std::unique_ptr<DeviceResetEntry> newEntry =
4342 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4343 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344 } // release lock
4345
4346 if (needWake) {
4347 mLooper->wake();
4348 }
4349}
4350
Prabir Pradhan7e186182020-11-10 13:56:45 -08004351void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004352 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004353 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004354 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004355 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004356
Antonio Kantekf16f2832021-09-28 04:39:20 +00004357 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004358 { // acquire lock
4359 std::scoped_lock _l(mLock);
4360 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004361 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004362 needWake = enqueueInboundEventLocked(std::move(entry));
4363 } // release lock
4364
4365 if (needWake) {
4366 mLooper->wake();
4367 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004368}
4369
Prabir Pradhan5735a322022-04-11 17:23:34 +00004370InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4371 std::optional<int32_t> targetUid,
4372 InputEventInjectionSync syncMode,
4373 std::chrono::milliseconds timeout,
4374 uint32_t policyFlags) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004375 if (debugInboundEventDetails()) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004376 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4377 "policyFlags=0x%08x",
4378 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4379 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004380 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004381 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382
Prabir Pradhan5735a322022-04-11 17:23:34 +00004383 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004385 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004386 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4387 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4388 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4389 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4390 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004391 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004392 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004393 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004394 }
4395
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004396 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004397 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004398 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004399 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4400 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004401 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004402 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004403 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004405 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004406 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4407 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4408 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004409 int32_t keyCode = incomingKey.getKeyCode();
4410 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004411 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004412 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004413 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004414 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004415 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4416 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4417 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004418
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004419 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4420 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004421 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004422
4423 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4424 android::base::Timer t;
4425 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4426 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4427 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4428 std::to_string(t.duration().count()).c_str());
4429 }
4430 }
4431
4432 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004433 std::unique_ptr<KeyEntry> injectedEntry =
4434 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004435 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004436 incomingKey.getDisplayId(), policyFlags, action,
4437 flags, keyCode, incomingKey.getScanCode(), metaState,
4438 incomingKey.getRepeatCount(),
4439 incomingKey.getDownTime());
4440 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004441 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004442 }
4443
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004444 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004445 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004446 const int32_t action = motionEvent.getAction();
4447 const bool isPointerEvent =
4448 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4449 // If a pointer event has no displayId specified, inject it to the default display.
4450 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4451 ? ADISPLAY_ID_DEFAULT
4452 : event->getDisplayId();
4453 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004454 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004455 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004456 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004457 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004458 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004459 }
4460
4461 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004462 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004463 android::base::Timer t;
4464 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4465 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4466 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4467 std::to_string(t.duration().count()).c_str());
4468 }
4469 }
4470
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004471 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4472 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4473 }
4474
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004475 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004476 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4477 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004478 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004479 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4480 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004481 displayId, policyFlags, action, actionButton,
4482 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004483 motionEvent.getButtonState(),
4484 motionEvent.getClassification(),
4485 motionEvent.getEdgeFlags(),
4486 motionEvent.getXPrecision(),
4487 motionEvent.getYPrecision(),
4488 motionEvent.getRawXCursorPosition(),
4489 motionEvent.getRawYCursorPosition(),
4490 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004491 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004492 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004493 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004494 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004495 sampleEventTimes += 1;
4496 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004497 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004498 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4499 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004500 displayId, policyFlags, action, actionButton,
4501 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004502 motionEvent.getButtonState(),
4503 motionEvent.getClassification(),
4504 motionEvent.getEdgeFlags(),
4505 motionEvent.getXPrecision(),
4506 motionEvent.getYPrecision(),
4507 motionEvent.getRawXCursorPosition(),
4508 motionEvent.getRawYCursorPosition(),
4509 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004510 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004511 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004512 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4513 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004514 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004515 }
4516 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004517 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004518
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004519 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004520 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004521 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004522 }
4523
Prabir Pradhan5735a322022-04-11 17:23:34 +00004524 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004525 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526 injectionState->injectionIsAsync = true;
4527 }
4528
4529 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004530 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004531
4532 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004533 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004534 if (DEBUG_INJECTION) {
4535 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4536 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004537 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004538 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004539 }
4540
4541 mLock.unlock();
4542
4543 if (needWake) {
4544 mLooper->wake();
4545 }
4546
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004547 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004548 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004549 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004550
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004551 if (syncMode == InputEventInjectionSync::NONE) {
4552 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553 } else {
4554 for (;;) {
4555 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004556 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557 break;
4558 }
4559
4560 nsecs_t remainingTimeout = endTime - now();
4561 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004562 if (DEBUG_INJECTION) {
4563 ALOGD("injectInputEvent - Timed out waiting for injection result "
4564 "to become available.");
4565 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004566 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004567 break;
4568 }
4569
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004570 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004571 }
4572
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004573 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4574 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004576 if (DEBUG_INJECTION) {
4577 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4578 injectionState->pendingForegroundDispatches);
4579 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004580 nsecs_t remainingTimeout = endTime - now();
4581 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004582 if (DEBUG_INJECTION) {
4583 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4584 "dispatches to finish.");
4585 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004586 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587 break;
4588 }
4589
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004590 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004591 }
4592 }
4593 }
4594
4595 injectionState->release();
4596 } // release lock
4597
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004598 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004599 LOG(DEBUG) << "injectInputEvent - Finished with result "
4600 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004601 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004602
4603 return injectionResult;
4604}
4605
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004606std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004607 std::array<uint8_t, 32> calculatedHmac;
4608 std::unique_ptr<VerifiedInputEvent> result;
4609 switch (event.getType()) {
4610 case AINPUT_EVENT_TYPE_KEY: {
4611 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4612 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4613 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004614 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004615 break;
4616 }
4617 case AINPUT_EVENT_TYPE_MOTION: {
4618 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4619 VerifiedMotionEvent verifiedMotionEvent =
4620 verifiedMotionEventFromMotionEvent(motionEvent);
4621 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004622 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004623 break;
4624 }
4625 default: {
4626 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4627 return nullptr;
4628 }
4629 }
4630 if (calculatedHmac == INVALID_HMAC) {
4631 return nullptr;
4632 }
4633 if (calculatedHmac != event.getHmac()) {
4634 return nullptr;
4635 }
4636 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004637}
4638
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004639void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004640 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004641 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004642 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004643 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004644 LOG(DEBUG) << "Setting input event injection result to "
4645 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004646 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004647
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004648 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004649 // Log the outcome since the injector did not wait for the injection result.
4650 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004651 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004652 ALOGV("Asynchronous input event injection succeeded.");
4653 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004654 case InputEventInjectionResult::TARGET_MISMATCH:
4655 ALOGV("Asynchronous input event injection target mismatch.");
4656 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004657 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004658 ALOGW("Asynchronous input event injection failed.");
4659 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004660 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004661 ALOGW("Asynchronous input event injection timed out.");
4662 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004663 case InputEventInjectionResult::PENDING:
4664 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4665 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004666 }
4667 }
4668
4669 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004670 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004671 }
4672}
4673
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004674void InputDispatcher::transformMotionEntryForInjectionLocked(
4675 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004676 // Input injection works in the logical display coordinate space, but the input pipeline works
4677 // display space, so we need to transform the injected events accordingly.
4678 const auto it = mDisplayInfos.find(entry.displayId);
4679 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004680 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004681
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004682 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4683 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4684 const vec2 cursor =
4685 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4686 {entry.xCursorPosition, entry.yCursorPosition});
4687 entry.xCursorPosition = cursor.x;
4688 entry.yCursorPosition = cursor.y;
4689 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004690 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004691 entry.pointerCoords[i] =
4692 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4693 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004694 }
4695}
4696
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004697void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4698 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004699 if (injectionState) {
4700 injectionState->pendingForegroundDispatches += 1;
4701 }
4702}
4703
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004704void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4705 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004706 if (injectionState) {
4707 injectionState->pendingForegroundDispatches -= 1;
4708
4709 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004710 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711 }
4712 }
4713}
4714
chaviw98318de2021-05-19 16:45:23 -05004715const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004716 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004717 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004718 auto it = mWindowHandlesByDisplay.find(displayId);
4719 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004720}
4721
chaviw98318de2021-05-19 16:45:23 -05004722sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004723 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004724 if (windowHandleToken == nullptr) {
4725 return nullptr;
4726 }
4727
Arthur Hungb92218b2018-08-14 12:00:21 +08004728 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004729 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4730 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004731 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004732 return windowHandle;
4733 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004734 }
4735 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004736 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004737}
4738
chaviw98318de2021-05-19 16:45:23 -05004739sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4740 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004741 if (windowHandleToken == nullptr) {
4742 return nullptr;
4743 }
4744
chaviw98318de2021-05-19 16:45:23 -05004745 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004746 if (windowHandle->getToken() == windowHandleToken) {
4747 return windowHandle;
4748 }
4749 }
4750 return nullptr;
4751}
4752
chaviw98318de2021-05-19 16:45:23 -05004753sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4754 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004755 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004756 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4757 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004758 if (handle->getId() == windowHandle->getId() &&
4759 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004760 if (windowHandle->getInfo()->displayId != it.first) {
4761 ALOGE("Found window %s in display %" PRId32
4762 ", but it should belong to display %" PRId32,
4763 windowHandle->getName().c_str(), it.first,
4764 windowHandle->getInfo()->displayId);
4765 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004766 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004767 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768 }
4769 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004770 return nullptr;
4771}
4772
chaviw98318de2021-05-19 16:45:23 -05004773sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004774 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4775 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004776}
4777
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004778ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4779 auto displayInfoIt = mDisplayInfos.find(displayId);
4780 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4781 : kIdentityTransform;
4782}
4783
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004784bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4785 const MotionEntry& motionEntry) const {
4786 const WindowInfo& info = *window->getInfo();
4787
4788 // Skip spy window targets that are not valid for targeted injection.
4789 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004790 return false;
4791 }
4792
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004793 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4794 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4795 return false;
4796 }
4797
4798 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4799 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4800 window->getName().c_str());
4801 return false;
4802 }
4803
4804 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004805 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004806 ALOGW("Not sending touch to %s because there's no corresponding connection",
4807 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004808 return false;
4809 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004810
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004811 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004812 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004813 return false;
4814 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004815
4816 // Drop events that can't be trusted due to occlusion
4817 const auto [x, y] = resolveTouchedPosition(motionEntry);
4818 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4819 if (!isTouchTrustedLocked(occlusionInfo)) {
4820 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004821 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004822 for (const auto& log : occlusionInfo.debugInfo) {
4823 ALOGD("%s", log.c_str());
4824 }
4825 }
4826 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4827 occlusionInfo.obscuringUid);
4828 return false;
4829 }
4830
4831 // Drop touch events if requested by input feature
4832 if (shouldDropInput(motionEntry, window)) {
4833 return false;
4834 }
4835
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004836 return true;
4837}
4838
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004839std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4840 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004841 auto connectionIt = mConnectionsByToken.find(token);
4842 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004843 return nullptr;
4844 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004845 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004846}
4847
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004848void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004849 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4850 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004851 // Remove all handles on a display if there are no windows left.
4852 mWindowHandlesByDisplay.erase(displayId);
4853 return;
4854 }
4855
4856 // Since we compare the pointer of input window handles across window updates, we need
4857 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004858 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4859 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4860 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004861 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004862 }
4863
chaviw98318de2021-05-19 16:45:23 -05004864 std::vector<sp<WindowInfoHandle>> newHandles;
4865 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004866 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004867 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004868 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004869 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004870 const bool canReceiveInput =
4871 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4872 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004873 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004874 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004875 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004876 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004877 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004878 }
4879
4880 if (info->displayId != displayId) {
4881 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4882 handle->getName().c_str(), displayId, info->displayId);
4883 continue;
4884 }
4885
Robert Carredd13602020-04-13 17:24:34 -07004886 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4887 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004888 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004889 oldHandle->updateFrom(handle);
4890 newHandles.push_back(oldHandle);
4891 } else {
4892 newHandles.push_back(handle);
4893 }
4894 }
4895
4896 // Insert or replace
4897 mWindowHandlesByDisplay[displayId] = newHandles;
4898}
4899
Arthur Hung72d8dc32020-03-28 00:48:39 +00004900void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004901 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004902 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004903 { // acquire lock
4904 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004905 for (const auto& [displayId, handles] : handlesPerDisplay) {
4906 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004907 }
4908 }
4909 // Wake up poll loop since it may need to make new input dispatching choices.
4910 mLooper->wake();
4911}
4912
Arthur Hungb92218b2018-08-14 12:00:21 +08004913/**
4914 * Called from InputManagerService, update window handle list by displayId that can receive input.
4915 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4916 * If set an empty list, remove all handles from the specific display.
4917 * For focused handle, check if need to change and send a cancel event to previous one.
4918 * For removed handle, check if need to send a cancel event if already in touch.
4919 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004920void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004921 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004922 if (DEBUG_FOCUS) {
4923 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004924 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004925 windowList += iwh->getName() + " ";
4926 }
4927 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4928 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004929
Prabir Pradhand65552b2021-10-07 11:23:50 -07004930 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004931 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004932 const WindowInfo& info = *window->getInfo();
4933
4934 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004935 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004936 if (noInputWindow && window->getToken() != nullptr) {
4937 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4938 window->getName().c_str());
4939 window->releaseChannel();
4940 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004941
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004942 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004943 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4944 !info.inputConfig.test(
4945 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004946 "%s has feature SPY, but is not a trusted overlay.",
4947 window->getName().c_str());
4948
Prabir Pradhand65552b2021-10-07 11:23:50 -07004949 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004950 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4951 !info.inputConfig.test(
4952 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004953 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4954 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004955 }
4956
Arthur Hung72d8dc32020-03-28 00:48:39 +00004957 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004958 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004960 // Save the old windows' orientation by ID before it gets updated.
4961 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004962 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004963 oldWindowOrientations.emplace(handle->getId(),
4964 handle->getInfo()->transform.getOrientation());
4965 }
4966
chaviw98318de2021-05-19 16:45:23 -05004967 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004968
chaviw98318de2021-05-19 16:45:23 -05004969 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004970
Vishnu Nairc519ff72021-01-21 08:23:08 -08004971 std::optional<FocusResolver::FocusChanges> changes =
4972 mFocusResolver.setInputWindows(displayId, windowHandles);
4973 if (changes) {
4974 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004975 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004976
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004977 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4978 mTouchStatesByDisplay.find(displayId);
4979 if (stateIt != mTouchStatesByDisplay.end()) {
4980 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004981 for (size_t i = 0; i < state.windows.size();) {
4982 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004983 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004984 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004985 ALOGD("Touched window was removed: %s in display %" PRId32,
4986 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004987 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004988 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004989 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4990 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004991 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00004992 "touched window was removed");
4993 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004994 // Since we are about to drop the touch, cancel the events for the wallpaper as
4995 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004996 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004997 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4998 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004999 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005000 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005001 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005002 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005003 state.windows.erase(state.windows.begin() + i);
5004 } else {
5005 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005006 }
5007 }
arthurhungb89ccb02020-12-30 16:19:01 +08005008
arthurhung6d4bed92021-03-17 11:59:33 +08005009 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005010 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005011 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005012 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005013 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005014 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5015 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005016 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005017 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005018 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005019
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005020 // Determine if the orientation of any of the input windows have changed, and cancel all
5021 // pointer events if necessary.
5022 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
5023 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
5024 if (newWindowHandle != nullptr &&
5025 newWindowHandle->getInfo()->transform.getOrientation() !=
5026 oldWindowOrientations[oldWindowHandle->getId()]) {
5027 std::shared_ptr<InputChannel> inputChannel =
5028 getInputChannelLocked(newWindowHandle->getToken());
5029 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005030 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005031 "touched window's orientation changed");
5032 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005033 }
5034 }
5035 }
5036
Arthur Hung72d8dc32020-03-28 00:48:39 +00005037 // Release information for windows that are no longer present.
5038 // This ensures that unused input channels are released promptly.
5039 // Otherwise, they might stick around until the window handle is destroyed
5040 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005041 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005042 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005043 if (DEBUG_FOCUS) {
5044 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005045 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005046 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005047 }
chaviw291d88a2019-02-14 10:33:58 -08005048 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005049}
5050
5051void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005052 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005053 if (DEBUG_FOCUS) {
5054 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5055 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5056 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005057 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005058 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005059 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005060 } // release lock
5061
5062 // Wake up poll loop since it may need to make new input dispatching choices.
5063 mLooper->wake();
5064}
5065
Vishnu Nair599f1412021-06-21 10:39:58 -07005066void InputDispatcher::setFocusedApplicationLocked(
5067 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5068 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5069 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5070
5071 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5072 return; // This application is already focused. No need to wake up or change anything.
5073 }
5074
5075 // Set the new application handle.
5076 if (inputApplicationHandle != nullptr) {
5077 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5078 } else {
5079 mFocusedApplicationHandlesByDisplay.erase(displayId);
5080 }
5081
5082 // No matter what the old focused application was, stop waiting on it because it is
5083 // no longer focused.
5084 resetNoFocusedWindowTimeoutLocked();
5085}
5086
Tiger Huang721e26f2018-07-24 22:26:19 +08005087/**
5088 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5089 * the display not specified.
5090 *
5091 * We track any unreleased events for each window. If a window loses the ability to receive the
5092 * released event, we will send a cancel event to it. So when the focused display is changed, we
5093 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5094 * display. The display-specified events won't be affected.
5095 */
5096void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005097 if (DEBUG_FOCUS) {
5098 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5099 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005100 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005101 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005102
5103 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005104 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005105 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005106 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005107 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005108 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005109 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005110 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005111 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005112 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005113 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005114 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5115 }
5116 }
5117 mFocusedDisplayId = displayId;
5118
Chris Ye3c2d6f52020-08-09 10:39:48 -07005119 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005120 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005121 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005122
Vishnu Nairad321cd2020-08-20 16:40:21 -07005123 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005124 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005125 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005126 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005127 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005128 }
5129 }
5130 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005131 } // release lock
5132
5133 // Wake up poll loop since it may need to make new input dispatching choices.
5134 mLooper->wake();
5135}
5136
Michael Wrightd02c5b62014-02-10 15:10:22 -08005137void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005138 if (DEBUG_FOCUS) {
5139 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5140 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141
5142 bool changed;
5143 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005144 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145
5146 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5147 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005148 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005149 }
5150
5151 if (mDispatchEnabled && !enabled) {
5152 resetAndDropEverythingLocked("dispatcher is being disabled");
5153 }
5154
5155 mDispatchEnabled = enabled;
5156 mDispatchFrozen = frozen;
5157 changed = true;
5158 } else {
5159 changed = false;
5160 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005161 } // release lock
5162
5163 if (changed) {
5164 // Wake up poll loop since it may need to make new input dispatching choices.
5165 mLooper->wake();
5166 }
5167}
5168
5169void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005170 if (DEBUG_FOCUS) {
5171 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5172 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173
5174 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005175 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176
5177 if (mInputFilterEnabled == enabled) {
5178 return;
5179 }
5180
5181 mInputFilterEnabled = enabled;
5182 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5183 } // release lock
5184
5185 // Wake up poll loop since there might be work to do to drop everything.
5186 mLooper->wake();
5187}
5188
Antonio Kanteka042c022022-07-06 16:51:07 -07005189bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5190 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005191 bool needWake = false;
5192 {
5193 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005194 ALOGD_IF(DEBUG_TOUCH_MODE,
5195 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5196 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5197 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5198 mTouchModePerDisplay.count(displayId) == 0
5199 ? "not set"
5200 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5201
Antonio Kantek15beb512022-06-13 22:35:41 +00005202 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5203 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005204 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005205 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005206 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005207 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5208 !recentWindowsAreOwnedByLocked(pid, uid)) {
5209 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5210 "window nor none of the previously interacted window",
5211 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005212 return false;
5213 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005214 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005215 mTouchModePerDisplay[displayId] = inTouchMode;
5216 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5217 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005218 needWake = enqueueInboundEventLocked(std::move(entry));
5219 } // release lock
5220
5221 if (needWake) {
5222 mLooper->wake();
5223 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005224 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005225}
5226
Antonio Kantek48710e42022-03-24 14:19:30 -07005227bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5228 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5229 if (focusedToken == nullptr) {
5230 return false;
5231 }
5232 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5233 return isWindowOwnedBy(windowHandle, pid, uid);
5234}
5235
5236bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5237 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5238 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5239 const sp<WindowInfoHandle> windowHandle =
5240 getWindowHandleLocked(connectionToken);
5241 return isWindowOwnedBy(windowHandle, pid, uid);
5242 }) != mInteractionConnectionTokens.end();
5243}
5244
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005245void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5246 if (opacity < 0 || opacity > 1) {
5247 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5248 return;
5249 }
5250
5251 std::scoped_lock lock(mLock);
5252 mMaximumObscuringOpacityForTouch = opacity;
5253}
5254
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005255std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5256InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005257 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5258 for (TouchedWindow& w : state.windows) {
5259 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005260 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005261 }
5262 }
5263 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005264 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005265}
5266
arthurhungb89ccb02020-12-30 16:19:01 +08005267bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5268 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005269 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005270 if (DEBUG_FOCUS) {
5271 ALOGD("Trivial transfer to same window.");
5272 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005273 return true;
5274 }
5275
Michael Wrightd02c5b62014-02-10 15:10:22 -08005276 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005277 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005278
Arthur Hungabbb9d82021-09-01 14:52:30 +00005279 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005280 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005281 if (state == nullptr || touchedWindow == nullptr) {
5282 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005283 return false;
5284 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005285
Arthur Hungabbb9d82021-09-01 14:52:30 +00005286 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5287 if (toWindowHandle == nullptr) {
5288 ALOGW("Cannot transfer focus because to window not found.");
5289 return false;
5290 }
5291
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005292 if (DEBUG_FOCUS) {
5293 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005294 touchedWindow->windowHandle->getName().c_str(),
5295 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005296 }
5297
Arthur Hungabbb9d82021-09-01 14:52:30 +00005298 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005299 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005300 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005301 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005302 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005303
Arthur Hungabbb9d82021-09-01 14:52:30 +00005304 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005305 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005306 ftl::Flags<InputTarget::Flags> newTargetFlags =
5307 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005308 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005309 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005310 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005311 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005312
Arthur Hungabbb9d82021-09-01 14:52:30 +00005313 // Store the dragging window.
5314 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005315 if (pointerIds.count() != 1) {
5316 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5317 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005318 return false;
5319 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005320 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005321 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005322 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323 }
5324
Arthur Hungabbb9d82021-09-01 14:52:30 +00005325 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005326 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5327 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005328 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005329 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005330 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005331 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005332 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005333 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005334 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5335 newTargetFlags);
5336
5337 // Check if the wallpaper window should deliver the corresponding event.
5338 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5339 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005340 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005341 } // release lock
5342
5343 // Wake up poll loop since it may need to make new input dispatching choices.
5344 mLooper->wake();
5345 return true;
5346}
5347
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005348/**
5349 * Get the touched foreground window on the given display.
5350 * Return null if there are no windows touched on that display, or if more than one foreground
5351 * window is being touched.
5352 */
5353sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5354 auto stateIt = mTouchStatesByDisplay.find(displayId);
5355 if (stateIt == mTouchStatesByDisplay.end()) {
5356 ALOGI("No touch state on display %" PRId32, displayId);
5357 return nullptr;
5358 }
5359
5360 const TouchState& state = stateIt->second;
5361 sp<WindowInfoHandle> touchedForegroundWindow;
5362 // If multiple foreground windows are touched, return nullptr
5363 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005364 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005365 if (touchedForegroundWindow != nullptr) {
5366 ALOGI("Two or more foreground windows: %s and %s",
5367 touchedForegroundWindow->getName().c_str(),
5368 window.windowHandle->getName().c_str());
5369 return nullptr;
5370 }
5371 touchedForegroundWindow = window.windowHandle;
5372 }
5373 }
5374 return touchedForegroundWindow;
5375}
5376
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005377// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005378bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005379 sp<IBinder> fromToken;
5380 { // acquire lock
5381 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005382 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005383 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005384 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5385 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005386 return false;
5387 }
5388
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005389 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5390 if (from == nullptr) {
5391 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5392 return false;
5393 }
5394
5395 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005396 } // release lock
5397
5398 return transferTouchFocus(fromToken, destChannelToken);
5399}
5400
Michael Wrightd02c5b62014-02-10 15:10:22 -08005401void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005402 if (DEBUG_FOCUS) {
5403 ALOGD("Resetting and dropping all events (%s).", reason);
5404 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005405
Michael Wrightfb04fd52022-11-24 22:31:11 +00005406 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005407 synthesizeCancelationEventsForAllConnectionsLocked(options);
5408
5409 resetKeyRepeatLocked();
5410 releasePendingEventLocked();
5411 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005412 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005413
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005414 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005415 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005416 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005417}
5418
5419void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005420 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005421 dumpDispatchStateLocked(dump);
5422
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005423 std::istringstream stream(dump);
5424 std::string line;
5425
5426 while (std::getline(stream, line, '\n')) {
5427 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005428 }
5429}
5430
Prabir Pradhan99987712020-11-10 18:43:05 -08005431std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5432 std::string dump;
5433
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005434 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5435 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005436
5437 std::string windowName = "None";
5438 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005439 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005440 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5441 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5442 : "token has capture without window";
5443 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005444 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005445
5446 return dump;
5447}
5448
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005449void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005450 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5451 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5452 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005453 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005454
Tiger Huang721e26f2018-07-24 22:26:19 +08005455 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5456 dump += StringPrintf(INDENT "FocusedApplications:\n");
5457 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5458 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005459 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005460 const std::chrono::duration timeout =
5461 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005462 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005463 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005464 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005465 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005466 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005467 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005468 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005469
Vishnu Nairc519ff72021-01-21 08:23:08 -08005470 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005471 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005472
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005473 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005474 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005475 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005476 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5477 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005478 }
5479 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005480 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005481 }
5482
arthurhung6d4bed92021-03-17 11:59:33 +08005483 if (mDragState) {
5484 dump += StringPrintf(INDENT "DragState:\n");
5485 mDragState->dump(dump, INDENT2);
5486 }
5487
Arthur Hungb92218b2018-08-14 12:00:21 +08005488 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005489 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5490 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5491 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5492 const auto& displayInfo = it->second;
5493 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5494 displayInfo.logicalHeight);
5495 displayInfo.transform.dump(dump, "transform", INDENT4);
5496 } else {
5497 dump += INDENT2 "No DisplayInfo found!\n";
5498 }
5499
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005500 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005501 dump += INDENT2 "Windows:\n";
5502 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005503 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5504 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005505
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005506 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005507 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005508 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005509 "applicationInfo.name=%s, "
5510 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005511 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005512 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005513 windowInfo->displayId,
5514 windowInfo->inputConfig.string().c_str(),
5515 windowInfo->alpha, windowInfo->frameLeft,
5516 windowInfo->frameTop, windowInfo->frameRight,
5517 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005518 windowInfo->applicationInfo.name.c_str(),
5519 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005520 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005521 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005522 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005523 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005524 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005525 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005526 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005527 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005528 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005529 }
5530 } else {
5531 dump += INDENT2 "Windows: <none>\n";
5532 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005533 }
5534 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005535 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005536 }
5537
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005538 if (!mGlobalMonitorsByDisplay.empty()) {
5539 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5540 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005541 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005543 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005544 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005545 }
5546
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005547 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005548
5549 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005550 if (!mRecentQueue.empty()) {
5551 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005552 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005553 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005554 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005555 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005556 }
5557 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005558 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005559 }
5560
5561 // Dump event currently being dispatched.
5562 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005563 dump += INDENT "PendingEvent:\n";
5564 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005565 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005566 dump += StringPrintf(", age=%" PRId64 "ms\n",
5567 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005568 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005569 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005570 }
5571
5572 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005573 if (!mInboundQueue.empty()) {
5574 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005575 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005576 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005577 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005578 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005579 }
5580 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005581 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005582 }
5583
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005584 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005585 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005586 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005587 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005588 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005589 }
5590 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005591 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005592 }
5593
Prabir Pradhancef936d2021-07-21 16:17:52 +00005594 if (!mCommandQueue.empty()) {
5595 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5596 } else {
5597 dump += INDENT "CommandQueue: <empty>\n";
5598 }
5599
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005600 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005601 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005602 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005603 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005604 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005605 connection->inputChannel->getFd().get(),
5606 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005607 connection->getWindowName().c_str(),
5608 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005609 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005610
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005611 if (!connection->outboundQueue.empty()) {
5612 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5613 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005614 dump += dumpQueue(connection->outboundQueue, currentTime);
5615
Michael Wrightd02c5b62014-02-10 15:10:22 -08005616 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005617 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005618 }
5619
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005620 if (!connection->waitQueue.empty()) {
5621 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5622 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005623 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005624 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005625 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005626 }
5627 }
5628 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005629 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005630 }
5631
5632 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005633 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5634 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005635 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005636 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005637 }
5638
Antonio Kantek15beb512022-06-13 22:35:41 +00005639 if (!mTouchModePerDisplay.empty()) {
5640 dump += INDENT "TouchModePerDisplay:\n";
5641 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5642 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5643 std::to_string(touchMode).c_str());
5644 }
5645 } else {
5646 dump += INDENT "TouchModePerDisplay: <none>\n";
5647 }
5648
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005649 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005650 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5651 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5652 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005653 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005654 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005655}
5656
Michael Wright3dd60e22019-03-27 22:06:44 +00005657void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5658 const size_t numMonitors = monitors.size();
5659 for (size_t i = 0; i < numMonitors; i++) {
5660 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005661 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005662 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5663 dump += "\n";
5664 }
5665}
5666
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005667class LooperEventCallback : public LooperCallback {
5668public:
5669 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5670 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5671
5672private:
5673 std::function<int(int events)> mCallback;
5674};
5675
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005676Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005677 if (DEBUG_CHANNEL_CREATION) {
5678 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5679 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005680
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005681 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005682 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005683 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005684
5685 if (result) {
5686 return base::Error(result) << "Failed to open input channel pair with name " << name;
5687 }
5688
Michael Wrightd02c5b62014-02-10 15:10:22 -08005689 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005690 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005691 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005692 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005693 sp<Connection> connection =
Harry Cutts33476232023-01-30 19:57:29 +00005694 sp<Connection>::make(std::move(serverChannel), /*monitor=*/false, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005695
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005696 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5697 ALOGE("Created a new connection, but the token %p is already known", token.get());
5698 }
5699 mConnectionsByToken.emplace(token, connection);
5700
5701 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5702 this, std::placeholders::_1, token);
5703
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005704 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5705 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005706 } // release lock
5707
5708 // Wake the looper because some connections have changed.
5709 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005710 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005711}
5712
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005713Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005714 const std::string& name,
5715 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005716 std::shared_ptr<InputChannel> serverChannel;
5717 std::unique_ptr<InputChannel> clientChannel;
5718 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5719 if (result) {
5720 return base::Error(result) << "Failed to open input channel pair with name " << name;
5721 }
5722
Michael Wright3dd60e22019-03-27 22:06:44 +00005723 { // acquire lock
5724 std::scoped_lock _l(mLock);
5725
5726 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005727 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5728 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005729 }
5730
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005731 sp<Connection> connection =
Harry Cutts33476232023-01-30 19:57:29 +00005732 sp<Connection>::make(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005733 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005734 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005735
5736 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5737 ALOGE("Created a new connection, but the token %p is already known", token.get());
5738 }
5739 mConnectionsByToken.emplace(token, connection);
5740 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5741 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005742
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005743 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005744
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005745 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5746 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005747 }
Garfield Tan15601662020-09-22 15:32:38 -07005748
Michael Wright3dd60e22019-03-27 22:06:44 +00005749 // Wake the looper because some connections have changed.
5750 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005751 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005752}
5753
Garfield Tan15601662020-09-22 15:32:38 -07005754status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005755 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005756 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005757
Harry Cutts33476232023-01-30 19:57:29 +00005758 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005759 if (status) {
5760 return status;
5761 }
5762 } // release lock
5763
5764 // Wake the poll loop because removing the connection may have changed the current
5765 // synchronization state.
5766 mLooper->wake();
5767 return OK;
5768}
5769
Garfield Tan15601662020-09-22 15:32:38 -07005770status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5771 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005772 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005773 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005774 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005775 return BAD_VALUE;
5776 }
5777
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005778 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005779
Michael Wrightd02c5b62014-02-10 15:10:22 -08005780 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005781 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005782 }
5783
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005784 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005785
5786 nsecs_t currentTime = now();
5787 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5788
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005789 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005790 return OK;
5791}
5792
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005793void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005794 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5795 auto& [displayId, monitors] = *it;
5796 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5797 return monitor.inputChannel->getConnectionToken() == connectionToken;
5798 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005799
Michael Wright3dd60e22019-03-27 22:06:44 +00005800 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005801 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005802 } else {
5803 ++it;
5804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005805 }
5806}
5807
Michael Wright3dd60e22019-03-27 22:06:44 +00005808status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005809 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005810 return pilferPointersLocked(token);
5811}
Michael Wright3dd60e22019-03-27 22:06:44 +00005812
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005813status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005814 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5815 if (!requestingChannel) {
5816 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5817 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005818 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005819
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005820 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005821 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.none()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005822 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5823 " Ignoring.");
5824 return BAD_VALUE;
5825 }
5826
5827 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005828 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005829 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005830 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005831 "input channel stole pointer stream");
5832 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005833 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005834 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005835 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005836 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005837 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005838 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005839 if (channel != nullptr && channel->getConnectionToken() != token) {
5840 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5841 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5842 canceledWindows += channel->getName();
5843 }
5844 }
5845 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5846 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5847 canceledWindows.c_str());
5848
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005849 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005850 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005851 window.pilferedPointerIds |= window.pointerIds;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005852
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005853 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005854 return OK;
5855}
5856
Prabir Pradhan99987712020-11-10 18:43:05 -08005857void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5858 { // acquire lock
5859 std::scoped_lock _l(mLock);
5860 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005861 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005862 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5863 windowHandle != nullptr ? windowHandle->getName().c_str()
5864 : "token without window");
5865 }
5866
Vishnu Nairc519ff72021-01-21 08:23:08 -08005867 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005868 if (focusedToken != windowToken) {
5869 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5870 enabled ? "enable" : "disable");
5871 return;
5872 }
5873
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005874 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005875 ALOGW("Ignoring request to %s Pointer Capture: "
5876 "window has %s requested pointer capture.",
5877 enabled ? "enable" : "disable", enabled ? "already" : "not");
5878 return;
5879 }
5880
Christine Franksb768bb42021-11-29 12:11:31 -08005881 if (enabled) {
5882 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5883 mIneligibleDisplaysForPointerCapture.end(),
5884 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5885 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5886 return;
5887 }
5888 }
5889
Prabir Pradhan99987712020-11-10 18:43:05 -08005890 setPointerCaptureLocked(enabled);
5891 } // release lock
5892
5893 // Wake the thread to process command entries.
5894 mLooper->wake();
5895}
5896
Christine Franksb768bb42021-11-29 12:11:31 -08005897void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5898 { // acquire lock
5899 std::scoped_lock _l(mLock);
5900 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5901 if (!isEligible) {
5902 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5903 }
5904 } // release lock
5905}
5906
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005907std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5908 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005909 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005910 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005911 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005912 }
5913 }
5914 }
5915 return std::nullopt;
5916}
5917
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005918sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005919 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005920 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005921 }
5922
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005923 for (const auto& [token, connection] : mConnectionsByToken) {
5924 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005925 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005926 }
5927 }
Robert Carr4e670e52018-08-15 13:26:12 -07005928
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005929 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005930}
5931
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005932std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5933 sp<Connection> connection = getConnectionLocked(connectionToken);
5934 if (connection == nullptr) {
5935 return "<nullptr>";
5936 }
5937 return connection->getInputChannelName();
5938}
5939
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005940void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005941 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005942 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005943}
5944
Prabir Pradhancef936d2021-07-21 16:17:52 +00005945void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5946 const sp<Connection>& connection, uint32_t seq,
5947 bool handled, nsecs_t consumeTime) {
5948 // Handle post-event policy actions.
5949 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5950 if (dispatchEntryIt == connection->waitQueue.end()) {
5951 return;
5952 }
5953 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5954 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5955 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5956 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5957 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5958 }
5959 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5960 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5961 connection->inputChannel->getConnectionToken(),
5962 dispatchEntry->deliveryTime, consumeTime, finishTime);
5963 }
5964
5965 bool restartEvent;
5966 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5967 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5968 restartEvent =
5969 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5970 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5971 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5972 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5973 handled);
5974 } else {
5975 restartEvent = false;
5976 }
5977
5978 // Dequeue the event and start the next cycle.
5979 // Because the lock might have been released, it is possible that the
5980 // contents of the wait queue to have been drained, so we need to double-check
5981 // a few things.
5982 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5983 if (dispatchEntryIt != connection->waitQueue.end()) {
5984 dispatchEntry = *dispatchEntryIt;
5985 connection->waitQueue.erase(dispatchEntryIt);
5986 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5987 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5988 if (!connection->responsive) {
5989 connection->responsive = isConnectionResponsive(*connection);
5990 if (connection->responsive) {
5991 // The connection was unresponsive, and now it's responsive.
5992 processConnectionResponsiveLocked(*connection);
5993 }
5994 }
5995 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005996 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005997 connection->outboundQueue.push_front(dispatchEntry);
5998 traceOutboundQueueLength(*connection);
5999 } else {
6000 releaseDispatchEntry(dispatchEntry);
6001 }
6002 }
6003
6004 // Start the next dispatch cycle for this connection.
6005 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006006}
6007
Prabir Pradhancef936d2021-07-21 16:17:52 +00006008void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6009 const sp<IBinder>& newToken) {
6010 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6011 scoped_unlock unlock(mLock);
6012 mPolicy->notifyFocusChanged(oldToken, newToken);
6013 };
6014 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006015}
6016
Prabir Pradhancef936d2021-07-21 16:17:52 +00006017void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6018 auto command = [this, token, x, y]() REQUIRES(mLock) {
6019 scoped_unlock unlock(mLock);
6020 mPolicy->notifyDropWindow(token, x, y);
6021 };
6022 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006023}
6024
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006025void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
6026 if (connection == nullptr) {
6027 LOG_ALWAYS_FATAL("Caller must check for nullness");
6028 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006029 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6030 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006031 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006032 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006033 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006034 return;
6035 }
6036 /**
6037 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6038 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6039 * has changed. This could cause newer entries to time out before the already dispatched
6040 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6041 * processes the events linearly. So providing information about the oldest entry seems to be
6042 * most useful.
6043 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006044 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006045 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6046 std::string reason =
6047 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006048 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006049 ns2ms(currentWait),
6050 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006051 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006052 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006053
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006054 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6055
6056 // Stop waking up for events on this connection, it is already unresponsive
6057 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006058}
6059
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006060void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6061 std::string reason =
6062 StringPrintf("%s does not have a focused window", application->getName().c_str());
6063 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006064
Prabir Pradhancef936d2021-07-21 16:17:52 +00006065 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
6066 scoped_unlock unlock(mLock);
6067 mPolicy->notifyNoFocusedWindowAnr(application);
6068 };
6069 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006070}
6071
chaviw98318de2021-05-19 16:45:23 -05006072void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006073 const std::string& reason) {
6074 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6075 updateLastAnrStateLocked(windowLabel, reason);
6076}
6077
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006078void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6079 const std::string& reason) {
6080 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006081 updateLastAnrStateLocked(windowLabel, reason);
6082}
6083
6084void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6085 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006086 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006087 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006088 struct tm tm;
6089 localtime_r(&t, &tm);
6090 char timestr[64];
6091 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006092 mLastAnrState.clear();
6093 mLastAnrState += INDENT "ANR:\n";
6094 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006095 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6096 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006097 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006098}
6099
Prabir Pradhancef936d2021-07-21 16:17:52 +00006100void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6101 KeyEntry& entry) {
6102 const KeyEvent event = createKeyEvent(entry);
6103 nsecs_t delay = 0;
6104 { // release lock
6105 scoped_unlock unlock(mLock);
6106 android::base::Timer t;
6107 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
6108 entry.policyFlags);
6109 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6110 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6111 std::to_string(t.duration().count()).c_str());
6112 }
6113 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006114
6115 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006116 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006117 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006118 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006119 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006120 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006121 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006122 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006123}
6124
Prabir Pradhancef936d2021-07-21 16:17:52 +00006125void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006126 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006127 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006128 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006129 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006130 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006131 };
6132 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006133}
6134
Prabir Pradhanedd96402022-02-15 01:46:16 -08006135void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6136 std::optional<int32_t> pid) {
6137 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006138 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006139 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006140 };
6141 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006142}
6143
6144/**
6145 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6146 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6147 * command entry to the command queue.
6148 */
6149void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6150 std::string reason) {
6151 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006152 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006153 if (connection.monitor) {
6154 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6155 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006156 pid = findMonitorPidByTokenLocked(connectionToken);
6157 } else {
6158 // The connection is a window
6159 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6160 reason.c_str());
6161 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6162 if (handle != nullptr) {
6163 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006164 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006165 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006166 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006167}
6168
6169/**
6170 * Tell the policy that a connection has become responsive so that it can stop ANR.
6171 */
6172void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6173 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006174 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006175 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006176 pid = findMonitorPidByTokenLocked(connectionToken);
6177 } else {
6178 // The connection is a window
6179 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6180 if (handle != nullptr) {
6181 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006182 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006183 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006184 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006185}
6186
Prabir Pradhancef936d2021-07-21 16:17:52 +00006187bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006188 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006189 KeyEntry& keyEntry, bool handled) {
6190 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006191 if (!handled) {
6192 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006193 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006194 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006195 return false;
6196 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006197
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006198 // Get the fallback key state.
6199 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006200 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006201 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006202 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006203 connection->inputState.removeFallbackKey(originalKeyCode);
6204 }
6205
6206 if (handled || !dispatchEntry->hasForegroundTarget()) {
6207 // If the application handles the original key for which we previously
6208 // generated a fallback or if the window is not a foreground window,
6209 // then cancel the associated fallback key, if any.
6210 if (fallbackKeyCode != -1) {
6211 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006212 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6213 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6214 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6215 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6216 keyEntry.policyFlags);
6217 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006218 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006219 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006220
6221 mLock.unlock();
6222
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006223 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006224 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006225
6226 mLock.lock();
6227
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006228 // Cancel the fallback key.
6229 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006230 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006231 "application handled the original non-fallback key "
6232 "or is no longer a foreground target, "
6233 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006234 options.keyCode = fallbackKeyCode;
6235 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006236 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006237 connection->inputState.removeFallbackKey(originalKeyCode);
6238 }
6239 } else {
6240 // If the application did not handle a non-fallback key, first check
6241 // that we are in a good state to perform unhandled key event processing
6242 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006243 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006244 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006245 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6246 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6247 "since this is not an initial down. "
6248 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6249 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6250 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006251 return false;
6252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006253
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006254 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006255 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6256 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6257 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6258 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6259 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006260 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006261
6262 mLock.unlock();
6263
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006264 bool fallback =
6265 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006266 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006267
6268 mLock.lock();
6269
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006270 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006271 connection->inputState.removeFallbackKey(originalKeyCode);
6272 return false;
6273 }
6274
6275 // Latch the fallback keycode for this key on an initial down.
6276 // The fallback keycode cannot change at any other point in the lifecycle.
6277 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006278 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006279 fallbackKeyCode = event.getKeyCode();
6280 } else {
6281 fallbackKeyCode = AKEYCODE_UNKNOWN;
6282 }
6283 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6284 }
6285
6286 ALOG_ASSERT(fallbackKeyCode != -1);
6287
6288 // Cancel the fallback key if the policy decides not to send it anymore.
6289 // We will continue to dispatch the key to the policy but we will no
6290 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006291 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6292 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006293 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6294 if (fallback) {
6295 ALOGD("Unhandled key event: Policy requested to send key %d"
6296 "as a fallback for %d, but on the DOWN it had requested "
6297 "to send %d instead. Fallback canceled.",
6298 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6299 } else {
6300 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6301 "but on the DOWN it had requested to send %d. "
6302 "Fallback canceled.",
6303 originalKeyCode, fallbackKeyCode);
6304 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006305 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006306
Michael Wrightfb04fd52022-11-24 22:31:11 +00006307 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006308 "canceling fallback, policy no longer desires it");
6309 options.keyCode = fallbackKeyCode;
6310 synthesizeCancelationEventsForConnectionLocked(connection, options);
6311
6312 fallback = false;
6313 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006314 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006315 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006316 }
6317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006318
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006319 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6320 {
6321 std::string msg;
6322 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6323 connection->inputState.getFallbackKeys();
6324 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6325 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6326 }
6327 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6328 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006329 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006330 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006331
6332 if (fallback) {
6333 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006334 keyEntry.eventTime = event.getEventTime();
6335 keyEntry.deviceId = event.getDeviceId();
6336 keyEntry.source = event.getSource();
6337 keyEntry.displayId = event.getDisplayId();
6338 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6339 keyEntry.keyCode = fallbackKeyCode;
6340 keyEntry.scanCode = event.getScanCode();
6341 keyEntry.metaState = event.getMetaState();
6342 keyEntry.repeatCount = event.getRepeatCount();
6343 keyEntry.downTime = event.getDownTime();
6344 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006345
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006346 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6347 ALOGD("Unhandled key event: Dispatching fallback key. "
6348 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6349 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6350 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006351 return true; // restart the event
6352 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006353 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6354 ALOGD("Unhandled key event: No fallback key.");
6355 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006356
6357 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006358 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006359 }
6360 }
6361 return false;
6362}
6363
Prabir Pradhancef936d2021-07-21 16:17:52 +00006364bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006365 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006366 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006367 return false;
6368}
6369
Michael Wrightd02c5b62014-02-10 15:10:22 -08006370void InputDispatcher::traceInboundQueueLengthLocked() {
6371 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006372 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006373 }
6374}
6375
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006376void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006377 if (ATRACE_ENABLED()) {
6378 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006379 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6380 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006381 }
6382}
6383
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006384void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006385 if (ATRACE_ENABLED()) {
6386 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006387 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6388 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006389 }
6390}
6391
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006392void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006393 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006394
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006395 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006396 dumpDispatchStateLocked(dump);
6397
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006398 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006399 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006400 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006401 }
6402}
6403
6404void InputDispatcher::monitor() {
6405 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006406 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006407 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006408 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006409}
6410
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006411/**
6412 * Wake up the dispatcher and wait until it processes all events and commands.
6413 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6414 * this method can be safely called from any thread, as long as you've ensured that
6415 * the work you are interested in completing has already been queued.
6416 */
6417bool InputDispatcher::waitForIdle() {
6418 /**
6419 * Timeout should represent the longest possible time that a device might spend processing
6420 * events and commands.
6421 */
6422 constexpr std::chrono::duration TIMEOUT = 100ms;
6423 std::unique_lock lock(mLock);
6424 mLooper->wake();
6425 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6426 return result == std::cv_status::no_timeout;
6427}
6428
Vishnu Naire798b472020-07-23 13:52:21 -07006429/**
6430 * Sets focus to the window identified by the token. This must be called
6431 * after updating any input window handles.
6432 *
6433 * Params:
6434 * request.token - input channel token used to identify the window that should gain focus.
6435 * request.focusedToken - the token that the caller expects currently to be focused. If the
6436 * specified token does not match the currently focused window, this request will be dropped.
6437 * If the specified focused token matches the currently focused window, the call will succeed.
6438 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6439 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6440 * when requesting the focus change. This determines which request gets
6441 * precedence if there is a focus change request from another source such as pointer down.
6442 */
Vishnu Nair958da932020-08-21 17:12:37 -07006443void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6444 { // acquire lock
6445 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006446 std::optional<FocusResolver::FocusChanges> changes =
6447 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6448 if (changes) {
6449 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006450 }
6451 } // release lock
6452 // Wake up poll loop since it may need to make new input dispatching choices.
6453 mLooper->wake();
6454}
6455
Vishnu Nairc519ff72021-01-21 08:23:08 -08006456void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6457 if (changes.oldFocus) {
6458 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006459 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006460 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006461 "focus left window");
6462 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006463 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006464 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006465 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006466 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006467 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006468 }
6469
Prabir Pradhan99987712020-11-10 18:43:05 -08006470 // If a window has pointer capture, then it must have focus. We need to ensure that this
6471 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6472 // If the window loses focus before it loses pointer capture, then the window can be in a state
6473 // where it has pointer capture but not focus, violating the contract. Therefore we must
6474 // dispatch the pointer capture event before the focus event. Since focus events are added to
6475 // the front of the queue (above), we add the pointer capture event to the front of the queue
6476 // after the focus events are added. This ensures the pointer capture event ends up at the
6477 // front.
6478 disablePointerCaptureForcedLocked();
6479
Vishnu Nairc519ff72021-01-21 08:23:08 -08006480 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006481 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006482 }
6483}
Vishnu Nair958da932020-08-21 17:12:37 -07006484
Prabir Pradhan99987712020-11-10 18:43:05 -08006485void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006486 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006487 return;
6488 }
6489
6490 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6491
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006492 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006493 setPointerCaptureLocked(false);
6494 }
6495
6496 if (!mWindowTokenWithPointerCapture) {
6497 // No need to send capture changes because no window has capture.
6498 return;
6499 }
6500
6501 if (mPendingEvent != nullptr) {
6502 // Move the pending event to the front of the queue. This will give the chance
6503 // for the pending event to be dropped if it is a captured event.
6504 mInboundQueue.push_front(mPendingEvent);
6505 mPendingEvent = nullptr;
6506 }
6507
6508 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006509 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006510 mInboundQueue.push_front(std::move(entry));
6511}
6512
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006513void InputDispatcher::setPointerCaptureLocked(bool enable) {
6514 mCurrentPointerCaptureRequest.enable = enable;
6515 mCurrentPointerCaptureRequest.seq++;
6516 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006517 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006518 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006519 };
6520 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006521}
6522
Vishnu Nair599f1412021-06-21 10:39:58 -07006523void InputDispatcher::displayRemoved(int32_t displayId) {
6524 { // acquire lock
6525 std::scoped_lock _l(mLock);
6526 // Set an empty list to remove all handles from the specific display.
6527 setInputWindowsLocked(/* window handles */ {}, displayId);
6528 setFocusedApplicationLocked(displayId, nullptr);
6529 // Call focus resolver to clean up stale requests. This must be called after input windows
6530 // have been removed for the removed display.
6531 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006532 // Reset pointer capture eligibility, regardless of previous state.
6533 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006534 // Remove the associated touch mode state.
6535 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006536 } // release lock
6537
6538 // Wake up poll loop since it may need to make new input dispatching choices.
6539 mLooper->wake();
6540}
6541
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006542void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6543 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006544 // The listener sends the windows as a flattened array. Separate the windows by display for
6545 // more convenient parsing.
6546 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006547 for (const auto& info : windowInfos) {
6548 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006549 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006550 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006551
6552 { // acquire lock
6553 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006554
6555 // Ensure that we have an entry created for all existing displays so that if a displayId has
6556 // no windows, we can tell that the windows were removed from the display.
6557 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6558 handlesPerDisplay[displayId];
6559 }
6560
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006561 mDisplayInfos.clear();
6562 for (const auto& displayInfo : displayInfos) {
6563 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6564 }
6565
6566 for (const auto& [displayId, handles] : handlesPerDisplay) {
6567 setInputWindowsLocked(handles, displayId);
6568 }
6569 }
6570 // Wake up poll loop since it may need to make new input dispatching choices.
6571 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006572}
6573
Vishnu Nair062a8672021-09-03 16:07:44 -07006574bool InputDispatcher::shouldDropInput(
6575 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006576 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6577 (windowHandle->getInfo()->inputConfig.test(
6578 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006579 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006580 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6581 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006582 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006583 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006584 windowHandle->getInfo()->displayId);
6585 return true;
6586 }
6587 return false;
6588}
6589
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006590void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6591 const std::vector<gui::WindowInfo>& windowInfos,
6592 const std::vector<DisplayInfo>& displayInfos) {
6593 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6594}
6595
Arthur Hungdfd528e2021-12-08 13:23:04 +00006596void InputDispatcher::cancelCurrentTouch() {
6597 {
6598 std::scoped_lock _l(mLock);
6599 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006600 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006601 "cancel current touch");
6602 synthesizeCancelationEventsForAllConnectionsLocked(options);
6603
6604 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006605 }
6606 // Wake up poll loop since there might be work to do.
6607 mLooper->wake();
6608}
6609
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006610void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6611 std::scoped_lock _l(mLock);
6612 mMonitorDispatchingTimeout = timeout;
6613}
6614
Arthur Hungc539dbb2022-12-08 07:45:36 +00006615void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6616 const sp<WindowInfoHandle>& oldWindowHandle,
6617 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006618 TouchState& state, int32_t pointerId,
6619 std::vector<InputTarget>& targets) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006620 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6621 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006622 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6623 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6624 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6625 newWindowHandle->getInfo()->inputConfig.test(
6626 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6627 const sp<WindowInfoHandle> oldWallpaper =
6628 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6629 const sp<WindowInfoHandle> newWallpaper =
6630 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6631 if (oldWallpaper == newWallpaper) {
6632 return;
6633 }
6634
6635 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006636 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6637 addWindowTargetLocked(oldWallpaper,
6638 oldTouchedWindow.targetFlags |
6639 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6640 pointerIds, oldTouchedWindow.firstDownTimeInTarget, targets);
6641 state.removeTouchedPointerFromWindow(pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006642 }
6643
6644 if (newWallpaper != nullptr) {
6645 state.addOrUpdateWindow(newWallpaper,
6646 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6647 InputTarget::Flags::WINDOW_IS_OBSCURED |
6648 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6649 pointerIds);
6650 }
6651}
6652
6653void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6654 ftl::Flags<InputTarget::Flags> newTargetFlags,
6655 const sp<WindowInfoHandle> fromWindowHandle,
6656 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006657 TouchState& state,
6658 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006659 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6660 fromWindowHandle->getInfo()->inputConfig.test(
6661 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6662 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6663 toWindowHandle->getInfo()->inputConfig.test(
6664 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6665
6666 const sp<WindowInfoHandle> oldWallpaper =
6667 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6668 const sp<WindowInfoHandle> newWallpaper =
6669 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6670 if (oldWallpaper == newWallpaper) {
6671 return;
6672 }
6673
6674 if (oldWallpaper != nullptr) {
6675 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6676 "transferring touch focus to another window");
6677 state.removeWindowByToken(oldWallpaper->getToken());
6678 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6679 }
6680
6681 if (newWallpaper != nullptr) {
6682 nsecs_t downTimeInTarget = now();
6683 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6684 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6685 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6686 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6687 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
6688 sp<Connection> wallpaperConnection = getConnectionLocked(newWallpaper->getToken());
6689 if (wallpaperConnection != nullptr) {
6690 sp<Connection> toConnection = getConnectionLocked(toWindowHandle->getToken());
6691 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6692 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6693 wallpaperFlags);
6694 }
6695 }
6696}
6697
6698sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6699 const sp<WindowInfoHandle>& windowHandle) const {
6700 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6701 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6702 bool foundWindow = false;
6703 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6704 if (!foundWindow && otherHandle != windowHandle) {
6705 continue;
6706 }
6707 if (windowHandle == otherHandle) {
6708 foundWindow = true;
6709 continue;
6710 }
6711
6712 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6713 return otherHandle;
6714 }
6715 }
6716 return nullptr;
6717}
6718
Garfield Tane84e6f92019-08-29 17:28:41 -07006719} // namespace android::inputdispatcher