blob: 0f3dc5c972cc8491cd0e53e55d6bcb097f3e8953 [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 Pradhan61a5d242021-07-26 16:41:09 +0000113inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800114 return systemTime(SYSTEM_TIME_MONOTONIC);
115}
116
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000117inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800118 return value ? "true" : "false";
119}
120
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000121inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000122 if (binder == nullptr) {
123 return "<null>";
124 }
125 return StringPrintf("%p", binder.get());
126}
127
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000128inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700129 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
130 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800131}
132
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000133bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800134 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700135 case AKEY_EVENT_ACTION_DOWN:
136 case AKEY_EVENT_ACTION_UP:
137 return true;
138 default:
139 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800140 }
141}
142
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000143bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700144 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800145 ALOGE("Key event has invalid action code 0x%x", action);
146 return false;
147 }
148 return true;
149}
150
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000151bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800152 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700153 case AMOTION_EVENT_ACTION_DOWN:
154 case AMOTION_EVENT_ACTION_UP:
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800155 return pointerCount == 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700156 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700157 case AMOTION_EVENT_ACTION_HOVER_ENTER:
158 case AMOTION_EVENT_ACTION_HOVER_MOVE:
159 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800160 return pointerCount >= 1;
161 case AMOTION_EVENT_ACTION_CANCEL:
162 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700163 case AMOTION_EVENT_ACTION_SCROLL:
164 return true;
165 case AMOTION_EVENT_ACTION_POINTER_DOWN:
166 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800167 const int32_t index = MotionEvent::getActionIndex(action);
168 return index >= 0 && index < pointerCount && pointerCount > 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700169 }
170 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
171 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
172 return actionButton != 0;
173 default:
174 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 }
176}
177
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000178int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500179 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
180}
181
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000182bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
183 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700184 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 ALOGE("Motion event has invalid action code 0x%x", action);
186 return false;
187 }
188 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800189 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %zu.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700190 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 return false;
192 }
193 BitSet32 pointerIdBits;
194 for (size_t i = 0; i < pointerCount; i++) {
195 int32_t id = pointerProperties[i].id;
196 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700197 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
198 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800199 return false;
200 }
201 if (pointerIdBits.hasBit(id)) {
202 ALOGE("Motion event has duplicate pointer id %d", id);
203 return false;
204 }
205 pointerIdBits.markBit(id);
206 }
207 return true;
208}
209
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000210std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000212 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800213 }
214
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000215 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 bool first = true;
217 Region::const_iterator cur = region.begin();
218 Region::const_iterator const tail = region.end();
219 while (cur != tail) {
220 if (first) {
221 first = false;
222 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800223 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800224 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800225 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226 cur++;
227 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000228 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800229}
230
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000231std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500232 constexpr size_t maxEntries = 50; // max events to print
233 constexpr size_t skipBegin = maxEntries / 2;
234 const size_t skipEnd = queue.size() - maxEntries / 2;
235 // skip from maxEntries / 2 ... size() - maxEntries/2
236 // only print from 0 .. skipBegin and then from skipEnd .. size()
237
238 std::string dump;
239 for (size_t i = 0; i < queue.size(); i++) {
240 const DispatchEntry& entry = *queue[i];
241 if (i >= skipBegin && i < skipEnd) {
242 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
243 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
244 continue;
245 }
246 dump.append(INDENT4);
247 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800248 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
249 "ms",
250 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500251 ns2ms(currentTime - entry.eventEntry->eventTime));
252 if (entry.deliveryTime != 0) {
253 // This entry was delivered, so add information on how long we've been waiting
254 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
255 }
256 dump.append("\n");
257 }
258 return dump;
259}
260
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700261/**
262 * Find the entry in std::unordered_map by key, and return it.
263 * If the entry is not found, return a default constructed entry.
264 *
265 * Useful when the entries are vectors, since an empty vector will be returned
266 * if the entry is not found.
267 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
268 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700269template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000270V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700271 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700272 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800273}
274
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000275bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700276 if (first == second) {
277 return true;
278 }
279
280 if (first == nullptr || second == nullptr) {
281 return false;
282 }
283
284 return first->getToken() == second->getToken();
285}
286
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000287bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000288 if (first == nullptr || second == nullptr) {
289 return false;
290 }
291 return first->applicationInfo.token != nullptr &&
292 first->applicationInfo.token == second->applicationInfo.token;
293}
294
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800295std::unique_ptr<DispatchEntry> createDispatchEntry(
296 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
297 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700298 if (inputTarget.useDefaultPointerTransform()) {
299 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700300 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700301 inputTarget.displayTransform,
302 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000303 }
304
305 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
306 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
307
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700308 std::vector<PointerCoords> pointerCoords;
309 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000310
311 // Use the first pointer information to normalize all other pointers. This could be any pointer
312 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700313 // uses the transform for the normalized pointer.
314 const ui::Transform& firstPointerTransform =
315 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
316 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000317
318 // Iterate through all pointers in the event to normalize against the first.
319 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
320 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
321 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700322 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000323
324 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700325 // First, apply the current pointer's transform to update the coordinates into
326 // window space.
327 pointerCoords[pointerIndex].transform(currTransform);
328 // Next, apply the inverse transform of the normalized coordinates so the
329 // current coordinates are transformed into the normalized coordinate space.
330 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000331 }
332
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700333 std::unique_ptr<MotionEntry> combinedMotionEntry =
334 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
335 motionEntry.deviceId, motionEntry.source,
336 motionEntry.displayId, motionEntry.policyFlags,
337 motionEntry.action, motionEntry.actionButton,
338 motionEntry.flags, motionEntry.metaState,
339 motionEntry.buttonState, motionEntry.classification,
340 motionEntry.edgeFlags, motionEntry.xPrecision,
341 motionEntry.yPrecision, motionEntry.xCursorPosition,
342 motionEntry.yCursorPosition, motionEntry.downTime,
343 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000344 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000345
346 if (motionEntry.injectionState) {
347 combinedMotionEntry->injectionState = motionEntry.injectionState;
348 combinedMotionEntry->injectionState->refCount += 1;
349 }
350
351 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700352 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700353 firstPointerTransform, inputTarget.displayTransform,
354 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000355 return dispatchEntry;
356}
357
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000358status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
359 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700360 std::unique_ptr<InputChannel> uniqueServerChannel;
361 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
362
363 serverChannel = std::move(uniqueServerChannel);
364 return result;
365}
366
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500367template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000368bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500369 if (lhs == nullptr && rhs == nullptr) {
370 return true;
371 }
372 if (lhs == nullptr || rhs == nullptr) {
373 return false;
374 }
375 return *lhs == *rhs;
376}
377
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000378KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000379 KeyEvent event;
380 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
381 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
382 entry.repeatCount, entry.downTime, entry.eventTime);
383 return event;
384}
385
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000386bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000387 // Do not keep track of gesture monitors. They receive every event and would disproportionately
388 // affect the statistics.
389 if (connection.monitor) {
390 return false;
391 }
392 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
393 if (!connection.responsive) {
394 return false;
395 }
396 return true;
397}
398
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000399bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000400 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
401 const int32_t& inputEventId = eventEntry.id;
402 if (inputEventId != dispatchEntry.resolvedEventId) {
403 // Event was transmuted
404 return false;
405 }
406 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
407 return false;
408 }
409 // Only track latency for events that originated from hardware
410 if (eventEntry.isSynthesized()) {
411 return false;
412 }
413 const EventEntry::Type& inputEventEntryType = eventEntry.type;
414 if (inputEventEntryType == EventEntry::Type::KEY) {
415 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
416 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
417 return false;
418 }
419 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
420 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
421 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
422 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
423 return false;
424 }
425 } else {
426 // Not a key or a motion
427 return false;
428 }
429 if (!shouldReportMetricsForConnection(connection)) {
430 return false;
431 }
432 return true;
433}
434
Prabir Pradhancef936d2021-07-21 16:17:52 +0000435/**
436 * Connection is responsive if it has no events in the waitQueue that are older than the
437 * current time.
438 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000439bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000440 const nsecs_t currentTime = now();
441 for (const DispatchEntry* entry : connection.waitQueue) {
442 if (entry->timeoutTime < currentTime) {
443 return false;
444 }
445 }
446 return true;
447}
448
Antonio Kantekf16f2832021-09-28 04:39:20 +0000449// Returns true if the event type passed as argument represents a user activity.
450bool isUserActivityEvent(const EventEntry& eventEntry) {
451 switch (eventEntry.type) {
452 case EventEntry::Type::FOCUS:
453 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
454 case EventEntry::Type::DRAG:
455 case EventEntry::Type::TOUCH_MODE_CHANGED:
456 case EventEntry::Type::SENSOR:
457 case EventEntry::Type::CONFIGURATION_CHANGED:
458 return false;
459 case EventEntry::Type::DEVICE_RESET:
460 case EventEntry::Type::KEY:
461 case EventEntry::Type::MOTION:
462 return true;
463 }
464}
465
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800466// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhand65552b2021-10-07 11:23:50 -0700467bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, int32_t x, int32_t y,
468 bool isStylus) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800469 const auto inputConfig = windowInfo.inputConfig;
470 if (windowInfo.displayId != displayId ||
471 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800472 return false;
473 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700474 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800475 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800476 return false;
477 }
Prabir Pradhan06349042022-02-04 09:19:17 -0800478 if (!windowInfo.touchableRegionContainsPoint(x, y)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800479 return false;
480 }
481 return true;
482}
483
Prabir Pradhand65552b2021-10-07 11:23:50 -0700484bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
485 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000486 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700487}
488
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800489// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000490// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
491// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
492// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800493// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000494bool canReceiveForegroundTouches(const WindowInfo& info) {
495 // A non-touchable window can still receive touch events (e.g. in the case of
496 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
497 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
498}
499
Antonio Kantek48710e42022-03-24 14:19:30 -0700500bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
501 if (windowHandle == nullptr) {
502 return false;
503 }
504 const WindowInfo* windowInfo = windowHandle->getInfo();
505 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
506 return true;
507 }
508 return false;
509}
510
Prabir Pradhan5735a322022-04-11 17:23:34 +0000511// Checks targeted injection using the window's owner's uid.
512// Returns an empty string if an entry can be sent to the given window, or an error message if the
513// entry is a targeted injection whose uid target doesn't match the window owner.
514std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
515 const EventEntry& entry) {
516 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
517 // The event was not injected, or the injected event does not target a window.
518 return {};
519 }
520 const int32_t uid = *entry.injectionState->targetUid;
521 if (window == nullptr) {
522 return StringPrintf("No valid window target for injection into uid %d.", uid);
523 }
524 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
525 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
526 "owned by uid %d.",
527 uid, window->getName().c_str(), window->getInfo()->ownerUid);
528 }
529 return {};
530}
531
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700532Point resolveTouchedPosition(const MotionEntry& entry) {
533 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
534 // Always dispatch mouse events to cursor position.
535 if (isFromMouse) {
536 return Point(static_cast<int32_t>(entry.xCursorPosition),
537 static_cast<int32_t>(entry.yCursorPosition));
538 }
539
540 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
541 return Point(static_cast<int32_t>(
542 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X)),
543 static_cast<int32_t>(
544 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)));
545}
546
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700547std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
548 if (eventEntry.type == EventEntry::Type::KEY) {
549 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
550 return keyEntry.downTime;
551 } else if (eventEntry.type == EventEntry::Type::MOTION) {
552 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
553 return motionEntry.downTime;
554 }
555 return std::nullopt;
556}
557
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000558/**
559 * Compare the old touch state to the new touch state, and generate the corresponding touched
560 * windows (== input targets).
561 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
562 * If the pointer just entered the new window, produce HOVER_ENTER.
563 * For pointers remaining in the window, produce HOVER_MOVE.
564 */
565std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
566 const TouchState& newTouchState,
567 const MotionEntry& entry) {
568 std::vector<TouchedWindow> out;
569 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
570 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
571 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
572 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
573 // Not a hover event - don't need to do anything
574 return out;
575 }
576
577 // We should consider all hovering pointers here. But for now, just use the first one
578 const int32_t pointerId = entry.pointerProperties[0].id;
579
580 std::set<sp<WindowInfoHandle>> oldWindows;
581 if (oldState != nullptr) {
582 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
583 }
584
585 std::set<sp<WindowInfoHandle>> newWindows =
586 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
587
588 // If the pointer is no longer in the new window set, send HOVER_EXIT.
589 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
590 if (newWindows.find(oldWindow) == newWindows.end()) {
591 TouchedWindow touchedWindow;
592 touchedWindow.windowHandle = oldWindow;
593 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
594 touchedWindow.pointerIds.markBit(pointerId);
595 out.push_back(touchedWindow);
596 }
597 }
598
599 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
600 TouchedWindow touchedWindow;
601 touchedWindow.windowHandle = newWindow;
602 if (oldWindows.find(newWindow) == oldWindows.end()) {
603 // Any windows that have this pointer now, and didn't have it before, should get
604 // HOVER_ENTER
605 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
606 } else {
607 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
608 LOG_ALWAYS_FATAL_IF(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE);
609 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
610 }
611 touchedWindow.pointerIds.markBit(pointerId);
612 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
613 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
614 }
615 out.push_back(touchedWindow);
616 }
617 return out;
618}
619
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800620template <typename T>
621std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
622 left.insert(left.end(), right.begin(), right.end());
623 return left;
624}
625
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000626} // namespace
627
Michael Wrightd02c5b62014-02-10 15:10:22 -0800628// --- InputDispatcher ---
629
Garfield Tan00f511d2019-06-12 16:55:40 -0700630InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800631 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
632
633InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
634 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700635 : mPolicy(policy),
636 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700637 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800638 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700639 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700640 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700641 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800642 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700643 mDispatchEnabled(false),
644 mDispatchFrozen(false),
645 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100646 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000647 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800648 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800649 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000650 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000651 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700652 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800653 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800654
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700655 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700656#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700657 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700658#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700659 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800660 policy->getDispatcherConfiguration(&mConfig);
661}
662
663InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000664 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800665
Prabir Pradhancef936d2021-07-21 16:17:52 +0000666 resetKeyRepeatLocked();
667 releasePendingEventLocked();
668 drainInboundQueueLocked();
669 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800670
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000671 while (!mConnectionsByToken.empty()) {
672 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000673 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
674 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800675 }
676}
677
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700678status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700679 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700680 return ALREADY_EXISTS;
681 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700682 mThread = std::make_unique<InputThread>(
683 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
684 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700685}
686
687status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700688 if (mThread && mThread->isCallingThread()) {
689 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700690 return INVALID_OPERATION;
691 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700692 mThread.reset();
693 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700694}
695
Michael Wrightd02c5b62014-02-10 15:10:22 -0800696void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700697 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800699 std::scoped_lock _l(mLock);
700 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800701
702 // Run a dispatch loop if there are no pending commands.
703 // The dispatch loop might enqueue commands to run afterwards.
704 if (!haveCommandsLocked()) {
705 dispatchOnceInnerLocked(&nextWakeupTime);
706 }
707
708 // Run all pending commands if there are any.
709 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000710 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700711 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800713
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700714 // If we are still waiting for ack on some events,
715 // we might have to wake up earlier to check if an app is anr'ing.
716 const nsecs_t nextAnrCheck = processAnrsLocked();
717 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
718
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800719 // We are about to enter an infinitely long sleep, because we have no commands or
720 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700721 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800722 mDispatcherEnteredIdle.notify_all();
723 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800724 } // release lock
725
726 // Wait for callback or timeout or wake. (make sure we round up, not down)
727 nsecs_t currentTime = now();
728 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
729 mLooper->pollOnce(timeoutMillis);
730}
731
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700732/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500733 * Raise ANR if there is no focused window.
734 * Before the ANR is raised, do a final state check:
735 * 1. The currently focused application must be the same one we are waiting for.
736 * 2. Ensure we still don't have a focused window.
737 */
738void InputDispatcher::processNoFocusedWindowAnrLocked() {
739 // Check if the application that we are waiting for is still focused.
740 std::shared_ptr<InputApplicationHandle> focusedApplication =
741 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
742 if (focusedApplication == nullptr ||
743 focusedApplication->getApplicationToken() !=
744 mAwaitedFocusedApplication->getApplicationToken()) {
745 // Unexpected because we should have reset the ANR timer when focused application changed
746 ALOGE("Waited for a focused window, but focused application has already changed to %s",
747 focusedApplication->getName().c_str());
748 return; // The focused application has changed.
749 }
750
chaviw98318de2021-05-19 16:45:23 -0500751 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500752 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
753 if (focusedWindowHandle != nullptr) {
754 return; // We now have a focused window. No need for ANR.
755 }
756 onAnrLocked(mAwaitedFocusedApplication);
757}
758
759/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700760 * Check if any of the connections' wait queues have events that are too old.
761 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
762 * Return the time at which we should wake up next.
763 */
764nsecs_t InputDispatcher::processAnrsLocked() {
765 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700766 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700767 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
768 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
769 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500770 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700771 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500772 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700773 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700774 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500775 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700776 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
777 }
778 }
779
780 // Check if any connection ANRs are due
781 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
782 if (currentTime < nextAnrCheck) { // most likely scenario
783 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
784 }
785
786 // If we reached here, we have an unresponsive connection.
787 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
788 if (connection == nullptr) {
789 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
790 return nextAnrCheck;
791 }
792 connection->responsive = false;
793 // Stop waking up for this unresponsive connection
794 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000795 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700796 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700797}
798
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800799std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
800 const sp<Connection>& connection) {
801 if (connection->monitor) {
802 return mMonitorDispatchingTimeout;
803 }
804 const sp<WindowInfoHandle> window =
805 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700806 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500807 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700808 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500809 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700810}
811
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
813 nsecs_t currentTime = now();
814
Jeff Browndc5992e2014-04-11 01:27:26 -0700815 // Reset the key repeat timer whenever normal dispatch is suspended while the
816 // device is in a non-interactive state. This is to ensure that we abort a key
817 // repeat if the device is just coming out of sleep.
818 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819 resetKeyRepeatLocked();
820 }
821
822 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
823 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100824 if (DEBUG_FOCUS) {
825 ALOGD("Dispatch frozen. Waiting some more.");
826 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 return;
828 }
829
830 // Optimize latency of app switches.
831 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
832 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
833 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
834 if (mAppSwitchDueTime < *nextWakeupTime) {
835 *nextWakeupTime = mAppSwitchDueTime;
836 }
837
838 // Ready to start a new event.
839 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700840 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700841 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800842 if (isAppSwitchDue) {
843 // The inbound queue is empty so the app switch key we were waiting
844 // for will never arrive. Stop waiting for it.
845 resetPendingAppSwitchLocked(false);
846 isAppSwitchDue = false;
847 }
848
849 // Synthesize a key repeat if appropriate.
850 if (mKeyRepeatState.lastKeyEntry) {
851 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
852 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
853 } else {
854 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
855 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
856 }
857 }
858 }
859
860 // Nothing to do if there is no pending event.
861 if (!mPendingEvent) {
862 return;
863 }
864 } else {
865 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700866 mPendingEvent = mInboundQueue.front();
867 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868 traceInboundQueueLengthLocked();
869 }
870
871 // Poke user activity for this event.
872 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700873 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 }
876
877 // Now we have an event to dispatch.
878 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700879 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700881 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700883 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700885 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886 }
887
888 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700889 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890 }
891
892 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700893 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700894 const ConfigurationChangedEntry& typedEntry =
895 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700896 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700897 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700898 break;
899 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700901 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700902 const DeviceResetEntry& typedEntry =
903 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700904 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700905 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700906 break;
907 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100909 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700910 std::shared_ptr<FocusEntry> typedEntry =
911 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100912 dispatchFocusLocked(currentTime, typedEntry);
913 done = true;
914 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
915 break;
916 }
917
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700918 case EventEntry::Type::TOUCH_MODE_CHANGED: {
919 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
920 dispatchTouchModeChangeLocked(currentTime, typedEntry);
921 done = true;
922 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
923 break;
924 }
925
Prabir Pradhan99987712020-11-10 18:43:05 -0800926 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
927 const auto typedEntry =
928 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
929 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
930 done = true;
931 break;
932 }
933
arthurhungb89ccb02020-12-30 16:19:01 +0800934 case EventEntry::Type::DRAG: {
935 std::shared_ptr<DragEntry> typedEntry =
936 std::static_pointer_cast<DragEntry>(mPendingEvent);
937 dispatchDragLocked(currentTime, typedEntry);
938 done = true;
939 break;
940 }
941
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700942 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700943 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700944 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700945 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700946 resetPendingAppSwitchLocked(true);
947 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700948 } else if (dropReason == DropReason::NOT_DROPPED) {
949 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700950 }
951 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700952 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700953 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700954 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700955 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
956 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700957 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700958 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700959 break;
960 }
961
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700962 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700963 std::shared_ptr<MotionEntry> motionEntry =
964 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700965 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
966 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700968 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700969 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700970 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700971 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
972 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700973 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700974 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700975 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800976 }
Chris Yef59a2f42020-10-16 12:55:26 -0700977
978 case EventEntry::Type::SENSOR: {
979 std::shared_ptr<SensorEntry> sensorEntry =
980 std::static_pointer_cast<SensorEntry>(mPendingEvent);
981 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
982 dropReason = DropReason::APP_SWITCH;
983 }
984 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
985 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
986 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
987 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
988 dropReason = DropReason::STALE;
989 }
990 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
991 done = true;
992 break;
993 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 }
995
996 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700997 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700998 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 }
Michael Wright3a981722015-06-10 15:26:13 +01001000 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001
1002 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001003 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004 }
1005}
1006
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001007bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1008 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1009}
1010
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001011/**
1012 * Return true if the events preceding this incoming motion event should be dropped
1013 * Return false otherwise (the default behaviour)
1014 */
1015bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001016 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001017 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001018
1019 // Optimize case where the current application is unresponsive and the user
1020 // decides to touch a window in a different application.
1021 // If the application takes too long to catch up then we drop all events preceding
1022 // the touch into the other window.
1023 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001024 const int32_t displayId = motionEntry.displayId;
1025 const auto [x, y] = resolveTouchedPosition(motionEntry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07001026 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001027
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001028 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001029 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001030 touchedWindowHandle->getApplicationToken() !=
1031 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001032 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001033 ALOGI("Pruning input queue because user touched a different application while waiting "
1034 "for %s",
1035 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001036 return true;
1037 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001038
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001039 // Alternatively, maybe there's a spy window that could handle this event.
1040 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1041 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1042 for (const auto& windowHandle : touchedSpies) {
1043 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001044 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001045 // This spy window could take more input. Drop all events preceding this
1046 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001047 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001048 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001049 mAwaitedFocusedApplication->getName().c_str());
1050 return true;
1051 }
1052 }
1053 }
1054
1055 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1056 // yet been processed by some connections, the dispatcher will wait for these motion
1057 // events to be processed before dispatching the key event. This is because these motion events
1058 // may cause a new window to be launched, which the user might expect to receive focus.
1059 // To prevent waiting forever for such events, just send the key to the currently focused window
1060 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1061 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1062 "just send the pending key event to the focused window.");
1063 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001064 }
1065 return false;
1066}
1067
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001068bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001069 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001070 mInboundQueue.push_back(std::move(newEntry));
1071 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072 traceInboundQueueLengthLocked();
1073
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001074 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001075 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001076 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1077 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078 // Optimize app switch latency.
1079 // If the application takes too long to catch up then we drop all events preceding
1080 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001081 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001082 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001083 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001084 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001085 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001086 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001087 if (DEBUG_APP_SWITCH) {
1088 ALOGD("App switch is pending!");
1089 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001090 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001091 mAppSwitchSawKeyDown = false;
1092 needWake = true;
1093 }
1094 }
1095 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001096
1097 // If a new up event comes in, and the pending event with same key code has been asked
1098 // to try again later because of the policy. We have to reset the intercept key wake up
1099 // time for it may have been handled in the policy and could be dropped.
1100 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1101 mPendingEvent->type == EventEntry::Type::KEY) {
1102 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1103 if (pendingKey.keyCode == keyEntry.keyCode &&
1104 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001105 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1106 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001107 pendingKey.interceptKeyWakeupTime = 0;
1108 needWake = true;
1109 }
1110 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001111 break;
1112 }
1113
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001114 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001115 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1116 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001117 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1118 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001119 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001121 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001123 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001124 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1125 break;
1126 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001127 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001128 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001129 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001130 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001131 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1132 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001133 // nothing to do
1134 break;
1135 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001136 }
1137
1138 return needWake;
1139}
1140
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001141void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001142 // Do not store sensor event in recent queue to avoid flooding the queue.
1143 if (entry->type != EventEntry::Type::SENSOR) {
1144 mRecentQueue.push_back(entry);
1145 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001146 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001147 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 }
1149}
1150
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001151std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
1152InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x, int32_t y, bool isStylus,
1153 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001155 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001156 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001157 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001158 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001159 continue;
1160 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001162 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001163 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001164 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001165 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001166
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001167 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1168 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
1169 BitSet32(0), /*firstDownTimeInTarget=*/std::nullopt,
1170 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171 }
1172 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001173 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174}
1175
Prabir Pradhand65552b2021-10-07 11:23:50 -07001176std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1177 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001178 // Traverse windows from front to back and gather the touched spy windows.
1179 std::vector<sp<WindowInfoHandle>> spyWindows;
1180 const auto& windowHandles = getWindowHandlesLocked(displayId);
1181 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1182 const WindowInfo& info = *windowHandle->getInfo();
1183
Prabir Pradhand65552b2021-10-07 11:23:50 -07001184 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001185 continue;
1186 }
1187 if (!info.isSpy()) {
1188 // The first touched non-spy window was found, so return the spy windows touched so far.
1189 return spyWindows;
1190 }
1191 spyWindows.push_back(windowHandle);
1192 }
1193 return spyWindows;
1194}
1195
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001196void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 const char* reason;
1198 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001199 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001200 if (DEBUG_INBOUND_EVENT_DETAILS) {
1201 ALOGD("Dropped event because policy consumed it.");
1202 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001203 reason = "inbound event was dropped because the policy consumed it";
1204 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001205 case DropReason::DISABLED:
1206 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001207 ALOGI("Dropped event because input dispatch is disabled.");
1208 }
1209 reason = "inbound event was dropped because input dispatch is disabled";
1210 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001211 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001212 ALOGI("Dropped event because of pending overdue app switch.");
1213 reason = "inbound event was dropped because of pending overdue app switch";
1214 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001215 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001216 ALOGI("Dropped event because the current application is not responding and the user "
1217 "has started interacting with a different application.");
1218 reason = "inbound event was dropped because the current application is not responding "
1219 "and the user has started interacting with a different application";
1220 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001221 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001222 ALOGI("Dropped event because it is stale.");
1223 reason = "inbound event was dropped because it is stale";
1224 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001225 case DropReason::NO_POINTER_CAPTURE:
1226 ALOGI("Dropped event because there is no window with Pointer Capture.");
1227 reason = "inbound event was dropped because there is no window with Pointer Capture";
1228 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001229 case DropReason::NOT_DROPPED: {
1230 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001231 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001232 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233 }
1234
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001235 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001236 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001237 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001239 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001241 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001242 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1243 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001244 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001245 synthesizeCancelationEventsForAllConnectionsLocked(options);
1246 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001247 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1248 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001249 synthesizeCancelationEventsForAllConnectionsLocked(options);
1250 }
1251 break;
1252 }
Chris Yef59a2f42020-10-16 12:55:26 -07001253 case EventEntry::Type::SENSOR: {
1254 break;
1255 }
arthurhungb89ccb02020-12-30 16:19:01 +08001256 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1257 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001258 break;
1259 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001260 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001261 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001262 case EventEntry::Type::CONFIGURATION_CHANGED:
1263 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001264 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001265 break;
1266 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267 }
1268}
1269
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001270static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001271 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1272 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273}
1274
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001275bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1276 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1277 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1278 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279}
1280
1281bool InputDispatcher::isAppSwitchPendingLocked() {
Colin Cross5b799302022-10-18 21:52:41 -07001282 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283}
1284
1285void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001286 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001287
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001288 if (DEBUG_APP_SWITCH) {
1289 if (handled) {
1290 ALOGD("App switch has arrived.");
1291 } else {
1292 ALOGD("App switch was abandoned.");
1293 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295}
1296
Michael Wrightd02c5b62014-02-10 15:10:22 -08001297bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001298 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299}
1300
Prabir Pradhancef936d2021-07-21 16:17:52 +00001301bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001302 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303 return false;
1304 }
1305
1306 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001307 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001308 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001309 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1310 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001311 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001312 return true;
1313}
1314
Prabir Pradhancef936d2021-07-21 16:17:52 +00001315void InputDispatcher::postCommandLocked(Command&& command) {
1316 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317}
1318
1319void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001320 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001321 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001322 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 releaseInboundEventLocked(entry);
1324 }
1325 traceInboundQueueLengthLocked();
1326}
1327
1328void InputDispatcher::releasePendingEventLocked() {
1329 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001331 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332 }
1333}
1334
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001335void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001336 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001337 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001338 if (DEBUG_DISPATCH_CYCLE) {
1339 ALOGD("Injected inbound event was dropped.");
1340 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001341 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001342 }
1343 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001344 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345 }
1346 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001347}
1348
1349void InputDispatcher::resetKeyRepeatLocked() {
1350 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001351 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352 }
1353}
1354
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001355std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1356 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001357
Michael Wright2e732952014-09-24 13:26:59 -07001358 uint32_t policyFlags = entry->policyFlags &
1359 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001360
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001361 std::shared_ptr<KeyEntry> newEntry =
1362 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1363 entry->source, entry->displayId, policyFlags, entry->action,
1364 entry->flags, entry->keyCode, entry->scanCode,
1365 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001367 newEntry->syntheticRepeat = true;
1368 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001370 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001371}
1372
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001373bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001374 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001375 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1376 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1377 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378
1379 // Reset key repeating in case a keyboard device was added or removed or something.
1380 resetKeyRepeatLocked();
1381
1382 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001383 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1384 scoped_unlock unlock(mLock);
1385 mPolicy->notifyConfigurationChanged(eventTime);
1386 };
1387 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388 return true;
1389}
1390
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001391bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1392 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001393 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1394 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1395 entry.deviceId);
1396 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397
liushenxiang42232912021-05-21 20:24:09 +08001398 // Reset key repeating in case a keyboard device was disabled or enabled.
1399 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1400 resetKeyRepeatLocked();
1401 }
1402
Michael Wrightfb04fd52022-11-24 22:31:11 +00001403 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001404 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405 synthesizeCancelationEventsForAllConnectionsLocked(options);
1406 return true;
1407}
1408
Vishnu Nairad321cd2020-08-20 16:40:21 -07001409void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001410 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001411 if (mPendingEvent != nullptr) {
1412 // Move the pending event to the front of the queue. This will give the chance
1413 // for the pending event to get dispatched to the newly focused window
1414 mInboundQueue.push_front(mPendingEvent);
1415 mPendingEvent = nullptr;
1416 }
1417
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001418 std::unique_ptr<FocusEntry> focusEntry =
1419 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1420 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001421
1422 // This event should go to the front of the queue, but behind all other focus events
1423 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001424 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001425 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001426 [](const std::shared_ptr<EventEntry>& event) {
1427 return event->type == EventEntry::Type::FOCUS;
1428 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001429
1430 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001431 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001432}
1433
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001434void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001435 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001436 if (channel == nullptr) {
1437 return; // Window has gone away
1438 }
1439 InputTarget target;
1440 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001441 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001442 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001443 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1444 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001445 std::string reason = std::string("reason=").append(entry->reason);
1446 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001447 dispatchEventLocked(currentTime, entry, {target});
1448}
1449
Prabir Pradhan99987712020-11-10 18:43:05 -08001450void InputDispatcher::dispatchPointerCaptureChangedLocked(
1451 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1452 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001453 dropReason = DropReason::NOT_DROPPED;
1454
Prabir Pradhan99987712020-11-10 18:43:05 -08001455 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001456 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001457
1458 if (entry->pointerCaptureRequest.enable) {
1459 // Enable Pointer Capture.
1460 if (haveWindowWithPointerCapture &&
1461 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001462 // This can happen if pointer capture is disabled and re-enabled before we notify the
1463 // app of the state change, so there is no need to notify the app.
1464 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1465 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001466 }
1467 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001468 // This can happen if a window requests capture and immediately releases capture.
1469 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001470 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001471 return;
1472 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001473 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1474 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1475 return;
1476 }
1477
Vishnu Nairc519ff72021-01-21 08:23:08 -08001478 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001479 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1480 mWindowTokenWithPointerCapture = token;
1481 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001482 // Disable Pointer Capture.
1483 // We do not check if the sequence number matches for requests to disable Pointer Capture
1484 // for two reasons:
1485 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1486 // to disable capture with the same sequence number: one generated by
1487 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1488 // Capture being disabled in InputReader.
1489 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1490 // actual Pointer Capture state that affects events being generated by input devices is
1491 // in InputReader.
1492 if (!haveWindowWithPointerCapture) {
1493 // Pointer capture was already forcefully disabled because of focus change.
1494 dropReason = DropReason::NOT_DROPPED;
1495 return;
1496 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001497 token = mWindowTokenWithPointerCapture;
1498 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001499 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001500 setPointerCaptureLocked(false);
1501 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001502 }
1503
1504 auto channel = getInputChannelLocked(token);
1505 if (channel == nullptr) {
1506 // Window has gone away, clean up Pointer Capture state.
1507 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001508 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001509 setPointerCaptureLocked(false);
1510 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001511 return;
1512 }
1513 InputTarget target;
1514 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001515 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001516 entry->dispatchInProgress = true;
1517 dispatchEventLocked(currentTime, entry, {target});
1518
1519 dropReason = DropReason::NOT_DROPPED;
1520}
1521
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001522void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1523 const std::shared_ptr<TouchModeEntry>& entry) {
1524 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001525 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001526 if (windowHandles.empty()) {
1527 return;
1528 }
1529 const std::vector<InputTarget> inputTargets =
1530 getInputTargetsFromWindowHandlesLocked(windowHandles);
1531 if (inputTargets.empty()) {
1532 return;
1533 }
1534 entry->dispatchInProgress = true;
1535 dispatchEventLocked(currentTime, entry, inputTargets);
1536}
1537
1538std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1539 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1540 std::vector<InputTarget> inputTargets;
1541 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001542 const sp<IBinder>& token = handle->getToken();
1543 if (token == nullptr) {
1544 continue;
1545 }
1546 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1547 if (channel == nullptr) {
1548 continue; // Window has gone away
1549 }
1550 InputTarget target;
1551 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001552 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001553 inputTargets.push_back(target);
1554 }
1555 return inputTargets;
1556}
1557
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001558bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001559 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001561 if (!entry->dispatchInProgress) {
1562 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1563 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1564 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1565 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001566 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 // We have seen two identical key downs in a row which indicates that the device
1568 // driver is automatically generating key repeats itself. We take note of the
1569 // repeat here, but we disable our own next key repeat timer since it is clear that
1570 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001571 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1572 // Make sure we don't get key down from a different device. If a different
1573 // device Id has same key pressed down, the new device Id will replace the
1574 // current one to hold the key repeat with repeat count reset.
1575 // In the future when got a KEY_UP on the device id, drop it and do not
1576 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1578 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001579 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580 } else {
1581 // Not a repeat. Save key down state in case we do see a repeat later.
1582 resetKeyRepeatLocked();
1583 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1584 }
1585 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001586 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1587 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001588 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001589 if (DEBUG_INBOUND_EVENT_DETAILS) {
1590 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1591 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001592 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001593 resetKeyRepeatLocked();
1594 }
1595
1596 if (entry->repeatCount == 1) {
1597 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1598 } else {
1599 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1600 }
1601
1602 entry->dispatchInProgress = true;
1603
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001604 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001605 }
1606
1607 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001608 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001609 if (currentTime < entry->interceptKeyWakeupTime) {
1610 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1611 *nextWakeupTime = entry->interceptKeyWakeupTime;
1612 }
1613 return false; // wait until next wakeup
1614 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001615 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001616 entry->interceptKeyWakeupTime = 0;
1617 }
1618
1619 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001620 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001622 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001623 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001624
1625 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1626 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1627 };
1628 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629 return false; // wait for the command to run
1630 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001631 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001633 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001634 if (*dropReason == DropReason::NOT_DROPPED) {
1635 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 }
1637 }
1638
1639 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001640 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001641 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001642 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1643 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001644 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 return true;
1646 }
1647
1648 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001649 InputEventInjectionResult injectionResult;
1650 sp<WindowInfoHandle> focusedWindow =
1651 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1652 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001653 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 return false;
1655 }
1656
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001657 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001658 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659 return true;
1660 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001661 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1662
1663 std::vector<InputTarget> inputTargets;
1664 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001665 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001666 BitSet32(0), getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001668 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001669 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670
1671 // Dispatch the key.
1672 dispatchEventLocked(currentTime, entry, inputTargets);
1673 return true;
1674}
1675
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001676void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001677 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1678 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1679 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1680 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1681 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1682 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1683 entry.metaState, entry.repeatCount, entry.downTime);
1684 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685}
1686
Prabir Pradhancef936d2021-07-21 16:17:52 +00001687void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1688 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001689 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001690 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1691 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1692 "source=0x%x, sensorType=%s",
1693 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001694 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001695 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001696 auto command = [this, entry]() REQUIRES(mLock) {
1697 scoped_unlock unlock(mLock);
1698
1699 if (entry->accuracyChanged) {
1700 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1701 }
1702 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1703 entry->hwTimestamp, entry->values);
1704 };
1705 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001706}
1707
1708bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001709 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1710 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001711 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001712 }
Chris Yef59a2f42020-10-16 12:55:26 -07001713 { // acquire lock
1714 std::scoped_lock _l(mLock);
1715
1716 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1717 std::shared_ptr<EventEntry> entry = *it;
1718 if (entry->type == EventEntry::Type::SENSOR) {
1719 it = mInboundQueue.erase(it);
1720 releaseInboundEventLocked(entry);
1721 }
1722 }
1723 }
1724 return true;
1725}
1726
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001727bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001728 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001729 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001731 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001732 entry->dispatchInProgress = true;
1733
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001734 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001735 }
1736
1737 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001738 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001739 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001740 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1741 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 return true;
1743 }
1744
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001745 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746
1747 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001748 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749
1750 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001751 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752 if (isPointerEvent) {
1753 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001754
1755 if (mDragState &&
1756 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1757 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1758 pilferPointersLocked(mDragState->dragWindow->getToken());
1759 }
1760
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001761 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001762 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001763 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001764 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1765 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766 } else {
1767 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001768 sp<WindowInfoHandle> focusedWindow =
1769 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1770 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1771 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1772 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001773 InputTarget::Flags::FOREGROUND |
1774 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001775 BitSet32(0), getDownTime(*entry), inputTargets);
1776 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001778 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001779 return false;
1780 }
1781
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001782 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001783 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001784 return true;
1785 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001786 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001787 CancelationOptions::Mode mode(
1788 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1789 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001790 CancelationOptions options(mode, "input event injection failed");
1791 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792 return true;
1793 }
1794
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001795 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001796 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797
1798 // Dispatch the motion.
1799 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001800 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001801 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802 synthesizeCancelationEventsForAllConnectionsLocked(options);
1803 }
1804 dispatchEventLocked(currentTime, entry, inputTargets);
1805 return true;
1806}
1807
chaviw98318de2021-05-19 16:45:23 -05001808void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001809 bool isExiting, const int32_t rawX,
1810 const int32_t rawY) {
1811 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001812 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001813 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1814 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001815
1816 enqueueInboundEventLocked(std::move(dragEntry));
1817}
1818
1819void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1820 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1821 if (channel == nullptr) {
1822 return; // Window has gone away
1823 }
1824 InputTarget target;
1825 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001826 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001827 entry->dispatchInProgress = true;
1828 dispatchEventLocked(currentTime, entry, {target});
1829}
1830
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001831void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001832 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001833 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001834 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001835 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001836 "metaState=0x%x, buttonState=0x%x,"
1837 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001838 prefix, entry.eventTime, entry.deviceId,
1839 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1840 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1841 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1842 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001844 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1845 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1846 "x=%f, y=%f, pressure=%f, size=%f, "
1847 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1848 "orientation=%f",
1849 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1850 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1851 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1852 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1853 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1854 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1855 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1856 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1857 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1858 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1859 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861}
1862
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001863void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1864 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001865 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001866 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001867 if (DEBUG_DISPATCH_CYCLE) {
1868 ALOGD("dispatchEventToCurrentInputTargets");
1869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001871 updateInteractionTokensLocked(*eventEntry, inputTargets);
1872
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1874
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001875 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001877 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001878 sp<Connection> connection =
1879 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001880 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001881 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001883 if (DEBUG_FOCUS) {
1884 ALOGD("Dropping event delivery to target with channel '%s' because it "
1885 "is no longer registered with the input dispatcher.",
1886 inputTarget.inputChannel->getName().c_str());
1887 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 }
1889 }
1890}
1891
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001892void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1893 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1894 // If the policy decides to close the app, we will get a channel removal event via
1895 // unregisterInputChannel, and will clean up the connection that way. We are already not
1896 // sending new pointers to the connection when it blocked, but focused events will continue to
1897 // pile up.
1898 ALOGW("Canceling events for %s because it is unresponsive",
1899 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001900 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001901 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001902 "application not responding");
1903 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 }
1905}
1906
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001907void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001908 if (DEBUG_FOCUS) {
1909 ALOGD("Resetting ANR timeouts.");
1910 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911
1912 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001913 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001914 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915}
1916
Tiger Huang721e26f2018-07-24 22:26:19 +08001917/**
1918 * Get the display id that the given event should go to. If this event specifies a valid display id,
1919 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1920 * Focused display is the display that the user most recently interacted with.
1921 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001922int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001923 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001924 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001925 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001926 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1927 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001928 break;
1929 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001930 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001931 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1932 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001933 break;
1934 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001935 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001936 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001937 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001938 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001939 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001940 case EventEntry::Type::SENSOR:
1941 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001942 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001943 return ADISPLAY_ID_NONE;
1944 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001945 }
1946 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1947}
1948
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001949bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1950 const char* focusedWindowName) {
1951 if (mAnrTracker.empty()) {
1952 // already processed all events that we waited for
1953 mKeyIsWaitingForEventsTimeout = std::nullopt;
1954 return false;
1955 }
1956
1957 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1958 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001959 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001960 mKeyIsWaitingForEventsTimeout = currentTime +
1961 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1962 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001963 return true;
1964 }
1965
1966 // We still have pending events, and already started the timer
1967 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1968 return true; // Still waiting
1969 }
1970
1971 // Waited too long, and some connection still hasn't processed all motions
1972 // Just send the key to the focused window
1973 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1974 focusedWindowName);
1975 mKeyIsWaitingForEventsTimeout = std::nullopt;
1976 return false;
1977}
1978
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001979sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
1980 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
1981 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001982 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001983 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984
Tiger Huang721e26f2018-07-24 22:26:19 +08001985 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001986 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001987 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001988 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1989
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990 // If there is no currently focused window and no focused application
1991 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001992 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1993 ALOGI("Dropping %s event because there is no focused window or focused application in "
1994 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001995 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001996 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997 }
1998
Vishnu Nair062a8672021-09-03 16:07:44 -07001999 // Drop key events if requested by input feature
2000 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002001 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002002 }
2003
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002004 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2005 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2006 // start interacting with another application via touch (app switch). This code can be removed
2007 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2008 // an app is expected to have a focused window.
2009 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2010 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2011 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002012 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2013 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2014 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002015 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002016 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002017 ALOGW("Waiting because no window has focus but %s may eventually add a "
2018 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002019 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002020 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002021 outInjectionResult = InputEventInjectionResult::PENDING;
2022 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002023 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2024 // Already raised ANR. Drop the event
2025 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002026 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002027 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002028 } else {
2029 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002030 outInjectionResult = InputEventInjectionResult::PENDING;
2031 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002032 }
2033 }
2034
2035 // we have a valid, non-null focused window
2036 resetNoFocusedWindowTimeoutLocked();
2037
Prabir Pradhan5735a322022-04-11 17:23:34 +00002038 // Verify targeted injection.
2039 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2040 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002041 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2042 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043 }
2044
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002045 if (focusedWindowHandle->getInfo()->inputConfig.test(
2046 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002047 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002048 outInjectionResult = InputEventInjectionResult::PENDING;
2049 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002050 }
2051
2052 // If the event is a key event, then we must wait for all previous events to
2053 // complete before delivering it because previous events may have the
2054 // side-effect of transferring focus to a different window and we want to
2055 // ensure that the following keys are sent to the new window.
2056 //
2057 // Suppose the user touches a button in a window then immediately presses "A".
2058 // If the button causes a pop-up window to appear then we want to ensure that
2059 // the "A" key is delivered to the new pop-up window. This is because users
2060 // often anticipate pending UI changes when typing on a keyboard.
2061 // To obtain this behavior, we must serialize key events with respect to all
2062 // prior input events.
2063 if (entry.type == EventEntry::Type::KEY) {
2064 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2065 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002066 outInjectionResult = InputEventInjectionResult::PENDING;
2067 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069 }
2070
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002071 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2072 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073}
2074
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002075/**
2076 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2077 * that are currently unresponsive.
2078 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002079std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2080 const std::vector<Monitor>& monitors) const {
2081 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002082 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002083 [this](const Monitor& monitor) REQUIRES(mLock) {
2084 sp<Connection> connection =
2085 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002086 if (connection == nullptr) {
2087 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002088 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002089 return false;
2090 }
2091 if (!connection->responsive) {
2092 ALOGW("Unresponsive monitor %s will not get the new gesture",
2093 connection->inputChannel->getName().c_str());
2094 return false;
2095 }
2096 return true;
2097 });
2098 return responsiveMonitors;
2099}
2100
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002101/**
2102 * In general, touch should be always split between windows. Some exceptions:
2103 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2104 * from the same device, *and* the window that's receiving the current pointer does not support
2105 * split touch.
2106 * 2. Don't split mouse events
2107 */
2108bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2109 const MotionEntry& entry) const {
2110 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2111 // We should never split mouse events
2112 return false;
2113 }
2114 for (const TouchedWindow& touchedWindow : touchState.windows) {
2115 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2116 // Spy windows should not affect whether or not touch is split.
2117 continue;
2118 }
2119 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2120 continue;
2121 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002122 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2123 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2124 // Wallpaper window should not affect whether or not touch is split
2125 continue;
2126 }
2127
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002128 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2129 // being sent there. For now, use deviceId from touch state.
2130 if (entry.deviceId == touchState.deviceId && !touchedWindow.pointerIds.isEmpty()) {
2131 return false;
2132 }
2133 }
2134 return true;
2135}
2136
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002137std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002138 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2139 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002140 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002141
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002142 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143 // For security reasons, we defer updating the touch state until we are sure that
2144 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002145 const int32_t displayId = entry.displayId;
2146 const int32_t action = entry.action;
2147 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148
2149 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002150 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002151
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002152 // Copy current touch state into tempTouchState.
2153 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2154 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002155 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002156 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002157 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2158 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002159 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002160 }
2161
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002162 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002163 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002164 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002165
2166 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2167 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2168 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002169 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2170 // touchable windows.
2171 const bool wasDown = oldState != nullptr && oldState->isDown();
2172 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2173 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
2174 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002175 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002176
Michael Wrightd02c5b62014-02-10 15:10:22 -08002177 if (newGesture) {
2178 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002179 if (switchedDevice && tempTouchState.isDown() && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002180 ALOGI("Dropping event because a pointer for a different device is already down "
2181 "in display %" PRId32,
2182 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002183 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002184 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002185 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002187 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002188 tempTouchState.deviceId = entry.deviceId;
2189 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002191 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002192 ALOGI("Dropping move event because a pointer for a different device is already active "
2193 "in display %" PRId32,
2194 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002195 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002196 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002197 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198 }
2199
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002200 if (isHoverAction) {
2201 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2202 // all of the existing hovering pointers and recompute.
2203 tempTouchState.clearHoveringPointers();
2204 }
2205
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2207 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002208 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002209 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002210 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2211 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002212 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002213 auto [newTouchedWindowHandle, outsideTargets] =
2214 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002215
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002216 if (isDown) {
2217 targets += outsideTargets;
2218 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002220 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002221 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2222 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002223 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002224 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002225 }
2226
Prabir Pradhan5735a322022-04-11 17:23:34 +00002227 // Verify targeted injection.
2228 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2229 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002230 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002231 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002232 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002233 }
2234
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002235 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002236 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002237 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2238 // New window supports splitting, but we should never split mouse events.
2239 isSplit = !isFromMouse;
2240 } else if (isSplit) {
2241 // New window does not support splitting but we have already split events.
2242 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002243 newTouchedWindowHandle = nullptr;
2244 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002245 } else {
2246 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002247 // be delivered to a new window which supports split touch. Pointers from a mouse device
2248 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002249 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002250 }
2251
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002252 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002253 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002254 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002255 // Process the foreground window first so that it is the first to receive the event.
2256 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002257 }
2258
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002259 if (newTouchedWindows.empty()) {
2260 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2261 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002262 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002263 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002264 }
2265
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002266 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002267 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002268 continue;
2269 }
2270
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002271 if (isHoverAction) {
2272 const int32_t pointerId = entry.pointerProperties[0].id;
2273 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2274 // Pointer left. Remove it
2275 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2276 } else {
2277 // The "windowHandle" is the target of this hovering pointer.
2278 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId,
2279 pointerId);
2280 }
2281 }
2282
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002283 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002284 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002285
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002286 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2287 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002288 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002289 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002290
2291 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002292 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002293 }
2294 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002295 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002296 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002297 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002298 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002299
2300 // Update the temporary touch state.
2301 BitSet32 pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002302 if (!isHoverAction) {
2303 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2304 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002305
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002306 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
2307 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002308
2309 // If this is the pointer going down and the touched window has a wallpaper
2310 // then also add the touched wallpaper windows so they are locked in for the duration
2311 // of the touch gesture.
2312 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2313 // engine only supports touch events. We would need to add a mechanism similar
2314 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2315 if (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2316 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2317 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2318 windowHandle->getInfo()->inputConfig.test(
2319 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2320 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2321 if (wallpaper != nullptr) {
2322 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2323 InputTarget::Flags::WINDOW_IS_OBSCURED |
2324 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2325 InputTarget::Flags::DISPATCH_AS_IS;
2326 if (isSplit) {
2327 wallpaperFlags |= InputTarget::Flags::SPLIT;
2328 }
2329 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2330 entry.eventTime);
2331 }
2332 }
2333 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002335
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002336 // If a window is already pilfering some pointers, give it this new pointer as well and
2337 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2338 // which is a specific behaviour that we want.
2339 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2340 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
2341 if (touchedWindow.pointerIds.hasBit(pointerId) &&
2342 touchedWindow.pilferedPointerIds.count() > 0) {
2343 // This window is already pilfering some pointers, and this new pointer is also
2344 // going to it. Therefore, take over this pointer and don't give it to anyone
2345 // else.
2346 touchedWindow.pilferedPointerIds.set(pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002347 }
2348 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002349
2350 // Restrict all pilfered pointers to the pilfering windows.
2351 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 } else {
2353 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2354
2355 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002356 if (!tempTouchState.isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002357 ALOGD_IF(DEBUG_FOCUS,
2358 "Dropping event because the pointer is not down or we previously "
2359 "dropped the pointer down event in display %" PRId32 ": %s",
2360 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002361 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002362 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002363 }
2364
arthurhung6d4bed92021-03-17 11:59:33 +08002365 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002366
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002368 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002369 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002370 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07002371 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002372 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002373 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002374 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002375
Prabir Pradhan5735a322022-04-11 17:23:34 +00002376 // Verify targeted injection.
2377 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2378 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002379 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002380 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002381 }
2382
Vishnu Nair062a8672021-09-03 16:07:44 -07002383 // Drop touch events if requested by input feature
2384 if (newTouchedWindowHandle != nullptr &&
2385 shouldDropInput(entry, newTouchedWindowHandle)) {
2386 newTouchedWindowHandle = nullptr;
2387 }
2388
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002389 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2390 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002391 if (DEBUG_FOCUS) {
2392 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2393 oldTouchedWindowHandle->getName().c_str(),
2394 newTouchedWindowHandle->getName().c_str(), displayId);
2395 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396 // Make a slippery exit from the old window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002397 BitSet32 pointerIds;
2398 const int32_t pointerId = entry.pointerProperties[0].id;
2399 pointerIds.markBit(pointerId);
2400
2401 const TouchedWindow& touchedWindow =
2402 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2403 addWindowTargetLocked(oldTouchedWindowHandle,
2404 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
2405 touchedWindow.firstDownTimeInTarget, targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406
2407 // Make a slippery entrance into the new window.
2408 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002409 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410 }
2411
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002412 ftl::Flags<InputTarget::Flags> targetFlags =
2413 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002414 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002415 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002418 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419 }
2420 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002421 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002422 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002423 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424 }
2425
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002426 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2427 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002428
2429 // Check if the wallpaper window should deliver the corresponding event.
2430 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002431 tempTouchState, pointerId, targets);
2432 tempTouchState.removeTouchedPointerFromWindow(pointerId, oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433 }
2434 }
Arthur Hung96483742022-11-15 03:30:48 +00002435
2436 // Update the pointerIds for non-splittable when it received pointer down.
2437 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2438 // If no split, we suppose all touched windows should receive pointer down.
2439 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2440 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2441 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2442 // Ignore drag window for it should just track one pointer.
2443 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2444 continue;
2445 }
2446 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2447 }
2448 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002449 }
2450
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002451 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002452 {
2453 std::vector<TouchedWindow> hoveringWindows =
2454 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2455 for (const TouchedWindow& touchedWindow : hoveringWindows) {
2456 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2457 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2458 targets);
2459 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002460 }
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002461 // Ensure that we have at least one foreground window or at least one window that cannot be a
2462 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2463 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2464 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002465 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2466 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002467 return !canReceiveForegroundTouches(
2468 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002469 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002470 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002471 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2472 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002473 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002474 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002475 }
2476
Prabir Pradhan5735a322022-04-11 17:23:34 +00002477 // Ensure that all touched windows are valid for injection.
2478 if (entry.injectionState != nullptr) {
2479 std::string errs;
2480 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002481 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002482 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2483 // dispatched to any uid, since the coords will be zeroed out later.
2484 continue;
2485 }
2486 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2487 if (err) errs += "\n - " + *err;
2488 }
2489 if (!errs.empty()) {
2490 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2491 "%d:%s",
2492 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002493 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002494 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002495 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002496 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002497
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002498 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2499 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002501 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002502 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002503 if (foregroundWindowHandle) {
2504 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002505 for (InputTarget& target : targets) {
2506 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2507 sp<WindowInfoHandle> targetWindow =
2508 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2509 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2510 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002511 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 }
2513 }
2514 }
2515 }
2516
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002517 // Success! Output targets from the touch state.
2518 tempTouchState.clearWindowsWithoutPointers();
2519 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
2520 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2521 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2522 targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002523 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002524
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002525 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002526 // Drop the outside or hover touch windows since we will not care about them
2527 // in the next iteration.
2528 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002529
Michael Wrightd02c5b62014-02-10 15:10:22 -08002530 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002531 if (switchedDevice) {
2532 if (DEBUG_FOCUS) {
2533 ALOGD("Conflicting pointer actions: Switched to a different device.");
2534 }
2535 *outConflictingPointerActions = true;
2536 }
2537
2538 if (isHoverAction) {
2539 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002540 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002541 ALOGD_IF(DEBUG_FOCUS,
2542 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002543 *outConflictingPointerActions = true;
2544 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002545 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2546 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2547 tempTouchState.deviceId = entry.deviceId;
2548 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002549 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002550 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2551 // Pointer went up.
2552 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
2553 tempTouchState.clearWindowsWithoutPointers();
2554 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002555 // All pointers up or canceled.
2556 tempTouchState.reset();
2557 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2558 // First pointer went down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002559 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002560 ALOGD("Conflicting pointer actions: Down received while already down.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002561 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002562 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002563 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2564 // One pointer went up.
2565 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2566 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002567
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002568 for (size_t i = 0; i < tempTouchState.windows.size();) {
2569 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2570 touchedWindow.pointerIds.clearBit(pointerId);
2571 if (touchedWindow.pointerIds.isEmpty()) {
2572 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2573 continue;
2574 }
2575 i += 1;
2576 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002577 }
2578
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002579 // Save changes unless the action was scroll in which case the temporary touch
2580 // state was only valid for this one action.
2581 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002582 if (displayId >= 0) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002583 mTouchStatesByDisplay[displayId] = tempTouchState;
2584 } else {
2585 mTouchStatesByDisplay.erase(displayId);
2586 }
2587 }
2588
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002589 if (tempTouchState.windows.empty()) {
2590 mTouchStatesByDisplay.erase(displayId);
2591 }
2592
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002593 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002594}
2595
arthurhung6d4bed92021-03-17 11:59:33 +08002596void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002597 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2598 // have an explicit reason to support it.
2599 constexpr bool isStylus = false;
2600
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002601 auto [dropWindow, _] =
2602 findTouchedWindowAtLocked(displayId, x, y, isStylus, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002603 if (dropWindow) {
2604 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002605 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002606 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002607 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002608 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002609 }
2610 mDragState.reset();
2611}
2612
2613void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002614 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002615 return;
2616 }
2617
arthurhung6d4bed92021-03-17 11:59:33 +08002618 if (!mDragState->isStartDrag) {
2619 mDragState->isStartDrag = true;
2620 mDragState->isStylusButtonDownAtStart =
2621 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2622 }
2623
Arthur Hung54745652022-04-20 07:17:41 +00002624 // Find the pointer index by id.
2625 int32_t pointerIndex = 0;
2626 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2627 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2628 if (pointerProperties.id == mDragState->pointerId) {
2629 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002630 }
Arthur Hung54745652022-04-20 07:17:41 +00002631 }
arthurhung6d4bed92021-03-17 11:59:33 +08002632
Arthur Hung54745652022-04-20 07:17:41 +00002633 if (uint32_t(pointerIndex) == entry.pointerCount) {
2634 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002635 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002636 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002637 return;
2638 }
2639
2640 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2641 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2642 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2643
2644 switch (maskedAction) {
2645 case AMOTION_EVENT_ACTION_MOVE: {
2646 // Handle the special case : stylus button no longer pressed.
2647 bool isStylusButtonDown =
2648 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2649 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2650 finishDragAndDrop(entry.displayId, x, y);
2651 return;
2652 }
2653
2654 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2655 // until we have an explicit reason to support it.
2656 constexpr bool isStylus = false;
2657
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002658 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2659 true /*ignoreDragWindow*/);
Arthur Hung54745652022-04-20 07:17:41 +00002660 // enqueue drag exit if needed.
2661 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2662 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2663 if (mDragState->dragHoverWindowHandle != nullptr) {
2664 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2665 y);
2666 }
2667 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2668 }
2669 // enqueue drag location if needed.
2670 if (hoverWindowHandle != nullptr) {
2671 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2672 }
2673 break;
2674 }
2675
2676 case AMOTION_EVENT_ACTION_POINTER_UP:
2677 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2678 break;
2679 }
2680 // The drag pointer is up.
2681 [[fallthrough]];
2682 case AMOTION_EVENT_ACTION_UP:
2683 finishDragAndDrop(entry.displayId, x, y);
2684 break;
2685 case AMOTION_EVENT_ACTION_CANCEL: {
2686 ALOGD("Receiving cancel when drag and drop.");
2687 sendDropWindowCommandLocked(nullptr, 0, 0);
2688 mDragState.reset();
2689 break;
2690 }
arthurhungb89ccb02020-12-30 16:19:01 +08002691 }
2692}
2693
chaviw98318de2021-05-19 16:45:23 -05002694void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002695 ftl::Flags<InputTarget::Flags> targetFlags,
2696 BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002697 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002698 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002699 std::vector<InputTarget>::iterator it =
2700 std::find_if(inputTargets.begin(), inputTargets.end(),
2701 [&windowHandle](const InputTarget& inputTarget) {
2702 return inputTarget.inputChannel->getConnectionToken() ==
2703 windowHandle->getToken();
2704 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002705
chaviw98318de2021-05-19 16:45:23 -05002706 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002707
2708 if (it == inputTargets.end()) {
2709 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002710 std::shared_ptr<InputChannel> inputChannel =
2711 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002712 if (inputChannel == nullptr) {
2713 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2714 return;
2715 }
2716 inputTarget.inputChannel = inputChannel;
2717 inputTarget.flags = targetFlags;
2718 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002719 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002720 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2721 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002722 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002723 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002724 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002725 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002726 inputTargets.push_back(inputTarget);
2727 it = inputTargets.end() - 1;
2728 }
2729
2730 ALOG_ASSERT(it->flags == targetFlags);
2731 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2732
chaviw1ff3d1e2020-07-01 15:53:47 -07002733 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734}
2735
Michael Wright3dd60e22019-03-27 22:06:44 +00002736void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002737 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002738 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2739 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002740
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002741 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2742 InputTarget target;
2743 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002744 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002745 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2746 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002747 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2748 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002749 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002750 target.setDefaultPointerTransform(target.displayTransform);
2751 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002752 }
2753}
2754
Robert Carrc9bf1d32020-04-13 17:21:08 -07002755/**
2756 * Indicate whether one window handle should be considered as obscuring
2757 * another window handle. We only check a few preconditions. Actually
2758 * checking the bounds is left to the caller.
2759 */
chaviw98318de2021-05-19 16:45:23 -05002760static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2761 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002762 // Compare by token so cloned layers aren't counted
2763 if (haveSameToken(windowHandle, otherHandle)) {
2764 return false;
2765 }
2766 auto info = windowHandle->getInfo();
2767 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002768 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002769 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002770 } else if (otherInfo->alpha == 0 &&
2771 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002772 // Those act as if they were invisible, so we don't need to flag them.
2773 // We do want to potentially flag touchable windows even if they have 0
2774 // opacity, since they can consume touches and alter the effects of the
2775 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002776 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002777 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2778 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002779 } else if (info->ownerUid == otherInfo->ownerUid) {
2780 // If ownerUid is the same we don't generate occlusion events as there
2781 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002782 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002783 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002784 return false;
2785 } else if (otherInfo->displayId != info->displayId) {
2786 return false;
2787 }
2788 return true;
2789}
2790
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002791/**
2792 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2793 * untrusted, one should check:
2794 *
2795 * 1. If result.hasBlockingOcclusion is true.
2796 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2797 * BLOCK_UNTRUSTED.
2798 *
2799 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2800 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2801 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2802 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2803 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2804 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2805 *
2806 * If neither of those is true, then it means the touch can be allowed.
2807 */
2808InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002809 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2810 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002811 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002812 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002813 TouchOcclusionInfo info;
2814 info.hasBlockingOcclusion = false;
2815 info.obscuringOpacity = 0;
2816 info.obscuringUid = -1;
2817 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002818 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002819 if (windowHandle == otherHandle) {
2820 break; // All future windows are below us. Exit early.
2821 }
chaviw98318de2021-05-19 16:45:23 -05002822 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002823 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2824 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002825 if (DEBUG_TOUCH_OCCLUSION) {
2826 info.debugInfo.push_back(
2827 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2828 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002829 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2830 // we perform the checks below to see if the touch can be propagated or not based on the
2831 // window's touch occlusion mode
2832 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2833 info.hasBlockingOcclusion = true;
2834 info.obscuringUid = otherInfo->ownerUid;
2835 info.obscuringPackage = otherInfo->packageName;
2836 break;
2837 }
2838 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2839 uint32_t uid = otherInfo->ownerUid;
2840 float opacity =
2841 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2842 // Given windows A and B:
2843 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2844 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2845 opacityByUid[uid] = opacity;
2846 if (opacity > info.obscuringOpacity) {
2847 info.obscuringOpacity = opacity;
2848 info.obscuringUid = uid;
2849 info.obscuringPackage = otherInfo->packageName;
2850 }
2851 }
2852 }
2853 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002854 if (DEBUG_TOUCH_OCCLUSION) {
2855 info.debugInfo.push_back(
2856 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2857 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002858 return info;
2859}
2860
chaviw98318de2021-05-19 16:45:23 -05002861std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002862 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002863 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2864 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2865 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2866 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002867 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2868 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2869 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2870 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2871 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002872 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002873 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002874}
2875
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002876bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2877 if (occlusionInfo.hasBlockingOcclusion) {
2878 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2879 occlusionInfo.obscuringUid);
2880 return false;
2881 }
2882 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2883 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2884 "%.2f, maximum allowed = %.2f)",
2885 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2886 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2887 return false;
2888 }
2889 return true;
2890}
2891
chaviw98318de2021-05-19 16:45:23 -05002892bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002893 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002894 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002895 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2896 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002897 if (windowHandle == otherHandle) {
2898 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002899 }
chaviw98318de2021-05-19 16:45:23 -05002900 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002901 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002902 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002903 return true;
2904 }
2905 }
2906 return false;
2907}
2908
chaviw98318de2021-05-19 16:45:23 -05002909bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002910 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002911 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2912 const WindowInfo* windowInfo = windowHandle->getInfo();
2913 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002914 if (windowHandle == otherHandle) {
2915 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002916 }
chaviw98318de2021-05-19 16:45:23 -05002917 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002918 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002919 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002920 return true;
2921 }
2922 }
2923 return false;
2924}
2925
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002926std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002927 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002928 if (applicationHandle != nullptr) {
2929 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002930 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931 } else {
2932 return applicationHandle->getName();
2933 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002934 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002935 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002936 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002937 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938 }
2939}
2940
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002941void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002942 if (!isUserActivityEvent(eventEntry)) {
2943 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002944 return;
2945 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002946 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002947 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002948 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002949 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002950 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002951 if (DEBUG_DISPATCH_CYCLE) {
2952 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2953 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002954 return;
2955 }
2956 }
2957
2958 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002959 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002960 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002961 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2962 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002963 return;
2964 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002965
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002966 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002967 eventType = USER_ACTIVITY_EVENT_TOUCH;
2968 }
2969 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002970 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002971 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002972 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2973 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002974 return;
2975 }
2976 eventType = USER_ACTIVITY_EVENT_BUTTON;
2977 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002978 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002979 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002980 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002981 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002982 break;
2983 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002984 }
2985
Prabir Pradhancef936d2021-07-21 16:17:52 +00002986 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2987 REQUIRES(mLock) {
2988 scoped_unlock unlock(mLock);
2989 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2990 };
2991 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002992}
2993
2994void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002995 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002996 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002997 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002998 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002999 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003000 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003001 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003002 ATRACE_NAME(message.c_str());
3003 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003004 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003005 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003006 "globalScaleFactor=%f, pointerIds=0x%x %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003007 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003008 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
3009 inputTarget.getPointerInfoString().c_str());
3010 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003011
3012 // Skip this event if the connection status is not normal.
3013 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003014 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003015 if (DEBUG_DISPATCH_CYCLE) {
3016 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003017 connection->getInputChannelName().c_str(),
3018 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003019 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003020 return;
3021 }
3022
3023 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003024 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003025 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003026 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003027 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003028
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003029 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003030 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003031 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
3032 "Splitting motion events requires a down time to be set for the "
3033 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003034 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003035 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3036 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003037 if (!splitMotionEntry) {
3038 return; // split event was dropped
3039 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003040 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3041 std::string reason = std::string("reason=pointer cancel on split window");
3042 android_log_event_list(LOGTAG_INPUT_CANCEL)
3043 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3044 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003045 if (DEBUG_FOCUS) {
3046 ALOGD("channel '%s' ~ Split motion event.",
3047 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003048 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003049 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003050 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3051 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052 return;
3053 }
3054 }
3055
3056 // Not splitting. Enqueue dispatch entries for the event as is.
3057 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3058}
3059
3060void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003061 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003062 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003063 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003064 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003065 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003066 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003067 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003068 ATRACE_NAME(message.c_str());
3069 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003070 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3071 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003072
hongzuo liu95785e22022-09-06 02:51:35 +00003073 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003074
3075 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003076 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003077 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003078 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003079 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003080 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003081 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003082 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003083 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003084 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003085 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003086 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003087 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088
3089 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003090 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003091 startDispatchCycleLocked(currentTime, connection);
3092 }
3093}
3094
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003095void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003096 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003097 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003098 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003099 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003100 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3101 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003102 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003103 ATRACE_NAME(message.c_str());
3104 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003105 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3106 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003107 return;
3108 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003109
3110 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3111 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003112
3113 // This is a new event.
3114 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003115 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003116 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003118 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3119 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003120 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003121 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003122 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003123 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003124 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003125 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003126 dispatchEntry->resolvedAction = keyEntry.action;
3127 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003129 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3130 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003131 if (DEBUG_DISPATCH_CYCLE) {
3132 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3133 "event",
3134 connection->getInputChannelName().c_str());
3135 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003136 return; // skip the inconsistent event
3137 }
3138 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003139 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003140
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003141 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003142 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003143 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3144 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3145 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3146 static_cast<int32_t>(IdGenerator::Source::OTHER);
3147 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003148 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003149 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003150 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003151 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003152 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003153 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003154 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003155 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003156 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003157 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3158 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003159 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003160 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003161 }
3162 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003163 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3164 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003165 if (DEBUG_DISPATCH_CYCLE) {
3166 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3167 "enter event",
3168 connection->getInputChannelName().c_str());
3169 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003170 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3171 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003172 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003175 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003176 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3177 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3178 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003179 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003180 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3181 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003182 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003183 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3184 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003186 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3187 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003188 if (DEBUG_DISPATCH_CYCLE) {
3189 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3190 "event",
3191 connection->getInputChannelName().c_str());
3192 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003193 return; // skip the inconsistent event
3194 }
3195
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003196 dispatchEntry->resolvedEventId =
3197 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3198 ? mIdGenerator.nextId()
3199 : motionEntry.id;
3200 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3201 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3202 ") to MotionEvent(id=0x%" PRIx32 ").",
3203 motionEntry.id, dispatchEntry->resolvedEventId);
3204 ATRACE_NAME(message.c_str());
3205 }
3206
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003207 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3208 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3209 // Skip reporting pointer down outside focus to the policy.
3210 break;
3211 }
3212
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003213 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003214 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003215
3216 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003218 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003219 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003220 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3221 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003222 break;
3223 }
Chris Yef59a2f42020-10-16 12:55:26 -07003224 case EventEntry::Type::SENSOR: {
3225 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3226 break;
3227 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003228 case EventEntry::Type::CONFIGURATION_CHANGED:
3229 case EventEntry::Type::DEVICE_RESET: {
3230 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003231 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003232 break;
3233 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003234 }
3235
3236 // Remember that we are waiting for this dispatch to complete.
3237 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003238 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239 }
3240
3241 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003242 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003243 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003244}
3245
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003246/**
3247 * This function is purely for debugging. It helps us understand where the user interaction
3248 * was taking place. For example, if user is touching launcher, we will see a log that user
3249 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3250 * We will see both launcher and wallpaper in that list.
3251 * Once the interaction with a particular set of connections starts, no new logs will be printed
3252 * until the set of interacted connections changes.
3253 *
3254 * The following items are skipped, to reduce the logspam:
3255 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3256 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3257 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3258 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3259 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003260 */
3261void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3262 const std::vector<InputTarget>& targets) {
3263 // Skip ACTION_UP events, and all events other than keys and motions
3264 if (entry.type == EventEntry::Type::KEY) {
3265 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3266 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3267 return;
3268 }
3269 } else if (entry.type == EventEntry::Type::MOTION) {
3270 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3271 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3272 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3273 return;
3274 }
3275 } else {
3276 return; // Not a key or a motion
3277 }
3278
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003279 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003280 std::vector<sp<Connection>> newConnections;
3281 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003282 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003283 continue; // Skip windows that receive ACTION_OUTSIDE
3284 }
3285
3286 sp<IBinder> token = target.inputChannel->getConnectionToken();
3287 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003288 if (connection == nullptr) {
3289 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003290 }
3291 newConnectionTokens.insert(std::move(token));
3292 newConnections.emplace_back(connection);
3293 }
3294 if (newConnectionTokens == mInteractionConnectionTokens) {
3295 return; // no change
3296 }
3297 mInteractionConnectionTokens = newConnectionTokens;
3298
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003299 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003300 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003301 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003302 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003303 std::string message = "Interaction with: " + targetList;
3304 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003305 message += "<none>";
3306 }
3307 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3308}
3309
chaviwfd6d3512019-03-25 13:23:49 -07003310void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003311 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003312 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003313 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3314 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003315 return;
3316 }
3317
Vishnu Nairc519ff72021-01-21 08:23:08 -08003318 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003319 if (focusedToken == token) {
3320 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003321 return;
3322 }
3323
Prabir Pradhancef936d2021-07-21 16:17:52 +00003324 auto command = [this, token]() REQUIRES(mLock) {
3325 scoped_unlock unlock(mLock);
3326 mPolicy->onPointerDownOutsideFocus(token);
3327 };
3328 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003329}
3330
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003331status_t InputDispatcher::publishMotionEvent(Connection& connection,
3332 DispatchEntry& dispatchEntry) const {
3333 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3334 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3335
3336 PointerCoords scaledCoords[MAX_POINTERS];
3337 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3338
3339 // Set the X and Y offset and X and Y scale depending on the input source.
3340 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003341 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003342 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3343 if (globalScaleFactor != 1.0f) {
3344 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3345 scaledCoords[i] = motionEntry.pointerCoords[i];
3346 // Don't apply window scale here since we don't want scale to affect raw
3347 // coordinates. The scale will be sent back to the client and applied
3348 // later when requesting relative coordinates.
3349 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3350 1 /* windowYScale */);
3351 }
3352 usingCoords = scaledCoords;
3353 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003354 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003355 // We don't want the dispatch target to know the coordinates
3356 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3357 scaledCoords[i].clear();
3358 }
3359 usingCoords = scaledCoords;
3360 }
3361
3362 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3363
3364 // Publish the motion event.
3365 return connection.inputPublisher
3366 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3367 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3368 std::move(hmac), dispatchEntry.resolvedAction,
3369 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3370 motionEntry.edgeFlags, motionEntry.metaState,
3371 motionEntry.buttonState, motionEntry.classification,
3372 dispatchEntry.transform, motionEntry.xPrecision,
3373 motionEntry.yPrecision, motionEntry.xCursorPosition,
3374 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3375 motionEntry.downTime, motionEntry.eventTime,
3376 motionEntry.pointerCount, motionEntry.pointerProperties,
3377 usingCoords);
3378}
3379
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003381 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003382 if (ATRACE_ENABLED()) {
3383 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003384 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003385 ATRACE_NAME(message.c_str());
3386 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003387 if (DEBUG_DISPATCH_CYCLE) {
3388 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003391 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003392 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003394 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003395 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396
3397 // Publish the event.
3398 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003399 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3400 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003401 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003402 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3403 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003404 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3405 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3406 << connection->getInputChannelName();
3407 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003409 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003410 status = connection->inputPublisher
3411 .publishKeyEvent(dispatchEntry->seq,
3412 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3413 keyEntry.source, keyEntry.displayId,
3414 std::move(hmac), dispatchEntry->resolvedAction,
3415 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3416 keyEntry.scanCode, keyEntry.metaState,
3417 keyEntry.repeatCount, keyEntry.downTime,
3418 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003419 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003420 }
3421
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003422 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003423 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3424 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3425 << connection->getInputChannelName();
3426 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003427 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003428 break;
3429 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003430
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003431 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003432 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003433 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003434 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003435 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003436 break;
3437 }
3438
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003439 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3440 const TouchModeEntry& touchModeEntry =
3441 static_cast<const TouchModeEntry&>(eventEntry);
3442 status = connection->inputPublisher
3443 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3444 touchModeEntry.inTouchMode);
3445
3446 break;
3447 }
3448
Prabir Pradhan99987712020-11-10 18:43:05 -08003449 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3450 const auto& captureEntry =
3451 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3452 status = connection->inputPublisher
3453 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003454 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003455 break;
3456 }
3457
arthurhungb89ccb02020-12-30 16:19:01 +08003458 case EventEntry::Type::DRAG: {
3459 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3460 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3461 dragEntry.id, dragEntry.x,
3462 dragEntry.y,
3463 dragEntry.isExiting);
3464 break;
3465 }
3466
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003467 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003468 case EventEntry::Type::DEVICE_RESET:
3469 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003470 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003471 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003472 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003473 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474 }
3475
3476 // Check the result.
3477 if (status) {
3478 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003479 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003480 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003481 "This is unexpected because the wait queue is empty, so the pipe "
3482 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003483 "event to it, status=%s(%d)",
3484 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3485 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3487 } else {
3488 // Pipe is full and we are waiting for the app to finish process some events
3489 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003490 if (DEBUG_DISPATCH_CYCLE) {
3491 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3492 "waiting for the application to catch up",
3493 connection->getInputChannelName().c_str());
3494 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003495 }
3496 } else {
3497 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003498 "status=%s(%d)",
3499 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3500 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3502 }
3503 return;
3504 }
3505
3506 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003507 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3508 connection->outboundQueue.end(),
3509 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003510 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003511 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003512 if (connection->responsive) {
3513 mAnrTracker.insert(dispatchEntry->timeoutTime,
3514 connection->inputChannel->getConnectionToken());
3515 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003516 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517 }
3518}
3519
chaviw09c8d2d2020-08-24 15:48:26 -07003520std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3521 size_t size;
3522 switch (event.type) {
3523 case VerifiedInputEvent::Type::KEY: {
3524 size = sizeof(VerifiedKeyEvent);
3525 break;
3526 }
3527 case VerifiedInputEvent::Type::MOTION: {
3528 size = sizeof(VerifiedMotionEvent);
3529 break;
3530 }
3531 }
3532 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3533 return mHmacKeyManager.sign(start, size);
3534}
3535
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003536const std::array<uint8_t, 32> InputDispatcher::getSignature(
3537 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003538 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3539 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003540 // Only sign events up and down events as the purely move events
3541 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003542 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003543 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003544
3545 VerifiedMotionEvent verifiedEvent =
3546 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3547 verifiedEvent.actionMasked = actionMasked;
3548 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3549 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003550}
3551
3552const std::array<uint8_t, 32> InputDispatcher::getSignature(
3553 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3554 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3555 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3556 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003557 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003558}
3559
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003561 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003562 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003563 if (DEBUG_DISPATCH_CYCLE) {
3564 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3565 connection->getInputChannelName().c_str(), seq, toString(handled));
3566 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003568 if (connection->status == Connection::Status::BROKEN ||
3569 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003570 return;
3571 }
3572
3573 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003574 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3575 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3576 };
3577 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003578}
3579
3580void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003581 const sp<Connection>& connection,
3582 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003583 if (DEBUG_DISPATCH_CYCLE) {
3584 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3585 connection->getInputChannelName().c_str(), toString(notify));
3586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003587
3588 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003589 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003590 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003591 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003592 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003593
3594 // The connection appears to be unrecoverably broken.
3595 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003596 if (connection->status == Connection::Status::NORMAL) {
3597 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598
3599 if (notify) {
3600 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003601 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3602 connection->getInputChannelName().c_str());
3603
3604 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003605 scoped_unlock unlock(mLock);
3606 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3607 };
3608 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 }
3610 }
3611}
3612
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003613void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3614 while (!queue.empty()) {
3615 DispatchEntry* dispatchEntry = queue.front();
3616 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003617 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618 }
3619}
3620
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003621void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003623 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624 }
3625 delete dispatchEntry;
3626}
3627
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003628int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3629 std::scoped_lock _l(mLock);
3630 sp<Connection> connection = getConnectionLocked(connectionToken);
3631 if (connection == nullptr) {
3632 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3633 connectionToken.get(), events);
3634 return 0; // remove the callback
3635 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003637 bool notify;
3638 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3639 if (!(events & ALOOPER_EVENT_INPUT)) {
3640 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3641 "events=0x%x",
3642 connection->getInputChannelName().c_str(), events);
3643 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644 }
3645
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003646 nsecs_t currentTime = now();
3647 bool gotOne = false;
3648 status_t status = OK;
3649 for (;;) {
3650 Result<InputPublisher::ConsumerResponse> result =
3651 connection->inputPublisher.receiveConsumerResponse();
3652 if (!result.ok()) {
3653 status = result.error().code();
3654 break;
3655 }
3656
3657 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3658 const InputPublisher::Finished& finish =
3659 std::get<InputPublisher::Finished>(*result);
3660 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3661 finish.consumeTime);
3662 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003663 if (shouldReportMetricsForConnection(*connection)) {
3664 const InputPublisher::Timeline& timeline =
3665 std::get<InputPublisher::Timeline>(*result);
3666 mLatencyTracker
3667 .trackGraphicsLatency(timeline.inputEventId,
3668 connection->inputChannel->getConnectionToken(),
3669 std::move(timeline.graphicsTimeline));
3670 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003671 }
3672 gotOne = true;
3673 }
3674 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003675 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003676 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677 return 1;
3678 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003679 }
3680
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003681 notify = status != DEAD_OBJECT || !connection->monitor;
3682 if (notify) {
3683 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3684 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3685 status);
3686 }
3687 } else {
3688 // Monitor channels are never explicitly unregistered.
3689 // We do it automatically when the remote endpoint is closed so don't warn about them.
3690 const bool stillHaveWindowHandle =
3691 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3692 notify = !connection->monitor && stillHaveWindowHandle;
3693 if (notify) {
3694 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3695 connection->getInputChannelName().c_str(), events);
3696 }
3697 }
3698
3699 // Remove the channel.
3700 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3701 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702}
3703
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003704void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003705 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003706 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003707 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708 }
3709}
3710
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003711void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003712 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003713 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003714 for (const Monitor& monitor : monitors) {
3715 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003716 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003717 }
3718}
3719
Michael Wrightd02c5b62014-02-10 15:10:22 -08003720void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003721 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003722 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003723 if (connection == nullptr) {
3724 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003725 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003726
3727 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728}
3729
3730void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3731 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003732 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733 return;
3734 }
3735
3736 nsecs_t currentTime = now();
3737
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003738 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003739 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003740
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003741 if (cancelationEvents.empty()) {
3742 return;
3743 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003744 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3745 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3746 "with reality: %s, mode=%d.",
3747 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3748 options.mode);
3749 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003750
Arthur Hungb3307ee2021-10-14 10:57:37 +00003751 std::string reason = std::string("reason=").append(options.reason);
3752 android_log_event_list(LOGTAG_INPUT_CANCEL)
3753 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3754
Svet Ganov5d3bc372020-01-26 23:11:07 -08003755 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003756 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003757 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3758 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003759 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003760 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003761 target.globalScaleFactor = windowInfo->globalScaleFactor;
3762 }
3763 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003764 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003765
hongzuo liu95785e22022-09-06 02:51:35 +00003766 const bool wasEmpty = connection->outboundQueue.empty();
3767
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003768 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003769 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003770 switch (cancelationEventEntry->type) {
3771 case EventEntry::Type::KEY: {
3772 logOutboundKeyDetails("cancel - ",
3773 static_cast<const KeyEntry&>(*cancelationEventEntry));
3774 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003776 case EventEntry::Type::MOTION: {
3777 logOutboundMotionDetails("cancel - ",
3778 static_cast<const MotionEntry&>(*cancelationEventEntry));
3779 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003781 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003782 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003783 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3784 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003785 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003786 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003787 break;
3788 }
3789 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003790 case EventEntry::Type::DEVICE_RESET:
3791 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003792 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003793 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003794 break;
3795 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 }
3797
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003798 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003799 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003801
hongzuo liu95785e22022-09-06 02:51:35 +00003802 // If the outbound queue was previously empty, start the dispatch cycle going.
3803 if (wasEmpty && !connection->outboundQueue.empty()) {
3804 startDispatchCycleLocked(currentTime, connection);
3805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806}
3807
Svet Ganov5d3bc372020-01-26 23:11:07 -08003808void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Arthur Hungc539dbb2022-12-08 07:45:36 +00003809 const nsecs_t downTime, const sp<Connection>& connection,
3810 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003811 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003812 return;
3813 }
3814
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003815 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003816 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003817
3818 if (downEvents.empty()) {
3819 return;
3820 }
3821
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003822 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003823 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3824 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003825 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003826
3827 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003828 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003829 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3830 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003831 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003832 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003833 target.globalScaleFactor = windowInfo->globalScaleFactor;
3834 }
3835 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00003836 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003837
hongzuo liu95785e22022-09-06 02:51:35 +00003838 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003839 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003840 switch (downEventEntry->type) {
3841 case EventEntry::Type::MOTION: {
3842 logOutboundMotionDetails("down - ",
3843 static_cast<const MotionEntry&>(*downEventEntry));
3844 break;
3845 }
3846
3847 case EventEntry::Type::KEY:
3848 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003849 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003850 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003851 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003852 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003853 case EventEntry::Type::SENSOR:
3854 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003855 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003856 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003857 break;
3858 }
3859 }
3860
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003861 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003862 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003863 }
3864
hongzuo liu95785e22022-09-06 02:51:35 +00003865 // If the outbound queue was previously empty, start the dispatch cycle going.
3866 if (wasEmpty && !connection->outboundQueue.empty()) {
3867 startDispatchCycleLocked(downTime, connection);
3868 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003869}
3870
Arthur Hungc539dbb2022-12-08 07:45:36 +00003871void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
3872 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
3873 if (windowHandle != nullptr) {
3874 sp<Connection> wallpaperConnection = getConnectionLocked(windowHandle->getToken());
3875 if (wallpaperConnection != nullptr) {
3876 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
3877 }
3878 }
3879}
3880
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003881std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003882 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883 ALOG_ASSERT(pointerIds.value != 0);
3884
3885 uint32_t splitPointerIndexMap[MAX_POINTERS];
3886 PointerProperties splitPointerProperties[MAX_POINTERS];
3887 PointerCoords splitPointerCoords[MAX_POINTERS];
3888
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003889 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003890 uint32_t splitPointerCount = 0;
3891
3892 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003893 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003895 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896 uint32_t pointerId = uint32_t(pointerProperties.id);
3897 if (pointerIds.hasBit(pointerId)) {
3898 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3899 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3900 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003901 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902 splitPointerCount += 1;
3903 }
3904 }
3905
3906 if (splitPointerCount != pointerIds.count()) {
3907 // This is bad. We are missing some of the pointers that we expected to deliver.
3908 // Most likely this indicates that we received an ACTION_MOVE events that has
3909 // different pointer ids than we expected based on the previous ACTION_DOWN
3910 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3911 // in this way.
3912 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003913 "we expected there to be %d pointers. This probably means we received "
3914 "a broken sequence of pointer ids from the input device.",
3915 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003916 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 }
3918
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003919 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003921 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3922 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3924 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003925 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926 uint32_t pointerId = uint32_t(pointerProperties.id);
3927 if (pointerIds.hasBit(pointerId)) {
3928 if (pointerIds.count() == 1) {
3929 // The first/last pointer went down/up.
3930 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003931 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003932 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3933 ? AMOTION_EVENT_ACTION_CANCEL
3934 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935 } else {
3936 // A secondary pointer went down/up.
3937 uint32_t splitPointerIndex = 0;
3938 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3939 splitPointerIndex += 1;
3940 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003941 action = maskedAction |
3942 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943 }
3944 } else {
3945 // An unrelated pointer changed.
3946 action = AMOTION_EVENT_ACTION_MOVE;
3947 }
3948 }
3949
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003950 if (action == AMOTION_EVENT_ACTION_DOWN) {
3951 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3952 "Split motion event has mismatching downTime and eventTime for "
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08003953 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
3954 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003955 }
3956
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003957 int32_t newId = mIdGenerator.nextId();
3958 if (ATRACE_ENABLED()) {
3959 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3960 ") to MotionEvent(id=0x%" PRIx32 ").",
3961 originalMotionEntry.id, newId);
3962 ATRACE_NAME(message.c_str());
3963 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003964 std::unique_ptr<MotionEntry> splitMotionEntry =
3965 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3966 originalMotionEntry.deviceId, originalMotionEntry.source,
3967 originalMotionEntry.displayId,
3968 originalMotionEntry.policyFlags, action,
3969 originalMotionEntry.actionButton,
3970 originalMotionEntry.flags, originalMotionEntry.metaState,
3971 originalMotionEntry.buttonState,
3972 originalMotionEntry.classification,
3973 originalMotionEntry.edgeFlags,
3974 originalMotionEntry.xPrecision,
3975 originalMotionEntry.yPrecision,
3976 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003977 originalMotionEntry.yCursorPosition, splitDownTime,
3978 splitPointerCount, splitPointerProperties,
3979 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003981 if (originalMotionEntry.injectionState) {
3982 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983 splitMotionEntry->injectionState->refCount += 1;
3984 }
3985
3986 return splitMotionEntry;
3987}
3988
3989void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003990 if (DEBUG_INBOUND_EVENT_DETAILS) {
3991 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3992 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993
Antonio Kantekf16f2832021-09-28 04:39:20 +00003994 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003996 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003997
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003998 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3999 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
4000 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004001 } // release lock
4002
4003 if (needWake) {
4004 mLooper->wake();
4005 }
4006}
4007
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004008/**
4009 * If one of the meta shortcuts is detected, process them here:
4010 * Meta + Backspace -> generate BACK
4011 * Meta + Enter -> generate HOME
4012 * This will potentially overwrite keyCode and metaState.
4013 */
4014void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004015 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004016 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4017 int32_t newKeyCode = AKEYCODE_UNKNOWN;
4018 if (keyCode == AKEYCODE_DEL) {
4019 newKeyCode = AKEYCODE_BACK;
4020 } else if (keyCode == AKEYCODE_ENTER) {
4021 newKeyCode = AKEYCODE_HOME;
4022 }
4023 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004024 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004025 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004026 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004027 keyCode = newKeyCode;
4028 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4029 }
4030 } else if (action == AKEY_EVENT_ACTION_UP) {
4031 // In order to maintain a consistent stream of up and down events, check to see if the key
4032 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4033 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004034 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004035 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004036 auto replacementIt = mReplacedKeys.find(replacement);
4037 if (replacementIt != mReplacedKeys.end()) {
4038 keyCode = replacementIt->second;
4039 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004040 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4041 }
4042 }
4043}
4044
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004046 if (DEBUG_INBOUND_EVENT_DETAILS) {
4047 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
4048 "policyFlags=0x%x, action=0x%x, "
4049 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
4050 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
4051 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
4052 args->downTime);
4053 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004054 if (!validateKeyEvent(args->action)) {
4055 return;
4056 }
4057
4058 uint32_t policyFlags = args->policyFlags;
4059 int32_t flags = args->flags;
4060 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004061 // InputDispatcher tracks and generates key repeats on behalf of
4062 // whatever notifies it, so repeatCount should always be set to 0
4063 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4065 policyFlags |= POLICY_FLAG_VIRTUAL;
4066 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004068 if (policyFlags & POLICY_FLAG_FUNCTION) {
4069 metaState |= AMETA_FUNCTION_ON;
4070 }
4071
4072 policyFlags |= POLICY_FLAG_TRUSTED;
4073
Michael Wright78f24442014-08-06 15:55:28 -07004074 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004075 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004076
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004078 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08004079 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
4080 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081
Michael Wright2b3c3302018-03-02 17:19:13 +00004082 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004084 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4085 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004086 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004087 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004088
Antonio Kantekf16f2832021-09-28 04:39:20 +00004089 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090 { // acquire lock
4091 mLock.lock();
4092
4093 if (shouldSendKeyToInputFilterLocked(args)) {
4094 mLock.unlock();
4095
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004096 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4098 return; // event was consumed by the filter
4099 }
4100
4101 mLock.lock();
4102 }
4103
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004104 std::unique_ptr<KeyEntry> newEntry =
4105 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4106 args->displayId, policyFlags, args->action, flags,
4107 keyCode, args->scanCode, metaState, repeatCount,
4108 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004110 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111 mLock.unlock();
4112 } // release lock
4113
4114 if (needWake) {
4115 mLooper->wake();
4116 }
4117}
4118
4119bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4120 return mInputFilterEnabled;
4121}
4122
4123void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004124 if (DEBUG_INBOUND_EVENT_DETAILS) {
4125 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4126 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004127 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004128 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4129 "yCursorPosition=%f, downTime=%" PRId64,
4130 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004131 args->policyFlags, MotionEvent::actionToString(args->action).c_str(),
4132 args->actionButton, args->flags, args->metaState, args->buttonState, args->edgeFlags,
4133 args->xPrecision, args->yPrecision, args->xCursorPosition, args->yCursorPosition,
4134 args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004135 for (uint32_t i = 0; i < args->pointerCount; i++) {
4136 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4137 "x=%f, y=%f, pressure=%f, size=%f, "
4138 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4139 "orientation=%f",
4140 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4141 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4142 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4143 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4144 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4145 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4146 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4147 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4148 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4149 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4150 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004151 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -08004152 LOG_ALWAYS_FATAL_IF(!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4153 args->pointerProperties),
4154 "Invalid event: %s", args->dump().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155
4156 uint32_t policyFlags = args->policyFlags;
4157 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004158
4159 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004160 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004161 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4162 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004163 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004164 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165
Antonio Kantekf16f2832021-09-28 04:39:20 +00004166 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167 { // acquire lock
4168 mLock.lock();
4169
4170 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004171 ui::Transform displayTransform;
4172 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4173 displayTransform = it->second.transform;
4174 }
4175
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176 mLock.unlock();
4177
4178 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004179 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4180 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004181 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004182 displayTransform, args->xPrecision, args->yPrecision,
4183 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004184 args->downTime, args->eventTime, args->pointerCount,
4185 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186
4187 policyFlags |= POLICY_FLAG_FILTERED;
4188 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4189 return; // event was consumed by the filter
4190 }
4191
4192 mLock.lock();
4193 }
4194
4195 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004196 std::unique_ptr<MotionEntry> newEntry =
4197 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4198 args->source, args->displayId, policyFlags,
4199 args->action, args->actionButton, args->flags,
4200 args->metaState, args->buttonState,
4201 args->classification, args->edgeFlags,
4202 args->xPrecision, args->yPrecision,
4203 args->xCursorPosition, args->yCursorPosition,
4204 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004205 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004207 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4208 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4209 !mInputFilterEnabled) {
4210 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4211 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4212 }
4213
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004214 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004215 mLock.unlock();
4216 } // release lock
4217
4218 if (needWake) {
4219 mLooper->wake();
4220 }
4221}
4222
Chris Yef59a2f42020-10-16 12:55:26 -07004223void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004224 if (DEBUG_INBOUND_EVENT_DETAILS) {
4225 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4226 " sensorType=%s",
4227 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004228 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004229 }
Chris Yef59a2f42020-10-16 12:55:26 -07004230
Antonio Kantekf16f2832021-09-28 04:39:20 +00004231 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004232 { // acquire lock
4233 mLock.lock();
4234
4235 // Just enqueue a new sensor event.
4236 std::unique_ptr<SensorEntry> newEntry =
4237 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4238 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4239 args->sensorType, args->accuracy,
4240 args->accuracyChanged, args->values);
4241
4242 needWake = enqueueInboundEventLocked(std::move(newEntry));
4243 mLock.unlock();
4244 } // release lock
4245
4246 if (needWake) {
4247 mLooper->wake();
4248 }
4249}
4250
Chris Yefb552902021-02-03 17:18:37 -08004251void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004252 if (DEBUG_INBOUND_EVENT_DETAILS) {
4253 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4254 args->deviceId, args->isOn);
4255 }
Chris Yefb552902021-02-03 17:18:37 -08004256 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4257}
4258
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004260 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261}
4262
4263void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004264 if (DEBUG_INBOUND_EVENT_DETAILS) {
4265 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4266 "switchMask=0x%08x",
4267 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4268 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269
4270 uint32_t policyFlags = args->policyFlags;
4271 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004272 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273}
4274
4275void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004276 if (DEBUG_INBOUND_EVENT_DETAILS) {
4277 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4278 args->deviceId);
4279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280
Antonio Kantekf16f2832021-09-28 04:39:20 +00004281 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004283 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004285 std::unique_ptr<DeviceResetEntry> newEntry =
4286 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4287 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288 } // release lock
4289
4290 if (needWake) {
4291 mLooper->wake();
4292 }
4293}
4294
Prabir Pradhan7e186182020-11-10 13:56:45 -08004295void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004296 if (DEBUG_INBOUND_EVENT_DETAILS) {
4297 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004298 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004299 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004300
Antonio Kantekf16f2832021-09-28 04:39:20 +00004301 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004302 { // acquire lock
4303 std::scoped_lock _l(mLock);
4304 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004305 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004306 needWake = enqueueInboundEventLocked(std::move(entry));
4307 } // release lock
4308
4309 if (needWake) {
4310 mLooper->wake();
4311 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004312}
4313
Prabir Pradhan5735a322022-04-11 17:23:34 +00004314InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4315 std::optional<int32_t> targetUid,
4316 InputEventInjectionSync syncMode,
4317 std::chrono::milliseconds timeout,
4318 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004319 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004320 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4321 "policyFlags=0x%08x",
4322 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4323 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004324 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004325 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326
Prabir Pradhan5735a322022-04-11 17:23:34 +00004327 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004329 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004330 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4331 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4332 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4333 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4334 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004335 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004336 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004337 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004338 }
4339
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004340 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004342 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004343 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4344 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004345 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004346 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004347 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004349 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004350 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4351 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4352 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004353 int32_t keyCode = incomingKey.getKeyCode();
4354 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004355 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004356 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004357 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004358 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004359 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4360 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4361 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004362
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004363 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4364 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004365 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004366
4367 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4368 android::base::Timer t;
4369 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4370 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4371 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4372 std::to_string(t.duration().count()).c_str());
4373 }
4374 }
4375
4376 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004377 std::unique_ptr<KeyEntry> injectedEntry =
4378 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004379 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004380 incomingKey.getDisplayId(), policyFlags, action,
4381 flags, keyCode, incomingKey.getScanCode(), metaState,
4382 incomingKey.getRepeatCount(),
4383 incomingKey.getDownTime());
4384 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004385 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386 }
4387
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004388 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004389 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004390 const int32_t action = motionEvent.getAction();
4391 const bool isPointerEvent =
4392 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4393 // If a pointer event has no displayId specified, inject it to the default display.
4394 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4395 ? ADISPLAY_ID_DEFAULT
4396 : event->getDisplayId();
4397 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004398 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004399 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004400 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004401 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004402 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004403 }
4404
4405 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004406 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004407 android::base::Timer t;
4408 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4409 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4410 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4411 std::to_string(t.duration().count()).c_str());
4412 }
4413 }
4414
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004415 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4416 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4417 }
4418
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004419 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004420 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4421 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004422 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004423 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4424 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004425 displayId, policyFlags, action, actionButton,
4426 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004427 motionEvent.getButtonState(),
4428 motionEvent.getClassification(),
4429 motionEvent.getEdgeFlags(),
4430 motionEvent.getXPrecision(),
4431 motionEvent.getYPrecision(),
4432 motionEvent.getRawXCursorPosition(),
4433 motionEvent.getRawYCursorPosition(),
4434 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004435 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004436 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004437 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004438 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004439 sampleEventTimes += 1;
4440 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004441 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004442 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4443 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004444 displayId, policyFlags, action, actionButton,
4445 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004446 motionEvent.getButtonState(),
4447 motionEvent.getClassification(),
4448 motionEvent.getEdgeFlags(),
4449 motionEvent.getXPrecision(),
4450 motionEvent.getYPrecision(),
4451 motionEvent.getRawXCursorPosition(),
4452 motionEvent.getRawYCursorPosition(),
4453 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004454 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004455 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004456 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4457 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004458 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004459 }
4460 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004461 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004462
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004463 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004464 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004465 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466 }
4467
Prabir Pradhan5735a322022-04-11 17:23:34 +00004468 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004469 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470 injectionState->injectionIsAsync = true;
4471 }
4472
4473 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004474 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004475
4476 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004477 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004478 if (DEBUG_INJECTION) {
4479 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4480 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004481 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004482 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004483 }
4484
4485 mLock.unlock();
4486
4487 if (needWake) {
4488 mLooper->wake();
4489 }
4490
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004491 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004492 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004493 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004494
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004495 if (syncMode == InputEventInjectionSync::NONE) {
4496 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004497 } else {
4498 for (;;) {
4499 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004500 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501 break;
4502 }
4503
4504 nsecs_t remainingTimeout = endTime - now();
4505 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004506 if (DEBUG_INJECTION) {
4507 ALOGD("injectInputEvent - Timed out waiting for injection result "
4508 "to become available.");
4509 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004510 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004511 break;
4512 }
4513
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004514 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004515 }
4516
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004517 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4518 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004520 if (DEBUG_INJECTION) {
4521 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4522 injectionState->pendingForegroundDispatches);
4523 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524 nsecs_t remainingTimeout = endTime - now();
4525 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004526 if (DEBUG_INJECTION) {
4527 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4528 "dispatches to finish.");
4529 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004530 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004531 break;
4532 }
4533
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004534 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004535 }
4536 }
4537 }
4538
4539 injectionState->release();
4540 } // release lock
4541
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004542 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004543 LOG(DEBUG) << "injectInputEvent - Finished with result "
4544 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004545 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546
4547 return injectionResult;
4548}
4549
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004550std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004551 std::array<uint8_t, 32> calculatedHmac;
4552 std::unique_ptr<VerifiedInputEvent> result;
4553 switch (event.getType()) {
4554 case AINPUT_EVENT_TYPE_KEY: {
4555 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4556 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4557 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004558 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004559 break;
4560 }
4561 case AINPUT_EVENT_TYPE_MOTION: {
4562 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4563 VerifiedMotionEvent verifiedMotionEvent =
4564 verifiedMotionEventFromMotionEvent(motionEvent);
4565 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004566 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004567 break;
4568 }
4569 default: {
4570 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4571 return nullptr;
4572 }
4573 }
4574 if (calculatedHmac == INVALID_HMAC) {
4575 return nullptr;
4576 }
4577 if (calculatedHmac != event.getHmac()) {
4578 return nullptr;
4579 }
4580 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004581}
4582
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004583void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004584 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004585 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004586 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004587 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004588 LOG(DEBUG) << "Setting input event injection result to "
4589 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004591
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004592 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004593 // Log the outcome since the injector did not wait for the injection result.
4594 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004595 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004596 ALOGV("Asynchronous input event injection succeeded.");
4597 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004598 case InputEventInjectionResult::TARGET_MISMATCH:
4599 ALOGV("Asynchronous input event injection target mismatch.");
4600 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004601 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004602 ALOGW("Asynchronous input event injection failed.");
4603 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004604 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004605 ALOGW("Asynchronous input event injection timed out.");
4606 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004607 case InputEventInjectionResult::PENDING:
4608 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4609 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004610 }
4611 }
4612
4613 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004614 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004615 }
4616}
4617
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004618void InputDispatcher::transformMotionEntryForInjectionLocked(
4619 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004620 // Input injection works in the logical display coordinate space, but the input pipeline works
4621 // display space, so we need to transform the injected events accordingly.
4622 const auto it = mDisplayInfos.find(entry.displayId);
4623 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004624 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004625
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004626 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4627 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4628 const vec2 cursor =
4629 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4630 {entry.xCursorPosition, entry.yCursorPosition});
4631 entry.xCursorPosition = cursor.x;
4632 entry.yCursorPosition = cursor.y;
4633 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004634 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004635 entry.pointerCoords[i] =
4636 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4637 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004638 }
4639}
4640
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004641void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4642 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004643 if (injectionState) {
4644 injectionState->pendingForegroundDispatches += 1;
4645 }
4646}
4647
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004648void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4649 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650 if (injectionState) {
4651 injectionState->pendingForegroundDispatches -= 1;
4652
4653 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004654 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004655 }
4656 }
4657}
4658
chaviw98318de2021-05-19 16:45:23 -05004659const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004660 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004661 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004662 auto it = mWindowHandlesByDisplay.find(displayId);
4663 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004664}
4665
chaviw98318de2021-05-19 16:45:23 -05004666sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004667 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004668 if (windowHandleToken == nullptr) {
4669 return nullptr;
4670 }
4671
Arthur Hungb92218b2018-08-14 12:00:21 +08004672 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004673 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4674 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004675 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004676 return windowHandle;
4677 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004678 }
4679 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004680 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681}
4682
chaviw98318de2021-05-19 16:45:23 -05004683sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4684 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004685 if (windowHandleToken == nullptr) {
4686 return nullptr;
4687 }
4688
chaviw98318de2021-05-19 16:45:23 -05004689 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004690 if (windowHandle->getToken() == windowHandleToken) {
4691 return windowHandle;
4692 }
4693 }
4694 return nullptr;
4695}
4696
chaviw98318de2021-05-19 16:45:23 -05004697sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4698 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004699 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004700 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4701 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004702 if (handle->getId() == windowHandle->getId() &&
4703 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004704 if (windowHandle->getInfo()->displayId != it.first) {
4705 ALOGE("Found window %s in display %" PRId32
4706 ", but it should belong to display %" PRId32,
4707 windowHandle->getName().c_str(), it.first,
4708 windowHandle->getInfo()->displayId);
4709 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004710 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004711 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004712 }
4713 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004714 return nullptr;
4715}
4716
chaviw98318de2021-05-19 16:45:23 -05004717sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004718 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4719 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720}
4721
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004722bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4723 const MotionEntry& motionEntry) const {
4724 const WindowInfo& info = *window->getInfo();
4725
4726 // Skip spy window targets that are not valid for targeted injection.
4727 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004728 return false;
4729 }
4730
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004731 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4732 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4733 return false;
4734 }
4735
4736 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4737 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4738 window->getName().c_str());
4739 return false;
4740 }
4741
4742 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004743 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004744 ALOGW("Not sending touch to %s because there's no corresponding connection",
4745 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004746 return false;
4747 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004748
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004749 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004750 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004751 return false;
4752 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004753
4754 // Drop events that can't be trusted due to occlusion
4755 const auto [x, y] = resolveTouchedPosition(motionEntry);
4756 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4757 if (!isTouchTrustedLocked(occlusionInfo)) {
4758 if (DEBUG_TOUCH_OCCLUSION) {
4759 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4760 for (const auto& log : occlusionInfo.debugInfo) {
4761 ALOGD("%s", log.c_str());
4762 }
4763 }
4764 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4765 occlusionInfo.obscuringUid);
4766 return false;
4767 }
4768
4769 // Drop touch events if requested by input feature
4770 if (shouldDropInput(motionEntry, window)) {
4771 return false;
4772 }
4773
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004774 return true;
4775}
4776
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004777std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4778 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004779 auto connectionIt = mConnectionsByToken.find(token);
4780 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004781 return nullptr;
4782 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004783 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004784}
4785
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004786void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004787 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4788 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004789 // Remove all handles on a display if there are no windows left.
4790 mWindowHandlesByDisplay.erase(displayId);
4791 return;
4792 }
4793
4794 // Since we compare the pointer of input window handles across window updates, we need
4795 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004796 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4797 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4798 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004799 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004800 }
4801
chaviw98318de2021-05-19 16:45:23 -05004802 std::vector<sp<WindowInfoHandle>> newHandles;
4803 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004804 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004805 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004806 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004807 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004808 const bool canReceiveInput =
4809 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4810 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004811 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004812 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004813 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004814 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004815 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004816 }
4817
4818 if (info->displayId != displayId) {
4819 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4820 handle->getName().c_str(), displayId, info->displayId);
4821 continue;
4822 }
4823
Robert Carredd13602020-04-13 17:24:34 -07004824 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4825 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004826 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004827 oldHandle->updateFrom(handle);
4828 newHandles.push_back(oldHandle);
4829 } else {
4830 newHandles.push_back(handle);
4831 }
4832 }
4833
4834 // Insert or replace
4835 mWindowHandlesByDisplay[displayId] = newHandles;
4836}
4837
Arthur Hung72d8dc32020-03-28 00:48:39 +00004838void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004839 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004840 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004841 { // acquire lock
4842 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004843 for (const auto& [displayId, handles] : handlesPerDisplay) {
4844 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004845 }
4846 }
4847 // Wake up poll loop since it may need to make new input dispatching choices.
4848 mLooper->wake();
4849}
4850
Arthur Hungb92218b2018-08-14 12:00:21 +08004851/**
4852 * Called from InputManagerService, update window handle list by displayId that can receive input.
4853 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4854 * If set an empty list, remove all handles from the specific display.
4855 * For focused handle, check if need to change and send a cancel event to previous one.
4856 * For removed handle, check if need to send a cancel event if already in touch.
4857 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004858void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004859 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004860 if (DEBUG_FOCUS) {
4861 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004862 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004863 windowList += iwh->getName() + " ";
4864 }
4865 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4866 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867
Prabir Pradhand65552b2021-10-07 11:23:50 -07004868 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004869 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004870 const WindowInfo& info = *window->getInfo();
4871
4872 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004873 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004874 if (noInputWindow && window->getToken() != nullptr) {
4875 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4876 window->getName().c_str());
4877 window->releaseChannel();
4878 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004879
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004880 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004881 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4882 !info.inputConfig.test(
4883 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004884 "%s has feature SPY, but is not a trusted overlay.",
4885 window->getName().c_str());
4886
Prabir Pradhand65552b2021-10-07 11:23:50 -07004887 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004888 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4889 !info.inputConfig.test(
4890 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004891 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4892 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004893 }
4894
Arthur Hung72d8dc32020-03-28 00:48:39 +00004895 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004896 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004898 // Save the old windows' orientation by ID before it gets updated.
4899 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004900 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004901 oldWindowOrientations.emplace(handle->getId(),
4902 handle->getInfo()->transform.getOrientation());
4903 }
4904
chaviw98318de2021-05-19 16:45:23 -05004905 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004906
chaviw98318de2021-05-19 16:45:23 -05004907 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004908
Vishnu Nairc519ff72021-01-21 08:23:08 -08004909 std::optional<FocusResolver::FocusChanges> changes =
4910 mFocusResolver.setInputWindows(displayId, windowHandles);
4911 if (changes) {
4912 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004913 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004914
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004915 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4916 mTouchStatesByDisplay.find(displayId);
4917 if (stateIt != mTouchStatesByDisplay.end()) {
4918 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004919 for (size_t i = 0; i < state.windows.size();) {
4920 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004921 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004922 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004923 ALOGD("Touched window was removed: %s in display %" PRId32,
4924 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004925 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004926 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004927 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4928 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004929 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00004930 "touched window was removed");
4931 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004932 // Since we are about to drop the touch, cancel the events for the wallpaper as
4933 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004934 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004935 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4936 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004937 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004938 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004940 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004941 state.windows.erase(state.windows.begin() + i);
4942 } else {
4943 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944 }
4945 }
arthurhungb89ccb02020-12-30 16:19:01 +08004946
arthurhung6d4bed92021-03-17 11:59:33 +08004947 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004948 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004949 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004950 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004951 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004952 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4953 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004954 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004955 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004956 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004957
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004958 // Determine if the orientation of any of the input windows have changed, and cancel all
4959 // pointer events if necessary.
4960 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4961 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4962 if (newWindowHandle != nullptr &&
4963 newWindowHandle->getInfo()->transform.getOrientation() !=
4964 oldWindowOrientations[oldWindowHandle->getId()]) {
4965 std::shared_ptr<InputChannel> inputChannel =
4966 getInputChannelLocked(newWindowHandle->getToken());
4967 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004968 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004969 "touched window's orientation changed");
4970 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004971 }
4972 }
4973 }
4974
Arthur Hung72d8dc32020-03-28 00:48:39 +00004975 // Release information for windows that are no longer present.
4976 // This ensures that unused input channels are released promptly.
4977 // Otherwise, they might stick around until the window handle is destroyed
4978 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004979 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004980 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004981 if (DEBUG_FOCUS) {
4982 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004983 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004984 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004985 }
chaviw291d88a2019-02-14 10:33:58 -08004986 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004987}
4988
4989void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004990 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004991 if (DEBUG_FOCUS) {
4992 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4993 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4994 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004995 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004996 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004997 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004998 } // release lock
4999
5000 // Wake up poll loop since it may need to make new input dispatching choices.
5001 mLooper->wake();
5002}
5003
Vishnu Nair599f1412021-06-21 10:39:58 -07005004void InputDispatcher::setFocusedApplicationLocked(
5005 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5006 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5007 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5008
5009 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5010 return; // This application is already focused. No need to wake up or change anything.
5011 }
5012
5013 // Set the new application handle.
5014 if (inputApplicationHandle != nullptr) {
5015 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5016 } else {
5017 mFocusedApplicationHandlesByDisplay.erase(displayId);
5018 }
5019
5020 // No matter what the old focused application was, stop waiting on it because it is
5021 // no longer focused.
5022 resetNoFocusedWindowTimeoutLocked();
5023}
5024
Tiger Huang721e26f2018-07-24 22:26:19 +08005025/**
5026 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5027 * the display not specified.
5028 *
5029 * We track any unreleased events for each window. If a window loses the ability to receive the
5030 * released event, we will send a cancel event to it. So when the focused display is changed, we
5031 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5032 * display. The display-specified events won't be affected.
5033 */
5034void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005035 if (DEBUG_FOCUS) {
5036 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5037 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005038 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005039 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005040
5041 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005042 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005043 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005044 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005045 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005046 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005047 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005048 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005049 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005050 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005051 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005052 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5053 }
5054 }
5055 mFocusedDisplayId = displayId;
5056
Chris Ye3c2d6f52020-08-09 10:39:48 -07005057 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005058 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005059 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005060
Vishnu Nairad321cd2020-08-20 16:40:21 -07005061 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005062 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005063 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005064 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005065 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005066 }
5067 }
5068 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005069 } // release lock
5070
5071 // Wake up poll loop since it may need to make new input dispatching choices.
5072 mLooper->wake();
5073}
5074
Michael Wrightd02c5b62014-02-10 15:10:22 -08005075void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005076 if (DEBUG_FOCUS) {
5077 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5078 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005079
5080 bool changed;
5081 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005082 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005083
5084 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5085 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005086 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005087 }
5088
5089 if (mDispatchEnabled && !enabled) {
5090 resetAndDropEverythingLocked("dispatcher is being disabled");
5091 }
5092
5093 mDispatchEnabled = enabled;
5094 mDispatchFrozen = frozen;
5095 changed = true;
5096 } else {
5097 changed = false;
5098 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005099 } // release lock
5100
5101 if (changed) {
5102 // Wake up poll loop since it may need to make new input dispatching choices.
5103 mLooper->wake();
5104 }
5105}
5106
5107void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005108 if (DEBUG_FOCUS) {
5109 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5110 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005111
5112 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005113 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005114
5115 if (mInputFilterEnabled == enabled) {
5116 return;
5117 }
5118
5119 mInputFilterEnabled = enabled;
5120 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5121 } // release lock
5122
5123 // Wake up poll loop since there might be work to do to drop everything.
5124 mLooper->wake();
5125}
5126
Antonio Kanteka042c022022-07-06 16:51:07 -07005127bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5128 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005129 bool needWake = false;
5130 {
5131 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005132 ALOGD_IF(DEBUG_TOUCH_MODE,
5133 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5134 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5135 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5136 mTouchModePerDisplay.count(displayId) == 0
5137 ? "not set"
5138 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5139
Antonio Kantek15beb512022-06-13 22:35:41 +00005140 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5141 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005142 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005143 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005144 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005145 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5146 !recentWindowsAreOwnedByLocked(pid, uid)) {
5147 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5148 "window nor none of the previously interacted window",
5149 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005150 return false;
5151 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005152 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005153 mTouchModePerDisplay[displayId] = inTouchMode;
5154 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5155 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005156 needWake = enqueueInboundEventLocked(std::move(entry));
5157 } // release lock
5158
5159 if (needWake) {
5160 mLooper->wake();
5161 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005162 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005163}
5164
Antonio Kantek48710e42022-03-24 14:19:30 -07005165bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5166 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5167 if (focusedToken == nullptr) {
5168 return false;
5169 }
5170 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5171 return isWindowOwnedBy(windowHandle, pid, uid);
5172}
5173
5174bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5175 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5176 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5177 const sp<WindowInfoHandle> windowHandle =
5178 getWindowHandleLocked(connectionToken);
5179 return isWindowOwnedBy(windowHandle, pid, uid);
5180 }) != mInteractionConnectionTokens.end();
5181}
5182
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005183void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5184 if (opacity < 0 || opacity > 1) {
5185 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5186 return;
5187 }
5188
5189 std::scoped_lock lock(mLock);
5190 mMaximumObscuringOpacityForTouch = opacity;
5191}
5192
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005193std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5194InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005195 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5196 for (TouchedWindow& w : state.windows) {
5197 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005198 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005199 }
5200 }
5201 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005202 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005203}
5204
arthurhungb89ccb02020-12-30 16:19:01 +08005205bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5206 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005207 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005208 if (DEBUG_FOCUS) {
5209 ALOGD("Trivial transfer to same window.");
5210 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005211 return true;
5212 }
5213
Michael Wrightd02c5b62014-02-10 15:10:22 -08005214 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005215 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005216
Arthur Hungabbb9d82021-09-01 14:52:30 +00005217 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005218 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005219 if (state == nullptr || touchedWindow == nullptr) {
5220 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005221 return false;
5222 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005223
Arthur Hungabbb9d82021-09-01 14:52:30 +00005224 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5225 if (toWindowHandle == nullptr) {
5226 ALOGW("Cannot transfer focus because to window not found.");
5227 return false;
5228 }
5229
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005230 if (DEBUG_FOCUS) {
5231 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005232 touchedWindow->windowHandle->getName().c_str(),
5233 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005234 }
5235
Arthur Hungabbb9d82021-09-01 14:52:30 +00005236 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005237 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005238 BitSet32 pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005239 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005240 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005241
Arthur Hungabbb9d82021-09-01 14:52:30 +00005242 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005243 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005244 ftl::Flags<InputTarget::Flags> newTargetFlags =
5245 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005246 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005247 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005248 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005249 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005250
Arthur Hungabbb9d82021-09-01 14:52:30 +00005251 // Store the dragging window.
5252 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005253 if (pointerIds.count() != 1) {
5254 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5255 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005256 return false;
5257 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005258 // Track the pointer id for drag window and generate the drag state.
5259 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005260 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005261 }
5262
Arthur Hungabbb9d82021-09-01 14:52:30 +00005263 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005264 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5265 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005266 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005267 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005268 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005269 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005270 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005271 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005272 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5273 newTargetFlags);
5274
5275 // Check if the wallpaper window should deliver the corresponding event.
5276 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5277 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005278 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005279 } // release lock
5280
5281 // Wake up poll loop since it may need to make new input dispatching choices.
5282 mLooper->wake();
5283 return true;
5284}
5285
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005286/**
5287 * Get the touched foreground window on the given display.
5288 * Return null if there are no windows touched on that display, or if more than one foreground
5289 * window is being touched.
5290 */
5291sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5292 auto stateIt = mTouchStatesByDisplay.find(displayId);
5293 if (stateIt == mTouchStatesByDisplay.end()) {
5294 ALOGI("No touch state on display %" PRId32, displayId);
5295 return nullptr;
5296 }
5297
5298 const TouchState& state = stateIt->second;
5299 sp<WindowInfoHandle> touchedForegroundWindow;
5300 // If multiple foreground windows are touched, return nullptr
5301 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005302 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005303 if (touchedForegroundWindow != nullptr) {
5304 ALOGI("Two or more foreground windows: %s and %s",
5305 touchedForegroundWindow->getName().c_str(),
5306 window.windowHandle->getName().c_str());
5307 return nullptr;
5308 }
5309 touchedForegroundWindow = window.windowHandle;
5310 }
5311 }
5312 return touchedForegroundWindow;
5313}
5314
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005315// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005316bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005317 sp<IBinder> fromToken;
5318 { // acquire lock
5319 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005320 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005321 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005322 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5323 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005324 return false;
5325 }
5326
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005327 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5328 if (from == nullptr) {
5329 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5330 return false;
5331 }
5332
5333 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005334 } // release lock
5335
5336 return transferTouchFocus(fromToken, destChannelToken);
5337}
5338
Michael Wrightd02c5b62014-02-10 15:10:22 -08005339void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005340 if (DEBUG_FOCUS) {
5341 ALOGD("Resetting and dropping all events (%s).", reason);
5342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005343
Michael Wrightfb04fd52022-11-24 22:31:11 +00005344 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005345 synthesizeCancelationEventsForAllConnectionsLocked(options);
5346
5347 resetKeyRepeatLocked();
5348 releasePendingEventLocked();
5349 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005350 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005352 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005353 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005354 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005355}
5356
5357void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005358 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359 dumpDispatchStateLocked(dump);
5360
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005361 std::istringstream stream(dump);
5362 std::string line;
5363
5364 while (std::getline(stream, line, '\n')) {
5365 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005366 }
5367}
5368
Prabir Pradhan99987712020-11-10 18:43:05 -08005369std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5370 std::string dump;
5371
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005372 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5373 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005374
5375 std::string windowName = "None";
5376 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005377 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005378 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5379 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5380 : "token has capture without window";
5381 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005382 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005383
5384 return dump;
5385}
5386
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005387void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005388 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5389 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5390 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005391 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005392
Tiger Huang721e26f2018-07-24 22:26:19 +08005393 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5394 dump += StringPrintf(INDENT "FocusedApplications:\n");
5395 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5396 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005397 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005398 const std::chrono::duration timeout =
5399 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005400 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005401 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005402 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005403 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005404 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005405 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005406 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005407
Vishnu Nairc519ff72021-01-21 08:23:08 -08005408 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005409 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005411 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005412 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005413 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005414 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5415 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005416 }
5417 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005418 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005419 }
5420
arthurhung6d4bed92021-03-17 11:59:33 +08005421 if (mDragState) {
5422 dump += StringPrintf(INDENT "DragState:\n");
5423 mDragState->dump(dump, INDENT2);
5424 }
5425
Arthur Hungb92218b2018-08-14 12:00:21 +08005426 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005427 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5428 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5429 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5430 const auto& displayInfo = it->second;
5431 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5432 displayInfo.logicalHeight);
5433 displayInfo.transform.dump(dump, "transform", INDENT4);
5434 } else {
5435 dump += INDENT2 "No DisplayInfo found!\n";
5436 }
5437
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005438 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005439 dump += INDENT2 "Windows:\n";
5440 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005441 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5442 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005443
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005444 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005445 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005446 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005447 "applicationInfo.name=%s, "
5448 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005449 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005450 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005451 windowInfo->displayId,
5452 windowInfo->inputConfig.string().c_str(),
5453 windowInfo->alpha, windowInfo->frameLeft,
5454 windowInfo->frameTop, windowInfo->frameRight,
5455 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005456 windowInfo->applicationInfo.name.c_str(),
5457 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005458 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005459 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005460 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005461 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005462 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005463 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005464 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005465 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005466 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005467 }
5468 } else {
5469 dump += INDENT2 "Windows: <none>\n";
5470 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005471 }
5472 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005473 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005474 }
5475
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005476 if (!mGlobalMonitorsByDisplay.empty()) {
5477 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5478 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005479 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005480 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005481 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005482 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005483 }
5484
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005485 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005486
5487 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005488 if (!mRecentQueue.empty()) {
5489 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005490 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005491 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005492 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005493 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005494 }
5495 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005496 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497 }
5498
5499 // Dump event currently being dispatched.
5500 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005501 dump += INDENT "PendingEvent:\n";
5502 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005503 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005504 dump += StringPrintf(", age=%" PRId64 "ms\n",
5505 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005506 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005507 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005508 }
5509
5510 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005511 if (!mInboundQueue.empty()) {
5512 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005513 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005514 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005515 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005516 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005517 }
5518 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005519 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005520 }
5521
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005522 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005523 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005524 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005525 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005526 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005527 }
5528 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005529 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005530 }
5531
Prabir Pradhancef936d2021-07-21 16:17:52 +00005532 if (!mCommandQueue.empty()) {
5533 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5534 } else {
5535 dump += INDENT "CommandQueue: <empty>\n";
5536 }
5537
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005538 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005539 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005540 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005541 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005542 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005543 connection->inputChannel->getFd().get(),
5544 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005545 connection->getWindowName().c_str(),
5546 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005547 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005548
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005549 if (!connection->outboundQueue.empty()) {
5550 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5551 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005552 dump += dumpQueue(connection->outboundQueue, currentTime);
5553
Michael Wrightd02c5b62014-02-10 15:10:22 -08005554 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005555 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005556 }
5557
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005558 if (!connection->waitQueue.empty()) {
5559 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5560 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005561 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005563 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005564 }
5565 }
5566 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005567 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005568 }
5569
5570 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005571 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5572 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005573 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005574 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005575 }
5576
Antonio Kantek15beb512022-06-13 22:35:41 +00005577 if (!mTouchModePerDisplay.empty()) {
5578 dump += INDENT "TouchModePerDisplay:\n";
5579 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5580 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5581 std::to_string(touchMode).c_str());
5582 }
5583 } else {
5584 dump += INDENT "TouchModePerDisplay: <none>\n";
5585 }
5586
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005587 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005588 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5589 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5590 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005591 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005592 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005593}
5594
Michael Wright3dd60e22019-03-27 22:06:44 +00005595void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5596 const size_t numMonitors = monitors.size();
5597 for (size_t i = 0; i < numMonitors; i++) {
5598 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005599 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005600 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5601 dump += "\n";
5602 }
5603}
5604
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005605class LooperEventCallback : public LooperCallback {
5606public:
5607 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5608 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5609
5610private:
5611 std::function<int(int events)> mCallback;
5612};
5613
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005614Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005615 if (DEBUG_CHANNEL_CREATION) {
5616 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5617 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005618
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005619 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005620 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005621 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005622
5623 if (result) {
5624 return base::Error(result) << "Failed to open input channel pair with name " << name;
5625 }
5626
Michael Wrightd02c5b62014-02-10 15:10:22 -08005627 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005628 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005629 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005630 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005631 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005632 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005633
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005634 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5635 ALOGE("Created a new connection, but the token %p is already known", token.get());
5636 }
5637 mConnectionsByToken.emplace(token, connection);
5638
5639 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5640 this, std::placeholders::_1, token);
5641
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005642 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5643 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005644 } // release lock
5645
5646 // Wake the looper because some connections have changed.
5647 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005648 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005649}
5650
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005651Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005652 const std::string& name,
5653 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005654 std::shared_ptr<InputChannel> serverChannel;
5655 std::unique_ptr<InputChannel> clientChannel;
5656 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5657 if (result) {
5658 return base::Error(result) << "Failed to open input channel pair with name " << name;
5659 }
5660
Michael Wright3dd60e22019-03-27 22:06:44 +00005661 { // acquire lock
5662 std::scoped_lock _l(mLock);
5663
5664 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005665 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5666 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005667 }
5668
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005669 sp<Connection> connection =
5670 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005671 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005672 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005673
5674 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5675 ALOGE("Created a new connection, but the token %p is already known", token.get());
5676 }
5677 mConnectionsByToken.emplace(token, connection);
5678 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5679 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005680
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005681 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005682
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005683 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5684 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005685 }
Garfield Tan15601662020-09-22 15:32:38 -07005686
Michael Wright3dd60e22019-03-27 22:06:44 +00005687 // Wake the looper because some connections have changed.
5688 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005689 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005690}
5691
Garfield Tan15601662020-09-22 15:32:38 -07005692status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005693 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005694 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005695
Garfield Tan15601662020-09-22 15:32:38 -07005696 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005697 if (status) {
5698 return status;
5699 }
5700 } // release lock
5701
5702 // Wake the poll loop because removing the connection may have changed the current
5703 // synchronization state.
5704 mLooper->wake();
5705 return OK;
5706}
5707
Garfield Tan15601662020-09-22 15:32:38 -07005708status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5709 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005710 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005711 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005712 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005713 return BAD_VALUE;
5714 }
5715
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005716 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005717
Michael Wrightd02c5b62014-02-10 15:10:22 -08005718 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005719 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005720 }
5721
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005722 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005723
5724 nsecs_t currentTime = now();
5725 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5726
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005727 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005728 return OK;
5729}
5730
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005731void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005732 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5733 auto& [displayId, monitors] = *it;
5734 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5735 return monitor.inputChannel->getConnectionToken() == connectionToken;
5736 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005737
Michael Wright3dd60e22019-03-27 22:06:44 +00005738 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005739 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005740 } else {
5741 ++it;
5742 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005743 }
5744}
5745
Michael Wright3dd60e22019-03-27 22:06:44 +00005746status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005747 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005748 return pilferPointersLocked(token);
5749}
Michael Wright3dd60e22019-03-27 22:06:44 +00005750
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005751status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005752 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5753 if (!requestingChannel) {
5754 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5755 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005756 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005757
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005758 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07005759 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.isEmpty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005760 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5761 " Ignoring.");
5762 return BAD_VALUE;
5763 }
5764
5765 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005766 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005767 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005768 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005769 "input channel stole pointer stream");
5770 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005771 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005772 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005773 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005774 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005775 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005776 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005777 if (channel != nullptr && channel->getConnectionToken() != token) {
5778 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5779 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5780 canceledWindows += channel->getName();
5781 }
5782 }
5783 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5784 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5785 canceledWindows.c_str());
5786
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005787 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005788 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08005789 for (BitSet32 idBits(window.pointerIds); !idBits.isEmpty();) {
5790 uint32_t id = idBits.clearFirstMarkedBit();
5791 window.pilferedPointerIds.set(id);
5792 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005793
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005794 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005795 return OK;
5796}
5797
Prabir Pradhan99987712020-11-10 18:43:05 -08005798void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5799 { // acquire lock
5800 std::scoped_lock _l(mLock);
5801 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005802 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005803 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5804 windowHandle != nullptr ? windowHandle->getName().c_str()
5805 : "token without window");
5806 }
5807
Vishnu Nairc519ff72021-01-21 08:23:08 -08005808 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005809 if (focusedToken != windowToken) {
5810 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5811 enabled ? "enable" : "disable");
5812 return;
5813 }
5814
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005815 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005816 ALOGW("Ignoring request to %s Pointer Capture: "
5817 "window has %s requested pointer capture.",
5818 enabled ? "enable" : "disable", enabled ? "already" : "not");
5819 return;
5820 }
5821
Christine Franksb768bb42021-11-29 12:11:31 -08005822 if (enabled) {
5823 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5824 mIneligibleDisplaysForPointerCapture.end(),
5825 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5826 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5827 return;
5828 }
5829 }
5830
Prabir Pradhan99987712020-11-10 18:43:05 -08005831 setPointerCaptureLocked(enabled);
5832 } // release lock
5833
5834 // Wake the thread to process command entries.
5835 mLooper->wake();
5836}
5837
Christine Franksb768bb42021-11-29 12:11:31 -08005838void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5839 { // acquire lock
5840 std::scoped_lock _l(mLock);
5841 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5842 if (!isEligible) {
5843 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5844 }
5845 } // release lock
5846}
5847
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005848std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5849 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005850 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005851 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005852 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005853 }
5854 }
5855 }
5856 return std::nullopt;
5857}
5858
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005859sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005860 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005861 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005862 }
5863
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005864 for (const auto& [token, connection] : mConnectionsByToken) {
5865 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005866 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005867 }
5868 }
Robert Carr4e670e52018-08-15 13:26:12 -07005869
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005870 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005871}
5872
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005873std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5874 sp<Connection> connection = getConnectionLocked(connectionToken);
5875 if (connection == nullptr) {
5876 return "<nullptr>";
5877 }
5878 return connection->getInputChannelName();
5879}
5880
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005881void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005882 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005883 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005884}
5885
Prabir Pradhancef936d2021-07-21 16:17:52 +00005886void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5887 const sp<Connection>& connection, uint32_t seq,
5888 bool handled, nsecs_t consumeTime) {
5889 // Handle post-event policy actions.
5890 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5891 if (dispatchEntryIt == connection->waitQueue.end()) {
5892 return;
5893 }
5894 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5895 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5896 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5897 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5898 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5899 }
5900 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5901 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5902 connection->inputChannel->getConnectionToken(),
5903 dispatchEntry->deliveryTime, consumeTime, finishTime);
5904 }
5905
5906 bool restartEvent;
5907 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5908 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5909 restartEvent =
5910 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5911 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5912 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5913 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5914 handled);
5915 } else {
5916 restartEvent = false;
5917 }
5918
5919 // Dequeue the event and start the next cycle.
5920 // Because the lock might have been released, it is possible that the
5921 // contents of the wait queue to have been drained, so we need to double-check
5922 // a few things.
5923 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5924 if (dispatchEntryIt != connection->waitQueue.end()) {
5925 dispatchEntry = *dispatchEntryIt;
5926 connection->waitQueue.erase(dispatchEntryIt);
5927 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5928 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5929 if (!connection->responsive) {
5930 connection->responsive = isConnectionResponsive(*connection);
5931 if (connection->responsive) {
5932 // The connection was unresponsive, and now it's responsive.
5933 processConnectionResponsiveLocked(*connection);
5934 }
5935 }
5936 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005937 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005938 connection->outboundQueue.push_front(dispatchEntry);
5939 traceOutboundQueueLength(*connection);
5940 } else {
5941 releaseDispatchEntry(dispatchEntry);
5942 }
5943 }
5944
5945 // Start the next dispatch cycle for this connection.
5946 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005947}
5948
Prabir Pradhancef936d2021-07-21 16:17:52 +00005949void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5950 const sp<IBinder>& newToken) {
5951 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5952 scoped_unlock unlock(mLock);
5953 mPolicy->notifyFocusChanged(oldToken, newToken);
5954 };
5955 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005956}
5957
Prabir Pradhancef936d2021-07-21 16:17:52 +00005958void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5959 auto command = [this, token, x, y]() REQUIRES(mLock) {
5960 scoped_unlock unlock(mLock);
5961 mPolicy->notifyDropWindow(token, x, y);
5962 };
5963 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005964}
5965
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005966void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5967 if (connection == nullptr) {
5968 LOG_ALWAYS_FATAL("Caller must check for nullness");
5969 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005970 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5971 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005972 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005973 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005974 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005975 return;
5976 }
5977 /**
5978 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5979 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5980 * has changed. This could cause newer entries to time out before the already dispatched
5981 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5982 * processes the events linearly. So providing information about the oldest entry seems to be
5983 * most useful.
5984 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005985 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005986 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5987 std::string reason =
5988 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005989 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005990 ns2ms(currentWait),
5991 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005992 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005993 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005994
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005995 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5996
5997 // Stop waking up for events on this connection, it is already unresponsive
5998 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005999}
6000
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006001void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6002 std::string reason =
6003 StringPrintf("%s does not have a focused window", application->getName().c_str());
6004 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006005
Prabir Pradhancef936d2021-07-21 16:17:52 +00006006 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
6007 scoped_unlock unlock(mLock);
6008 mPolicy->notifyNoFocusedWindowAnr(application);
6009 };
6010 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006011}
6012
chaviw98318de2021-05-19 16:45:23 -05006013void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006014 const std::string& reason) {
6015 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6016 updateLastAnrStateLocked(windowLabel, reason);
6017}
6018
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006019void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6020 const std::string& reason) {
6021 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006022 updateLastAnrStateLocked(windowLabel, reason);
6023}
6024
6025void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6026 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006027 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006028 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006029 struct tm tm;
6030 localtime_r(&t, &tm);
6031 char timestr[64];
6032 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006033 mLastAnrState.clear();
6034 mLastAnrState += INDENT "ANR:\n";
6035 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006036 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6037 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006038 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006039}
6040
Prabir Pradhancef936d2021-07-21 16:17:52 +00006041void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6042 KeyEntry& entry) {
6043 const KeyEvent event = createKeyEvent(entry);
6044 nsecs_t delay = 0;
6045 { // release lock
6046 scoped_unlock unlock(mLock);
6047 android::base::Timer t;
6048 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
6049 entry.policyFlags);
6050 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6051 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6052 std::to_string(t.duration().count()).c_str());
6053 }
6054 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006055
6056 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006057 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006058 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006059 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006060 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006061 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006062 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006063 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006064}
6065
Prabir Pradhancef936d2021-07-21 16:17:52 +00006066void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006067 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006068 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006069 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006070 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006071 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006072 };
6073 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006074}
6075
Prabir Pradhanedd96402022-02-15 01:46:16 -08006076void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6077 std::optional<int32_t> pid) {
6078 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006079 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006080 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006081 };
6082 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006083}
6084
6085/**
6086 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6087 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6088 * command entry to the command queue.
6089 */
6090void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6091 std::string reason) {
6092 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006093 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006094 if (connection.monitor) {
6095 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6096 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006097 pid = findMonitorPidByTokenLocked(connectionToken);
6098 } else {
6099 // The connection is a window
6100 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6101 reason.c_str());
6102 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6103 if (handle != nullptr) {
6104 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006105 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006106 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006107 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006108}
6109
6110/**
6111 * Tell the policy that a connection has become responsive so that it can stop ANR.
6112 */
6113void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6114 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006115 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006116 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006117 pid = findMonitorPidByTokenLocked(connectionToken);
6118 } else {
6119 // The connection is a window
6120 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6121 if (handle != nullptr) {
6122 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006123 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006124 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006125 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006126}
6127
Prabir Pradhancef936d2021-07-21 16:17:52 +00006128bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006129 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006130 KeyEntry& keyEntry, bool handled) {
6131 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006132 if (!handled) {
6133 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006134 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006135 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006136 return false;
6137 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006138
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006139 // Get the fallback key state.
6140 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006141 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006142 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006143 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006144 connection->inputState.removeFallbackKey(originalKeyCode);
6145 }
6146
6147 if (handled || !dispatchEntry->hasForegroundTarget()) {
6148 // If the application handles the original key for which we previously
6149 // generated a fallback or if the window is not a foreground window,
6150 // then cancel the associated fallback key, if any.
6151 if (fallbackKeyCode != -1) {
6152 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006153 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6154 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6155 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6156 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6157 keyEntry.policyFlags);
6158 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006159 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006160 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006161
6162 mLock.unlock();
6163
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006164 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006165 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006166
6167 mLock.lock();
6168
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006169 // Cancel the fallback key.
6170 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006171 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006172 "application handled the original non-fallback key "
6173 "or is no longer a foreground target, "
6174 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006175 options.keyCode = fallbackKeyCode;
6176 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006177 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006178 connection->inputState.removeFallbackKey(originalKeyCode);
6179 }
6180 } else {
6181 // If the application did not handle a non-fallback key, first check
6182 // that we are in a good state to perform unhandled key event processing
6183 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006184 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006185 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006186 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6187 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6188 "since this is not an initial down. "
6189 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6190 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6191 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006192 return false;
6193 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006194
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006195 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006196 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6197 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6198 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6199 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6200 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006201 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006202
6203 mLock.unlock();
6204
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006205 bool fallback =
6206 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006207 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006208
6209 mLock.lock();
6210
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006211 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006212 connection->inputState.removeFallbackKey(originalKeyCode);
6213 return false;
6214 }
6215
6216 // Latch the fallback keycode for this key on an initial down.
6217 // The fallback keycode cannot change at any other point in the lifecycle.
6218 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006219 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006220 fallbackKeyCode = event.getKeyCode();
6221 } else {
6222 fallbackKeyCode = AKEYCODE_UNKNOWN;
6223 }
6224 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6225 }
6226
6227 ALOG_ASSERT(fallbackKeyCode != -1);
6228
6229 // Cancel the fallback key if the policy decides not to send it anymore.
6230 // We will continue to dispatch the key to the policy but we will no
6231 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006232 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6233 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006234 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6235 if (fallback) {
6236 ALOGD("Unhandled key event: Policy requested to send key %d"
6237 "as a fallback for %d, but on the DOWN it had requested "
6238 "to send %d instead. Fallback canceled.",
6239 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6240 } else {
6241 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6242 "but on the DOWN it had requested to send %d. "
6243 "Fallback canceled.",
6244 originalKeyCode, fallbackKeyCode);
6245 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006246 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006247
Michael Wrightfb04fd52022-11-24 22:31:11 +00006248 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006249 "canceling fallback, policy no longer desires it");
6250 options.keyCode = fallbackKeyCode;
6251 synthesizeCancelationEventsForConnectionLocked(connection, options);
6252
6253 fallback = false;
6254 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006255 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006256 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006257 }
6258 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006259
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006260 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6261 {
6262 std::string msg;
6263 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6264 connection->inputState.getFallbackKeys();
6265 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6266 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6267 }
6268 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6269 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006270 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006271 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006272
6273 if (fallback) {
6274 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006275 keyEntry.eventTime = event.getEventTime();
6276 keyEntry.deviceId = event.getDeviceId();
6277 keyEntry.source = event.getSource();
6278 keyEntry.displayId = event.getDisplayId();
6279 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6280 keyEntry.keyCode = fallbackKeyCode;
6281 keyEntry.scanCode = event.getScanCode();
6282 keyEntry.metaState = event.getMetaState();
6283 keyEntry.repeatCount = event.getRepeatCount();
6284 keyEntry.downTime = event.getDownTime();
6285 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006286
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006287 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6288 ALOGD("Unhandled key event: Dispatching fallback key. "
6289 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6290 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6291 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006292 return true; // restart the event
6293 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006294 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6295 ALOGD("Unhandled key event: No fallback key.");
6296 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006297
6298 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006299 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006300 }
6301 }
6302 return false;
6303}
6304
Prabir Pradhancef936d2021-07-21 16:17:52 +00006305bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006306 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006307 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006308 return false;
6309}
6310
Michael Wrightd02c5b62014-02-10 15:10:22 -08006311void InputDispatcher::traceInboundQueueLengthLocked() {
6312 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006313 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006314 }
6315}
6316
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006317void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006318 if (ATRACE_ENABLED()) {
6319 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006320 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6321 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006322 }
6323}
6324
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006325void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006326 if (ATRACE_ENABLED()) {
6327 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006328 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6329 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006330 }
6331}
6332
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006333void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006334 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006335
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006336 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006337 dumpDispatchStateLocked(dump);
6338
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006339 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006340 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006341 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006342 }
6343}
6344
6345void InputDispatcher::monitor() {
6346 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006347 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006348 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006349 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006350}
6351
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006352/**
6353 * Wake up the dispatcher and wait until it processes all events and commands.
6354 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6355 * this method can be safely called from any thread, as long as you've ensured that
6356 * the work you are interested in completing has already been queued.
6357 */
6358bool InputDispatcher::waitForIdle() {
6359 /**
6360 * Timeout should represent the longest possible time that a device might spend processing
6361 * events and commands.
6362 */
6363 constexpr std::chrono::duration TIMEOUT = 100ms;
6364 std::unique_lock lock(mLock);
6365 mLooper->wake();
6366 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6367 return result == std::cv_status::no_timeout;
6368}
6369
Vishnu Naire798b472020-07-23 13:52:21 -07006370/**
6371 * Sets focus to the window identified by the token. This must be called
6372 * after updating any input window handles.
6373 *
6374 * Params:
6375 * request.token - input channel token used to identify the window that should gain focus.
6376 * request.focusedToken - the token that the caller expects currently to be focused. If the
6377 * specified token does not match the currently focused window, this request will be dropped.
6378 * If the specified focused token matches the currently focused window, the call will succeed.
6379 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6380 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6381 * when requesting the focus change. This determines which request gets
6382 * precedence if there is a focus change request from another source such as pointer down.
6383 */
Vishnu Nair958da932020-08-21 17:12:37 -07006384void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6385 { // acquire lock
6386 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006387 std::optional<FocusResolver::FocusChanges> changes =
6388 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6389 if (changes) {
6390 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006391 }
6392 } // release lock
6393 // Wake up poll loop since it may need to make new input dispatching choices.
6394 mLooper->wake();
6395}
6396
Vishnu Nairc519ff72021-01-21 08:23:08 -08006397void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6398 if (changes.oldFocus) {
6399 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006400 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006401 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006402 "focus left window");
6403 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006404 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006405 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006406 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006407 if (changes.newFocus) {
6408 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006409 }
6410
Prabir Pradhan99987712020-11-10 18:43:05 -08006411 // If a window has pointer capture, then it must have focus. We need to ensure that this
6412 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6413 // If the window loses focus before it loses pointer capture, then the window can be in a state
6414 // where it has pointer capture but not focus, violating the contract. Therefore we must
6415 // dispatch the pointer capture event before the focus event. Since focus events are added to
6416 // the front of the queue (above), we add the pointer capture event to the front of the queue
6417 // after the focus events are added. This ensures the pointer capture event ends up at the
6418 // front.
6419 disablePointerCaptureForcedLocked();
6420
Vishnu Nairc519ff72021-01-21 08:23:08 -08006421 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006422 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006423 }
6424}
Vishnu Nair958da932020-08-21 17:12:37 -07006425
Prabir Pradhan99987712020-11-10 18:43:05 -08006426void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006427 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006428 return;
6429 }
6430
6431 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6432
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006433 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006434 setPointerCaptureLocked(false);
6435 }
6436
6437 if (!mWindowTokenWithPointerCapture) {
6438 // No need to send capture changes because no window has capture.
6439 return;
6440 }
6441
6442 if (mPendingEvent != nullptr) {
6443 // Move the pending event to the front of the queue. This will give the chance
6444 // for the pending event to be dropped if it is a captured event.
6445 mInboundQueue.push_front(mPendingEvent);
6446 mPendingEvent = nullptr;
6447 }
6448
6449 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006450 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006451 mInboundQueue.push_front(std::move(entry));
6452}
6453
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006454void InputDispatcher::setPointerCaptureLocked(bool enable) {
6455 mCurrentPointerCaptureRequest.enable = enable;
6456 mCurrentPointerCaptureRequest.seq++;
6457 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006458 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006459 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006460 };
6461 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006462}
6463
Vishnu Nair599f1412021-06-21 10:39:58 -07006464void InputDispatcher::displayRemoved(int32_t displayId) {
6465 { // acquire lock
6466 std::scoped_lock _l(mLock);
6467 // Set an empty list to remove all handles from the specific display.
6468 setInputWindowsLocked(/* window handles */ {}, displayId);
6469 setFocusedApplicationLocked(displayId, nullptr);
6470 // Call focus resolver to clean up stale requests. This must be called after input windows
6471 // have been removed for the removed display.
6472 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006473 // Reset pointer capture eligibility, regardless of previous state.
6474 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006475 // Remove the associated touch mode state.
6476 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006477 } // release lock
6478
6479 // Wake up poll loop since it may need to make new input dispatching choices.
6480 mLooper->wake();
6481}
6482
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006483void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6484 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006485 // The listener sends the windows as a flattened array. Separate the windows by display for
6486 // more convenient parsing.
6487 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006488 for (const auto& info : windowInfos) {
6489 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006490 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006491 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006492
6493 { // acquire lock
6494 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006495
6496 // Ensure that we have an entry created for all existing displays so that if a displayId has
6497 // no windows, we can tell that the windows were removed from the display.
6498 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6499 handlesPerDisplay[displayId];
6500 }
6501
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006502 mDisplayInfos.clear();
6503 for (const auto& displayInfo : displayInfos) {
6504 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6505 }
6506
6507 for (const auto& [displayId, handles] : handlesPerDisplay) {
6508 setInputWindowsLocked(handles, displayId);
6509 }
6510 }
6511 // Wake up poll loop since it may need to make new input dispatching choices.
6512 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006513}
6514
Vishnu Nair062a8672021-09-03 16:07:44 -07006515bool InputDispatcher::shouldDropInput(
6516 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006517 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6518 (windowHandle->getInfo()->inputConfig.test(
6519 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006520 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006521 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6522 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006523 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006524 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006525 windowHandle->getInfo()->displayId);
6526 return true;
6527 }
6528 return false;
6529}
6530
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006531void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6532 const std::vector<gui::WindowInfo>& windowInfos,
6533 const std::vector<DisplayInfo>& displayInfos) {
6534 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6535}
6536
Arthur Hungdfd528e2021-12-08 13:23:04 +00006537void InputDispatcher::cancelCurrentTouch() {
6538 {
6539 std::scoped_lock _l(mLock);
6540 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006541 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006542 "cancel current touch");
6543 synthesizeCancelationEventsForAllConnectionsLocked(options);
6544
6545 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006546 }
6547 // Wake up poll loop since there might be work to do.
6548 mLooper->wake();
6549}
6550
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006551void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6552 std::scoped_lock _l(mLock);
6553 mMonitorDispatchingTimeout = timeout;
6554}
6555
Arthur Hungc539dbb2022-12-08 07:45:36 +00006556void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6557 const sp<WindowInfoHandle>& oldWindowHandle,
6558 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006559 TouchState& state, int32_t pointerId,
6560 std::vector<InputTarget>& targets) {
6561 BitSet32 pointerIds;
6562 pointerIds.markBit(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006563 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6564 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6565 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6566 newWindowHandle->getInfo()->inputConfig.test(
6567 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6568 const sp<WindowInfoHandle> oldWallpaper =
6569 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6570 const sp<WindowInfoHandle> newWallpaper =
6571 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6572 if (oldWallpaper == newWallpaper) {
6573 return;
6574 }
6575
6576 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006577 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6578 addWindowTargetLocked(oldWallpaper,
6579 oldTouchedWindow.targetFlags |
6580 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6581 pointerIds, oldTouchedWindow.firstDownTimeInTarget, targets);
6582 state.removeTouchedPointerFromWindow(pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006583 }
6584
6585 if (newWallpaper != nullptr) {
6586 state.addOrUpdateWindow(newWallpaper,
6587 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6588 InputTarget::Flags::WINDOW_IS_OBSCURED |
6589 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6590 pointerIds);
6591 }
6592}
6593
6594void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6595 ftl::Flags<InputTarget::Flags> newTargetFlags,
6596 const sp<WindowInfoHandle> fromWindowHandle,
6597 const sp<WindowInfoHandle> toWindowHandle,
6598 TouchState& state, const BitSet32& pointerIds) {
6599 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6600 fromWindowHandle->getInfo()->inputConfig.test(
6601 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6602 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6603 toWindowHandle->getInfo()->inputConfig.test(
6604 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6605
6606 const sp<WindowInfoHandle> oldWallpaper =
6607 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6608 const sp<WindowInfoHandle> newWallpaper =
6609 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6610 if (oldWallpaper == newWallpaper) {
6611 return;
6612 }
6613
6614 if (oldWallpaper != nullptr) {
6615 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6616 "transferring touch focus to another window");
6617 state.removeWindowByToken(oldWallpaper->getToken());
6618 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6619 }
6620
6621 if (newWallpaper != nullptr) {
6622 nsecs_t downTimeInTarget = now();
6623 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6624 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6625 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6626 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6627 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
6628 sp<Connection> wallpaperConnection = getConnectionLocked(newWallpaper->getToken());
6629 if (wallpaperConnection != nullptr) {
6630 sp<Connection> toConnection = getConnectionLocked(toWindowHandle->getToken());
6631 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6632 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6633 wallpaperFlags);
6634 }
6635 }
6636}
6637
6638sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6639 const sp<WindowInfoHandle>& windowHandle) const {
6640 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6641 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6642 bool foundWindow = false;
6643 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6644 if (!foundWindow && otherHandle != windowHandle) {
6645 continue;
6646 }
6647 if (windowHandle == otherHandle) {
6648 foundWindow = true;
6649 continue;
6650 }
6651
6652 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6653 return otherHandle;
6654 }
6655 }
6656 return nullptr;
6657}
6658
Garfield Tane84e6f92019-08-29 17:28:41 -07006659} // namespace android::inputdispatcher