blob: 44c133c9a12cd2289a6014c54ba0d053ac58895c [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
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002306 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2307 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2308
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002309 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002310 isDownOrPointerDown
2311 ? std::make_optional(entry.eventTime)
2312 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002313
2314 // If this is the pointer going down and the touched window has a wallpaper
2315 // then also add the touched wallpaper windows so they are locked in for the duration
2316 // of the touch gesture.
2317 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2318 // engine only supports touch events. We would need to add a mechanism similar
2319 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002320 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002321 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2322 windowHandle->getInfo()->inputConfig.test(
2323 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2324 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2325 if (wallpaper != nullptr) {
2326 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2327 InputTarget::Flags::WINDOW_IS_OBSCURED |
2328 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2329 InputTarget::Flags::DISPATCH_AS_IS;
2330 if (isSplit) {
2331 wallpaperFlags |= InputTarget::Flags::SPLIT;
2332 }
2333 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2334 entry.eventTime);
2335 }
2336 }
2337 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002339
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002340 // If a window is already pilfering some pointers, give it this new pointer as well and
2341 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2342 // which is a specific behaviour that we want.
2343 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2344 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
2345 if (touchedWindow.pointerIds.hasBit(pointerId) &&
2346 touchedWindow.pilferedPointerIds.count() > 0) {
2347 // This window is already pilfering some pointers, and this new pointer is also
2348 // going to it. Therefore, take over this pointer and don't give it to anyone
2349 // else.
2350 touchedWindow.pilferedPointerIds.set(pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002351 }
2352 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002353
2354 // Restrict all pilfered pointers to the pilfering windows.
2355 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 } else {
2357 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2358
2359 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002360 if (!tempTouchState.isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002361 ALOGD_IF(DEBUG_FOCUS,
2362 "Dropping event because the pointer is not down or we previously "
2363 "dropped the pointer down event in display %" PRId32 ": %s",
2364 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002365 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002366 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367 }
2368
arthurhung6d4bed92021-03-17 11:59:33 +08002369 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002370
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002372 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002373 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002374 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07002375 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002376 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002377 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002378 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002379
Prabir Pradhan5735a322022-04-11 17:23:34 +00002380 // Verify targeted injection.
2381 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2382 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002383 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002384 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002385 }
2386
Vishnu Nair062a8672021-09-03 16:07:44 -07002387 // Drop touch events if requested by input feature
2388 if (newTouchedWindowHandle != nullptr &&
2389 shouldDropInput(entry, newTouchedWindowHandle)) {
2390 newTouchedWindowHandle = nullptr;
2391 }
2392
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002393 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2394 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002395 if (DEBUG_FOCUS) {
2396 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2397 oldTouchedWindowHandle->getName().c_str(),
2398 newTouchedWindowHandle->getName().c_str(), displayId);
2399 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002400 // Make a slippery exit from the old window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002401 BitSet32 pointerIds;
2402 const int32_t pointerId = entry.pointerProperties[0].id;
2403 pointerIds.markBit(pointerId);
2404
2405 const TouchedWindow& touchedWindow =
2406 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2407 addWindowTargetLocked(oldTouchedWindowHandle,
2408 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
2409 touchedWindow.firstDownTimeInTarget, targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410
2411 // Make a slippery entrance into the new window.
2412 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002413 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002414 }
2415
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002416 ftl::Flags<InputTarget::Flags> targetFlags =
2417 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002418 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002419 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002420 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002422 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002423 }
2424 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002425 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002426 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002427 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002428 }
2429
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002430 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2431 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002432
2433 // Check if the wallpaper window should deliver the corresponding event.
2434 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002435 tempTouchState, pointerId, targets);
2436 tempTouchState.removeTouchedPointerFromWindow(pointerId, oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437 }
2438 }
Arthur Hung96483742022-11-15 03:30:48 +00002439
2440 // Update the pointerIds for non-splittable when it received pointer down.
2441 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2442 // If no split, we suppose all touched windows should receive pointer down.
2443 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2444 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2445 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2446 // Ignore drag window for it should just track one pointer.
2447 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2448 continue;
2449 }
2450 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2451 }
2452 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002453 }
2454
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002455 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002456 {
2457 std::vector<TouchedWindow> hoveringWindows =
2458 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2459 for (const TouchedWindow& touchedWindow : hoveringWindows) {
2460 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2461 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2462 targets);
2463 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464 }
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002465 // Ensure that we have at least one foreground window or at least one window that cannot be a
2466 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2467 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2468 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002469 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2470 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002471 return !canReceiveForegroundTouches(
2472 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002473 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002474 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002475 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2476 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002477 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002478 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002479 }
2480
Prabir Pradhan5735a322022-04-11 17:23:34 +00002481 // Ensure that all touched windows are valid for injection.
2482 if (entry.injectionState != nullptr) {
2483 std::string errs;
2484 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002485 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002486 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2487 // dispatched to any uid, since the coords will be zeroed out later.
2488 continue;
2489 }
2490 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2491 if (err) errs += "\n - " + *err;
2492 }
2493 if (!errs.empty()) {
2494 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2495 "%d:%s",
2496 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002497 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002498 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002499 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002500 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002501
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002502 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2503 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002505 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002506 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002507 if (foregroundWindowHandle) {
2508 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002509 for (InputTarget& target : targets) {
2510 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2511 sp<WindowInfoHandle> targetWindow =
2512 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2513 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2514 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002515 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516 }
2517 }
2518 }
2519 }
2520
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002521 // Success! Output targets from the touch state.
2522 tempTouchState.clearWindowsWithoutPointers();
2523 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002524 if (touchedWindow.pointerIds.isEmpty() &&
2525 !touchedWindow.hasHoveringPointers(entry.deviceId)) {
2526 // Windows with hovering pointers are getting persisted inside TouchState.
2527 // Do not send this event to those windows.
2528 continue;
2529 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002530 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2531 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2532 targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002533 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002534
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002535 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002536 // Drop the outside or hover touch windows since we will not care about them
2537 // in the next iteration.
2538 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002539
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002541 if (switchedDevice) {
2542 if (DEBUG_FOCUS) {
2543 ALOGD("Conflicting pointer actions: Switched to a different device.");
2544 }
2545 *outConflictingPointerActions = true;
2546 }
2547
2548 if (isHoverAction) {
2549 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002550 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002551 ALOGD_IF(DEBUG_FOCUS,
2552 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002553 *outConflictingPointerActions = true;
2554 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002555 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2556 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2557 tempTouchState.deviceId = entry.deviceId;
2558 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002559 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002560 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2561 // Pointer went up.
2562 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
2563 tempTouchState.clearWindowsWithoutPointers();
2564 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002565 // All pointers up or canceled.
2566 tempTouchState.reset();
2567 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2568 // First pointer went down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002569 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002570 ALOGD("Conflicting pointer actions: Down received while already down.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002571 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002572 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002573 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2574 // One pointer went up.
2575 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2576 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002577
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002578 for (size_t i = 0; i < tempTouchState.windows.size();) {
2579 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2580 touchedWindow.pointerIds.clearBit(pointerId);
2581 if (touchedWindow.pointerIds.isEmpty()) {
2582 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2583 continue;
2584 }
2585 i += 1;
2586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587 }
2588
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002589 // Save changes unless the action was scroll in which case the temporary touch
2590 // state was only valid for this one action.
2591 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002592 if (displayId >= 0) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002593 mTouchStatesByDisplay[displayId] = tempTouchState;
2594 } else {
2595 mTouchStatesByDisplay.erase(displayId);
2596 }
2597 }
2598
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002599 if (tempTouchState.windows.empty()) {
2600 mTouchStatesByDisplay.erase(displayId);
2601 }
2602
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002603 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002604}
2605
arthurhung6d4bed92021-03-17 11:59:33 +08002606void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002607 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2608 // have an explicit reason to support it.
2609 constexpr bool isStylus = false;
2610
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002611 auto [dropWindow, _] =
2612 findTouchedWindowAtLocked(displayId, x, y, isStylus, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002613 if (dropWindow) {
2614 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002615 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002616 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002617 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002618 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002619 }
2620 mDragState.reset();
2621}
2622
2623void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002624 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002625 return;
2626 }
2627
arthurhung6d4bed92021-03-17 11:59:33 +08002628 if (!mDragState->isStartDrag) {
2629 mDragState->isStartDrag = true;
2630 mDragState->isStylusButtonDownAtStart =
2631 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2632 }
2633
Arthur Hung54745652022-04-20 07:17:41 +00002634 // Find the pointer index by id.
2635 int32_t pointerIndex = 0;
2636 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2637 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2638 if (pointerProperties.id == mDragState->pointerId) {
2639 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002640 }
Arthur Hung54745652022-04-20 07:17:41 +00002641 }
arthurhung6d4bed92021-03-17 11:59:33 +08002642
Arthur Hung54745652022-04-20 07:17:41 +00002643 if (uint32_t(pointerIndex) == entry.pointerCount) {
2644 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002645 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002646 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002647 return;
2648 }
2649
2650 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2651 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2652 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2653
2654 switch (maskedAction) {
2655 case AMOTION_EVENT_ACTION_MOVE: {
2656 // Handle the special case : stylus button no longer pressed.
2657 bool isStylusButtonDown =
2658 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2659 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2660 finishDragAndDrop(entry.displayId, x, y);
2661 return;
2662 }
2663
2664 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2665 // until we have an explicit reason to support it.
2666 constexpr bool isStylus = false;
2667
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002668 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2669 true /*ignoreDragWindow*/);
Arthur Hung54745652022-04-20 07:17:41 +00002670 // enqueue drag exit if needed.
2671 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2672 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2673 if (mDragState->dragHoverWindowHandle != nullptr) {
2674 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2675 y);
2676 }
2677 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2678 }
2679 // enqueue drag location if needed.
2680 if (hoverWindowHandle != nullptr) {
2681 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2682 }
2683 break;
2684 }
2685
2686 case AMOTION_EVENT_ACTION_POINTER_UP:
2687 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2688 break;
2689 }
2690 // The drag pointer is up.
2691 [[fallthrough]];
2692 case AMOTION_EVENT_ACTION_UP:
2693 finishDragAndDrop(entry.displayId, x, y);
2694 break;
2695 case AMOTION_EVENT_ACTION_CANCEL: {
2696 ALOGD("Receiving cancel when drag and drop.");
2697 sendDropWindowCommandLocked(nullptr, 0, 0);
2698 mDragState.reset();
2699 break;
2700 }
arthurhungb89ccb02020-12-30 16:19:01 +08002701 }
2702}
2703
chaviw98318de2021-05-19 16:45:23 -05002704void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002705 ftl::Flags<InputTarget::Flags> targetFlags,
2706 BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002707 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002708 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002709 std::vector<InputTarget>::iterator it =
2710 std::find_if(inputTargets.begin(), inputTargets.end(),
2711 [&windowHandle](const InputTarget& inputTarget) {
2712 return inputTarget.inputChannel->getConnectionToken() ==
2713 windowHandle->getToken();
2714 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002715
chaviw98318de2021-05-19 16:45:23 -05002716 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002717
2718 if (it == inputTargets.end()) {
2719 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002720 std::shared_ptr<InputChannel> inputChannel =
2721 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002722 if (inputChannel == nullptr) {
2723 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2724 return;
2725 }
2726 inputTarget.inputChannel = inputChannel;
2727 inputTarget.flags = targetFlags;
2728 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002729 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002730 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2731 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002732 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002733 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002734 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002735 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002736 inputTargets.push_back(inputTarget);
2737 it = inputTargets.end() - 1;
2738 }
2739
2740 ALOG_ASSERT(it->flags == targetFlags);
2741 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2742
chaviw1ff3d1e2020-07-01 15:53:47 -07002743 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744}
2745
Michael Wright3dd60e22019-03-27 22:06:44 +00002746void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002747 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002748 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2749 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002750
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002751 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2752 InputTarget target;
2753 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002754 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002755 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2756 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002757 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2758 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002759 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002760 target.setDefaultPointerTransform(target.displayTransform);
2761 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762 }
2763}
2764
Robert Carrc9bf1d32020-04-13 17:21:08 -07002765/**
2766 * Indicate whether one window handle should be considered as obscuring
2767 * another window handle. We only check a few preconditions. Actually
2768 * checking the bounds is left to the caller.
2769 */
chaviw98318de2021-05-19 16:45:23 -05002770static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2771 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002772 // Compare by token so cloned layers aren't counted
2773 if (haveSameToken(windowHandle, otherHandle)) {
2774 return false;
2775 }
2776 auto info = windowHandle->getInfo();
2777 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002778 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002779 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002780 } else if (otherInfo->alpha == 0 &&
2781 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002782 // Those act as if they were invisible, so we don't need to flag them.
2783 // We do want to potentially flag touchable windows even if they have 0
2784 // opacity, since they can consume touches and alter the effects of the
2785 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002786 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002787 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2788 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002789 } else if (info->ownerUid == otherInfo->ownerUid) {
2790 // If ownerUid is the same we don't generate occlusion events as there
2791 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002792 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002793 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002794 return false;
2795 } else if (otherInfo->displayId != info->displayId) {
2796 return false;
2797 }
2798 return true;
2799}
2800
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002801/**
2802 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2803 * untrusted, one should check:
2804 *
2805 * 1. If result.hasBlockingOcclusion is true.
2806 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2807 * BLOCK_UNTRUSTED.
2808 *
2809 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2810 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2811 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2812 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2813 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2814 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2815 *
2816 * If neither of those is true, then it means the touch can be allowed.
2817 */
2818InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002819 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2820 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002821 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002822 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002823 TouchOcclusionInfo info;
2824 info.hasBlockingOcclusion = false;
2825 info.obscuringOpacity = 0;
2826 info.obscuringUid = -1;
2827 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002828 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002829 if (windowHandle == otherHandle) {
2830 break; // All future windows are below us. Exit early.
2831 }
chaviw98318de2021-05-19 16:45:23 -05002832 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002833 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2834 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002835 if (DEBUG_TOUCH_OCCLUSION) {
2836 info.debugInfo.push_back(
2837 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2838 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002839 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2840 // we perform the checks below to see if the touch can be propagated or not based on the
2841 // window's touch occlusion mode
2842 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2843 info.hasBlockingOcclusion = true;
2844 info.obscuringUid = otherInfo->ownerUid;
2845 info.obscuringPackage = otherInfo->packageName;
2846 break;
2847 }
2848 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2849 uint32_t uid = otherInfo->ownerUid;
2850 float opacity =
2851 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2852 // Given windows A and B:
2853 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2854 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2855 opacityByUid[uid] = opacity;
2856 if (opacity > info.obscuringOpacity) {
2857 info.obscuringOpacity = opacity;
2858 info.obscuringUid = uid;
2859 info.obscuringPackage = otherInfo->packageName;
2860 }
2861 }
2862 }
2863 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002864 if (DEBUG_TOUCH_OCCLUSION) {
2865 info.debugInfo.push_back(
2866 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2867 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002868 return info;
2869}
2870
chaviw98318de2021-05-19 16:45:23 -05002871std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002872 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002873 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2874 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2875 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2876 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002877 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2878 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2879 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2880 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2881 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002882 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002883 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002884}
2885
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002886bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2887 if (occlusionInfo.hasBlockingOcclusion) {
2888 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2889 occlusionInfo.obscuringUid);
2890 return false;
2891 }
2892 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2893 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2894 "%.2f, maximum allowed = %.2f)",
2895 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2896 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2897 return false;
2898 }
2899 return true;
2900}
2901
chaviw98318de2021-05-19 16:45:23 -05002902bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002903 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002904 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002905 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2906 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002907 if (windowHandle == otherHandle) {
2908 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002909 }
chaviw98318de2021-05-19 16:45:23 -05002910 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002911 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002912 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002913 return true;
2914 }
2915 }
2916 return false;
2917}
2918
chaviw98318de2021-05-19 16:45:23 -05002919bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002920 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002921 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2922 const WindowInfo* windowInfo = windowHandle->getInfo();
2923 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002924 if (windowHandle == otherHandle) {
2925 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002926 }
chaviw98318de2021-05-19 16:45:23 -05002927 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002928 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002929 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002930 return true;
2931 }
2932 }
2933 return false;
2934}
2935
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002936std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002937 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002938 if (applicationHandle != nullptr) {
2939 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002940 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002941 } else {
2942 return applicationHandle->getName();
2943 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002944 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002945 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002946 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002947 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002948 }
2949}
2950
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002951void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002952 if (!isUserActivityEvent(eventEntry)) {
2953 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002954 return;
2955 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002956 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002957 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002958 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002959 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002960 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002961 if (DEBUG_DISPATCH_CYCLE) {
2962 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2963 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002964 return;
2965 }
2966 }
2967
2968 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002969 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002970 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002971 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2972 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002973 return;
2974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002975
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002976 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002977 eventType = USER_ACTIVITY_EVENT_TOUCH;
2978 }
2979 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002980 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002981 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002982 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2983 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002984 return;
2985 }
2986 eventType = USER_ACTIVITY_EVENT_BUTTON;
2987 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002988 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002989 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002990 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002991 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002992 break;
2993 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002994 }
2995
Prabir Pradhancef936d2021-07-21 16:17:52 +00002996 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2997 REQUIRES(mLock) {
2998 scoped_unlock unlock(mLock);
2999 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
3000 };
3001 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003002}
3003
3004void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003005 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003006 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003007 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003008 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003009 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003010 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003011 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003012 ATRACE_NAME(message.c_str());
3013 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003014 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003015 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003016 "globalScaleFactor=%f, pointerIds=0x%x %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003017 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003018 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
3019 inputTarget.getPointerInfoString().c_str());
3020 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003021
3022 // Skip this event if the connection status is not normal.
3023 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003024 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003025 if (DEBUG_DISPATCH_CYCLE) {
3026 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003027 connection->getInputChannelName().c_str(),
3028 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003029 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003030 return;
3031 }
3032
3033 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003034 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003035 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003036 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003037 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003039 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003040 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003041 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
3042 "Splitting motion events requires a down time to be set for the "
3043 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003044 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003045 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3046 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047 if (!splitMotionEntry) {
3048 return; // split event was dropped
3049 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003050 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3051 std::string reason = std::string("reason=pointer cancel on split window");
3052 android_log_event_list(LOGTAG_INPUT_CANCEL)
3053 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3054 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003055 if (DEBUG_FOCUS) {
3056 ALOGD("channel '%s' ~ Split motion event.",
3057 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003058 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003059 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003060 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3061 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062 return;
3063 }
3064 }
3065
3066 // Not splitting. Enqueue dispatch entries for the event as is.
3067 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3068}
3069
3070void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003071 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003072 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003073 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003074 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003075 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003076 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003077 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003078 ATRACE_NAME(message.c_str());
3079 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003080 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3081 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003082
hongzuo liu95785e22022-09-06 02:51:35 +00003083 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084
3085 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003086 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003087 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003088 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003089 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003090 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003091 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003092 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003093 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003094 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003095 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003096 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003097 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098
3099 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003100 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101 startDispatchCycleLocked(currentTime, connection);
3102 }
3103}
3104
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003105void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003106 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003107 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003108 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003109 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003110 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3111 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003112 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003113 ATRACE_NAME(message.c_str());
3114 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003115 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3116 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117 return;
3118 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003119
3120 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3121 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003122
3123 // This is a new event.
3124 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003125 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003126 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003128 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3129 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003130 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003131 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003132 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003133 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003134 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003135 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003136 dispatchEntry->resolvedAction = keyEntry.action;
3137 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003139 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3140 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003141 if (DEBUG_DISPATCH_CYCLE) {
3142 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3143 "event",
3144 connection->getInputChannelName().c_str());
3145 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003146 return; // skip the inconsistent event
3147 }
3148 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003149 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003151 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003152 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003153 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3154 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3155 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3156 static_cast<int32_t>(IdGenerator::Source::OTHER);
3157 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003158 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003159 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003160 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003161 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003162 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003163 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003164 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003165 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003166 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003167 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3168 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003169 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003170 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003171 }
3172 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003173 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3174 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003175 if (DEBUG_DISPATCH_CYCLE) {
3176 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3177 "enter event",
3178 connection->getInputChannelName().c_str());
3179 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003180 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3181 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003182 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3183 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003185 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003186 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3187 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3188 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003189 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003190 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3191 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003192 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003193 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3194 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003195
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003196 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3197 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003198 if (DEBUG_DISPATCH_CYCLE) {
3199 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3200 "event",
3201 connection->getInputChannelName().c_str());
3202 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003203 return; // skip the inconsistent event
3204 }
3205
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003206 dispatchEntry->resolvedEventId =
3207 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3208 ? mIdGenerator.nextId()
3209 : motionEntry.id;
3210 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3211 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3212 ") to MotionEvent(id=0x%" PRIx32 ").",
3213 motionEntry.id, dispatchEntry->resolvedEventId);
3214 ATRACE_NAME(message.c_str());
3215 }
3216
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003217 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3218 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3219 // Skip reporting pointer down outside focus to the policy.
3220 break;
3221 }
3222
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003223 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003224 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003225
3226 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003228 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003229 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003230 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3231 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003232 break;
3233 }
Chris Yef59a2f42020-10-16 12:55:26 -07003234 case EventEntry::Type::SENSOR: {
3235 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3236 break;
3237 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003238 case EventEntry::Type::CONFIGURATION_CHANGED:
3239 case EventEntry::Type::DEVICE_RESET: {
3240 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003241 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003242 break;
3243 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244 }
3245
3246 // Remember that we are waiting for this dispatch to complete.
3247 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003248 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249 }
3250
3251 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003252 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003253 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003254}
3255
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003256/**
3257 * This function is purely for debugging. It helps us understand where the user interaction
3258 * was taking place. For example, if user is touching launcher, we will see a log that user
3259 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3260 * We will see both launcher and wallpaper in that list.
3261 * Once the interaction with a particular set of connections starts, no new logs will be printed
3262 * until the set of interacted connections changes.
3263 *
3264 * The following items are skipped, to reduce the logspam:
3265 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3266 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3267 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3268 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3269 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003270 */
3271void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3272 const std::vector<InputTarget>& targets) {
3273 // Skip ACTION_UP events, and all events other than keys and motions
3274 if (entry.type == EventEntry::Type::KEY) {
3275 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3276 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3277 return;
3278 }
3279 } else if (entry.type == EventEntry::Type::MOTION) {
3280 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3281 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3282 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3283 return;
3284 }
3285 } else {
3286 return; // Not a key or a motion
3287 }
3288
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003289 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003290 std::vector<sp<Connection>> newConnections;
3291 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003292 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003293 continue; // Skip windows that receive ACTION_OUTSIDE
3294 }
3295
3296 sp<IBinder> token = target.inputChannel->getConnectionToken();
3297 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003298 if (connection == nullptr) {
3299 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003300 }
3301 newConnectionTokens.insert(std::move(token));
3302 newConnections.emplace_back(connection);
3303 }
3304 if (newConnectionTokens == mInteractionConnectionTokens) {
3305 return; // no change
3306 }
3307 mInteractionConnectionTokens = newConnectionTokens;
3308
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003309 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003310 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003311 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003312 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003313 std::string message = "Interaction with: " + targetList;
3314 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003315 message += "<none>";
3316 }
3317 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3318}
3319
chaviwfd6d3512019-03-25 13:23:49 -07003320void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003321 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003322 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003323 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3324 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003325 return;
3326 }
3327
Vishnu Nairc519ff72021-01-21 08:23:08 -08003328 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003329 if (focusedToken == token) {
3330 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003331 return;
3332 }
3333
Prabir Pradhancef936d2021-07-21 16:17:52 +00003334 auto command = [this, token]() REQUIRES(mLock) {
3335 scoped_unlock unlock(mLock);
3336 mPolicy->onPointerDownOutsideFocus(token);
3337 };
3338 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003339}
3340
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003341status_t InputDispatcher::publishMotionEvent(Connection& connection,
3342 DispatchEntry& dispatchEntry) const {
3343 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3344 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3345
3346 PointerCoords scaledCoords[MAX_POINTERS];
3347 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3348
3349 // Set the X and Y offset and X and Y scale depending on the input source.
3350 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003351 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003352 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3353 if (globalScaleFactor != 1.0f) {
3354 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3355 scaledCoords[i] = motionEntry.pointerCoords[i];
3356 // Don't apply window scale here since we don't want scale to affect raw
3357 // coordinates. The scale will be sent back to the client and applied
3358 // later when requesting relative coordinates.
3359 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3360 1 /* windowYScale */);
3361 }
3362 usingCoords = scaledCoords;
3363 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003364 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003365 // We don't want the dispatch target to know the coordinates
3366 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3367 scaledCoords[i].clear();
3368 }
3369 usingCoords = scaledCoords;
3370 }
3371
3372 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3373
3374 // Publish the motion event.
3375 return connection.inputPublisher
3376 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3377 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3378 std::move(hmac), dispatchEntry.resolvedAction,
3379 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3380 motionEntry.edgeFlags, motionEntry.metaState,
3381 motionEntry.buttonState, motionEntry.classification,
3382 dispatchEntry.transform, motionEntry.xPrecision,
3383 motionEntry.yPrecision, motionEntry.xCursorPosition,
3384 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3385 motionEntry.downTime, motionEntry.eventTime,
3386 motionEntry.pointerCount, motionEntry.pointerProperties,
3387 usingCoords);
3388}
3389
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003391 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003392 if (ATRACE_ENABLED()) {
3393 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003394 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003395 ATRACE_NAME(message.c_str());
3396 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003397 if (DEBUG_DISPATCH_CYCLE) {
3398 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3399 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003401 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003402 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003403 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003404 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003405 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406
3407 // Publish the event.
3408 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003409 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3410 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003411 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003412 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3413 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003414 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3415 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3416 << connection->getInputChannelName();
3417 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003419 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003420 status = connection->inputPublisher
3421 .publishKeyEvent(dispatchEntry->seq,
3422 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3423 keyEntry.source, keyEntry.displayId,
3424 std::move(hmac), dispatchEntry->resolvedAction,
3425 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3426 keyEntry.scanCode, keyEntry.metaState,
3427 keyEntry.repeatCount, keyEntry.downTime,
3428 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003429 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430 }
3431
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003432 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003433 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3434 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3435 << connection->getInputChannelName();
3436 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003437 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003438 break;
3439 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003440
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003441 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003442 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003443 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003444 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003445 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003446 break;
3447 }
3448
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003449 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3450 const TouchModeEntry& touchModeEntry =
3451 static_cast<const TouchModeEntry&>(eventEntry);
3452 status = connection->inputPublisher
3453 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3454 touchModeEntry.inTouchMode);
3455
3456 break;
3457 }
3458
Prabir Pradhan99987712020-11-10 18:43:05 -08003459 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3460 const auto& captureEntry =
3461 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3462 status = connection->inputPublisher
3463 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003464 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003465 break;
3466 }
3467
arthurhungb89ccb02020-12-30 16:19:01 +08003468 case EventEntry::Type::DRAG: {
3469 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3470 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3471 dragEntry.id, dragEntry.x,
3472 dragEntry.y,
3473 dragEntry.isExiting);
3474 break;
3475 }
3476
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003477 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003478 case EventEntry::Type::DEVICE_RESET:
3479 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003480 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003481 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003482 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003484 }
3485
3486 // Check the result.
3487 if (status) {
3488 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003489 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003491 "This is unexpected because the wait queue is empty, so the pipe "
3492 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003493 "event to it, status=%s(%d)",
3494 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3495 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3497 } else {
3498 // Pipe is full and we are waiting for the app to finish process some events
3499 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003500 if (DEBUG_DISPATCH_CYCLE) {
3501 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3502 "waiting for the application to catch up",
3503 connection->getInputChannelName().c_str());
3504 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505 }
3506 } else {
3507 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003508 "status=%s(%d)",
3509 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3510 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3512 }
3513 return;
3514 }
3515
3516 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003517 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3518 connection->outboundQueue.end(),
3519 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003520 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003521 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003522 if (connection->responsive) {
3523 mAnrTracker.insert(dispatchEntry->timeoutTime,
3524 connection->inputChannel->getConnectionToken());
3525 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003526 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 }
3528}
3529
chaviw09c8d2d2020-08-24 15:48:26 -07003530std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3531 size_t size;
3532 switch (event.type) {
3533 case VerifiedInputEvent::Type::KEY: {
3534 size = sizeof(VerifiedKeyEvent);
3535 break;
3536 }
3537 case VerifiedInputEvent::Type::MOTION: {
3538 size = sizeof(VerifiedMotionEvent);
3539 break;
3540 }
3541 }
3542 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3543 return mHmacKeyManager.sign(start, size);
3544}
3545
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003546const std::array<uint8_t, 32> InputDispatcher::getSignature(
3547 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003548 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3549 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003550 // Only sign events up and down events as the purely move events
3551 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003552 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003553 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003554
3555 VerifiedMotionEvent verifiedEvent =
3556 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3557 verifiedEvent.actionMasked = actionMasked;
3558 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3559 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003560}
3561
3562const std::array<uint8_t, 32> InputDispatcher::getSignature(
3563 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3564 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3565 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3566 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003567 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003568}
3569
Michael Wrightd02c5b62014-02-10 15:10:22 -08003570void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003571 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003572 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003573 if (DEBUG_DISPATCH_CYCLE) {
3574 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3575 connection->getInputChannelName().c_str(), seq, toString(handled));
3576 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003578 if (connection->status == Connection::Status::BROKEN ||
3579 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580 return;
3581 }
3582
3583 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003584 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3585 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3586 };
3587 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588}
3589
3590void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003591 const sp<Connection>& connection,
3592 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003593 if (DEBUG_DISPATCH_CYCLE) {
3594 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3595 connection->getInputChannelName().c_str(), toString(notify));
3596 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597
3598 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003599 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003600 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003601 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003602 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603
3604 // The connection appears to be unrecoverably broken.
3605 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003606 if (connection->status == Connection::Status::NORMAL) {
3607 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608
3609 if (notify) {
3610 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003611 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3612 connection->getInputChannelName().c_str());
3613
3614 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003615 scoped_unlock unlock(mLock);
3616 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3617 };
3618 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003619 }
3620 }
3621}
3622
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003623void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3624 while (!queue.empty()) {
3625 DispatchEntry* dispatchEntry = queue.front();
3626 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003627 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003628 }
3629}
3630
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003631void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003633 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634 }
3635 delete dispatchEntry;
3636}
3637
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003638int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3639 std::scoped_lock _l(mLock);
3640 sp<Connection> connection = getConnectionLocked(connectionToken);
3641 if (connection == nullptr) {
3642 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3643 connectionToken.get(), events);
3644 return 0; // remove the callback
3645 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003647 bool notify;
3648 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3649 if (!(events & ALOOPER_EVENT_INPUT)) {
3650 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3651 "events=0x%x",
3652 connection->getInputChannelName().c_str(), events);
3653 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003654 }
3655
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003656 nsecs_t currentTime = now();
3657 bool gotOne = false;
3658 status_t status = OK;
3659 for (;;) {
3660 Result<InputPublisher::ConsumerResponse> result =
3661 connection->inputPublisher.receiveConsumerResponse();
3662 if (!result.ok()) {
3663 status = result.error().code();
3664 break;
3665 }
3666
3667 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3668 const InputPublisher::Finished& finish =
3669 std::get<InputPublisher::Finished>(*result);
3670 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3671 finish.consumeTime);
3672 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003673 if (shouldReportMetricsForConnection(*connection)) {
3674 const InputPublisher::Timeline& timeline =
3675 std::get<InputPublisher::Timeline>(*result);
3676 mLatencyTracker
3677 .trackGraphicsLatency(timeline.inputEventId,
3678 connection->inputChannel->getConnectionToken(),
3679 std::move(timeline.graphicsTimeline));
3680 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003681 }
3682 gotOne = true;
3683 }
3684 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003685 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003686 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687 return 1;
3688 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689 }
3690
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003691 notify = status != DEAD_OBJECT || !connection->monitor;
3692 if (notify) {
3693 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3694 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3695 status);
3696 }
3697 } else {
3698 // Monitor channels are never explicitly unregistered.
3699 // We do it automatically when the remote endpoint is closed so don't warn about them.
3700 const bool stillHaveWindowHandle =
3701 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3702 notify = !connection->monitor && stillHaveWindowHandle;
3703 if (notify) {
3704 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3705 connection->getInputChannelName().c_str(), events);
3706 }
3707 }
3708
3709 // Remove the channel.
3710 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3711 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003712}
3713
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003714void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003716 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003717 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003718 }
3719}
3720
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003721void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003722 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003723 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003724 for (const Monitor& monitor : monitors) {
3725 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003726 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003727 }
3728}
3729
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003731 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003732 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003733 if (connection == nullptr) {
3734 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003735 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003736
3737 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003738}
3739
3740void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3741 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003742 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003743 return;
3744 }
3745
3746 nsecs_t currentTime = now();
3747
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003748 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003749 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003750
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003751 if (cancelationEvents.empty()) {
3752 return;
3753 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003754 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3755 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3756 "with reality: %s, mode=%d.",
3757 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3758 options.mode);
3759 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003760
Arthur Hungb3307ee2021-10-14 10:57:37 +00003761 std::string reason = std::string("reason=").append(options.reason);
3762 android_log_event_list(LOGTAG_INPUT_CANCEL)
3763 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3764
Svet Ganov5d3bc372020-01-26 23:11:07 -08003765 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003766 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003767 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3768 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003769 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003770 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003771 target.globalScaleFactor = windowInfo->globalScaleFactor;
3772 }
3773 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003774 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003775
hongzuo liu95785e22022-09-06 02:51:35 +00003776 const bool wasEmpty = connection->outboundQueue.empty();
3777
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003778 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003779 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003780 switch (cancelationEventEntry->type) {
3781 case EventEntry::Type::KEY: {
3782 logOutboundKeyDetails("cancel - ",
3783 static_cast<const KeyEntry&>(*cancelationEventEntry));
3784 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003786 case EventEntry::Type::MOTION: {
3787 logOutboundMotionDetails("cancel - ",
3788 static_cast<const MotionEntry&>(*cancelationEventEntry));
3789 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003791 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003792 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003793 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3794 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003795 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003796 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003797 break;
3798 }
3799 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003800 case EventEntry::Type::DEVICE_RESET:
3801 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003802 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003803 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003804 break;
3805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806 }
3807
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003808 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003809 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003811
hongzuo liu95785e22022-09-06 02:51:35 +00003812 // If the outbound queue was previously empty, start the dispatch cycle going.
3813 if (wasEmpty && !connection->outboundQueue.empty()) {
3814 startDispatchCycleLocked(currentTime, connection);
3815 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003816}
3817
Svet Ganov5d3bc372020-01-26 23:11:07 -08003818void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Arthur Hungc539dbb2022-12-08 07:45:36 +00003819 const nsecs_t downTime, const sp<Connection>& connection,
3820 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003821 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003822 return;
3823 }
3824
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003825 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003826 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003827
3828 if (downEvents.empty()) {
3829 return;
3830 }
3831
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003832 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003833 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3834 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003835 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003836
3837 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003838 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003839 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3840 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003841 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003842 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003843 target.globalScaleFactor = windowInfo->globalScaleFactor;
3844 }
3845 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00003846 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003847
hongzuo liu95785e22022-09-06 02:51:35 +00003848 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003849 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003850 switch (downEventEntry->type) {
3851 case EventEntry::Type::MOTION: {
3852 logOutboundMotionDetails("down - ",
3853 static_cast<const MotionEntry&>(*downEventEntry));
3854 break;
3855 }
3856
3857 case EventEntry::Type::KEY:
3858 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003859 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003860 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003861 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003862 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003863 case EventEntry::Type::SENSOR:
3864 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003865 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003866 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003867 break;
3868 }
3869 }
3870
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003871 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003872 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003873 }
3874
hongzuo liu95785e22022-09-06 02:51:35 +00003875 // If the outbound queue was previously empty, start the dispatch cycle going.
3876 if (wasEmpty && !connection->outboundQueue.empty()) {
3877 startDispatchCycleLocked(downTime, connection);
3878 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003879}
3880
Arthur Hungc539dbb2022-12-08 07:45:36 +00003881void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
3882 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
3883 if (windowHandle != nullptr) {
3884 sp<Connection> wallpaperConnection = getConnectionLocked(windowHandle->getToken());
3885 if (wallpaperConnection != nullptr) {
3886 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
3887 }
3888 }
3889}
3890
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003891std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003892 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893 ALOG_ASSERT(pointerIds.value != 0);
3894
3895 uint32_t splitPointerIndexMap[MAX_POINTERS];
3896 PointerProperties splitPointerProperties[MAX_POINTERS];
3897 PointerCoords splitPointerCoords[MAX_POINTERS];
3898
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003899 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900 uint32_t splitPointerCount = 0;
3901
3902 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003903 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003905 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906 uint32_t pointerId = uint32_t(pointerProperties.id);
3907 if (pointerIds.hasBit(pointerId)) {
3908 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3909 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3910 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003911 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912 splitPointerCount += 1;
3913 }
3914 }
3915
3916 if (splitPointerCount != pointerIds.count()) {
3917 // This is bad. We are missing some of the pointers that we expected to deliver.
3918 // Most likely this indicates that we received an ACTION_MOVE events that has
3919 // different pointer ids than we expected based on the previous ACTION_DOWN
3920 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3921 // in this way.
3922 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003923 "we expected there to be %d pointers. This probably means we received "
3924 "a broken sequence of pointer ids from the input device.",
3925 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003926 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927 }
3928
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003929 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003930 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003931 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3932 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003933 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3934 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003935 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936 uint32_t pointerId = uint32_t(pointerProperties.id);
3937 if (pointerIds.hasBit(pointerId)) {
3938 if (pointerIds.count() == 1) {
3939 // The first/last pointer went down/up.
3940 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003941 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003942 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3943 ? AMOTION_EVENT_ACTION_CANCEL
3944 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003945 } else {
3946 // A secondary pointer went down/up.
3947 uint32_t splitPointerIndex = 0;
3948 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3949 splitPointerIndex += 1;
3950 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003951 action = maskedAction |
3952 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953 }
3954 } else {
3955 // An unrelated pointer changed.
3956 action = AMOTION_EVENT_ACTION_MOVE;
3957 }
3958 }
3959
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003960 if (action == AMOTION_EVENT_ACTION_DOWN) {
3961 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3962 "Split motion event has mismatching downTime and eventTime for "
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08003963 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
3964 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003965 }
3966
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003967 int32_t newId = mIdGenerator.nextId();
3968 if (ATRACE_ENABLED()) {
3969 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3970 ") to MotionEvent(id=0x%" PRIx32 ").",
3971 originalMotionEntry.id, newId);
3972 ATRACE_NAME(message.c_str());
3973 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003974 std::unique_ptr<MotionEntry> splitMotionEntry =
3975 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3976 originalMotionEntry.deviceId, originalMotionEntry.source,
3977 originalMotionEntry.displayId,
3978 originalMotionEntry.policyFlags, action,
3979 originalMotionEntry.actionButton,
3980 originalMotionEntry.flags, originalMotionEntry.metaState,
3981 originalMotionEntry.buttonState,
3982 originalMotionEntry.classification,
3983 originalMotionEntry.edgeFlags,
3984 originalMotionEntry.xPrecision,
3985 originalMotionEntry.yPrecision,
3986 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003987 originalMotionEntry.yCursorPosition, splitDownTime,
3988 splitPointerCount, splitPointerProperties,
3989 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003991 if (originalMotionEntry.injectionState) {
3992 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993 splitMotionEntry->injectionState->refCount += 1;
3994 }
3995
3996 return splitMotionEntry;
3997}
3998
3999void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004000 if (DEBUG_INBOUND_EVENT_DETAILS) {
4001 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
4002 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004003
Antonio Kantekf16f2832021-09-28 04:39:20 +00004004 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004006 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004007
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004008 std::unique_ptr<ConfigurationChangedEntry> newEntry =
4009 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
4010 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004011 } // release lock
4012
4013 if (needWake) {
4014 mLooper->wake();
4015 }
4016}
4017
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004018/**
4019 * If one of the meta shortcuts is detected, process them here:
4020 * Meta + Backspace -> generate BACK
4021 * Meta + Enter -> generate HOME
4022 * This will potentially overwrite keyCode and metaState.
4023 */
4024void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004025 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004026 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4027 int32_t newKeyCode = AKEYCODE_UNKNOWN;
4028 if (keyCode == AKEYCODE_DEL) {
4029 newKeyCode = AKEYCODE_BACK;
4030 } else if (keyCode == AKEYCODE_ENTER) {
4031 newKeyCode = AKEYCODE_HOME;
4032 }
4033 if (newKeyCode != AKEYCODE_UNKNOWN) {
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 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004037 keyCode = newKeyCode;
4038 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4039 }
4040 } else if (action == AKEY_EVENT_ACTION_UP) {
4041 // In order to maintain a consistent stream of up and down events, check to see if the key
4042 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4043 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004044 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004045 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004046 auto replacementIt = mReplacedKeys.find(replacement);
4047 if (replacementIt != mReplacedKeys.end()) {
4048 keyCode = replacementIt->second;
4049 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004050 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4051 }
4052 }
4053}
4054
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004056 if (DEBUG_INBOUND_EVENT_DETAILS) {
4057 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
4058 "policyFlags=0x%x, action=0x%x, "
4059 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
4060 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
4061 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
4062 args->downTime);
4063 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064 if (!validateKeyEvent(args->action)) {
4065 return;
4066 }
4067
4068 uint32_t policyFlags = args->policyFlags;
4069 int32_t flags = args->flags;
4070 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004071 // InputDispatcher tracks and generates key repeats on behalf of
4072 // whatever notifies it, so repeatCount should always be set to 0
4073 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4075 policyFlags |= POLICY_FLAG_VIRTUAL;
4076 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4077 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004078 if (policyFlags & POLICY_FLAG_FUNCTION) {
4079 metaState |= AMETA_FUNCTION_ON;
4080 }
4081
4082 policyFlags |= POLICY_FLAG_TRUSTED;
4083
Michael Wright78f24442014-08-06 15:55:28 -07004084 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004085 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004086
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004088 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08004089 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
4090 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091
Michael Wright2b3c3302018-03-02 17:19:13 +00004092 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004093 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004094 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4095 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004096 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004097 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098
Antonio Kantekf16f2832021-09-28 04:39:20 +00004099 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100 { // acquire lock
4101 mLock.lock();
4102
4103 if (shouldSendKeyToInputFilterLocked(args)) {
4104 mLock.unlock();
4105
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004106 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4108 return; // event was consumed by the filter
4109 }
4110
4111 mLock.lock();
4112 }
4113
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004114 std::unique_ptr<KeyEntry> newEntry =
4115 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4116 args->displayId, policyFlags, args->action, flags,
4117 keyCode, args->scanCode, metaState, repeatCount,
4118 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004120 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004121 mLock.unlock();
4122 } // release lock
4123
4124 if (needWake) {
4125 mLooper->wake();
4126 }
4127}
4128
4129bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4130 return mInputFilterEnabled;
4131}
4132
4133void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004134 if (DEBUG_INBOUND_EVENT_DETAILS) {
4135 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4136 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004137 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004138 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4139 "yCursorPosition=%f, downTime=%" PRId64,
4140 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004141 args->policyFlags, MotionEvent::actionToString(args->action).c_str(),
4142 args->actionButton, args->flags, args->metaState, args->buttonState, args->edgeFlags,
4143 args->xPrecision, args->yPrecision, args->xCursorPosition, args->yCursorPosition,
4144 args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004145 for (uint32_t i = 0; i < args->pointerCount; i++) {
4146 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4147 "x=%f, y=%f, pressure=%f, size=%f, "
4148 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4149 "orientation=%f",
4150 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4151 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4152 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4153 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4154 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4155 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4156 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4157 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4158 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4159 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4160 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -08004162 LOG_ALWAYS_FATAL_IF(!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4163 args->pointerProperties),
4164 "Invalid event: %s", args->dump().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165
4166 uint32_t policyFlags = args->policyFlags;
4167 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004168
4169 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004170 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004171 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4172 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004173 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004174 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175
Antonio Kantekf16f2832021-09-28 04:39:20 +00004176 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004177 { // acquire lock
4178 mLock.lock();
4179
4180 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004181 ui::Transform displayTransform;
4182 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4183 displayTransform = it->second.transform;
4184 }
4185
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 mLock.unlock();
4187
4188 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004189 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4190 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004191 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004192 displayTransform, args->xPrecision, args->yPrecision,
4193 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004194 args->downTime, args->eventTime, args->pointerCount,
4195 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196
4197 policyFlags |= POLICY_FLAG_FILTERED;
4198 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4199 return; // event was consumed by the filter
4200 }
4201
4202 mLock.lock();
4203 }
4204
4205 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004206 std::unique_ptr<MotionEntry> newEntry =
4207 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4208 args->source, args->displayId, policyFlags,
4209 args->action, args->actionButton, args->flags,
4210 args->metaState, args->buttonState,
4211 args->classification, args->edgeFlags,
4212 args->xPrecision, args->yPrecision,
4213 args->xCursorPosition, args->yCursorPosition,
4214 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004215 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004216
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004217 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4218 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4219 !mInputFilterEnabled) {
4220 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4221 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4222 }
4223
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004224 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225 mLock.unlock();
4226 } // release lock
4227
4228 if (needWake) {
4229 mLooper->wake();
4230 }
4231}
4232
Chris Yef59a2f42020-10-16 12:55:26 -07004233void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004234 if (DEBUG_INBOUND_EVENT_DETAILS) {
4235 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4236 " sensorType=%s",
4237 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004238 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004239 }
Chris Yef59a2f42020-10-16 12:55:26 -07004240
Antonio Kantekf16f2832021-09-28 04:39:20 +00004241 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004242 { // acquire lock
4243 mLock.lock();
4244
4245 // Just enqueue a new sensor event.
4246 std::unique_ptr<SensorEntry> newEntry =
4247 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4248 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4249 args->sensorType, args->accuracy,
4250 args->accuracyChanged, args->values);
4251
4252 needWake = enqueueInboundEventLocked(std::move(newEntry));
4253 mLock.unlock();
4254 } // release lock
4255
4256 if (needWake) {
4257 mLooper->wake();
4258 }
4259}
4260
Chris Yefb552902021-02-03 17:18:37 -08004261void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004262 if (DEBUG_INBOUND_EVENT_DETAILS) {
4263 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4264 args->deviceId, args->isOn);
4265 }
Chris Yefb552902021-02-03 17:18:37 -08004266 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4267}
4268
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004270 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271}
4272
4273void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004274 if (DEBUG_INBOUND_EVENT_DETAILS) {
4275 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4276 "switchMask=0x%08x",
4277 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4278 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279
4280 uint32_t policyFlags = args->policyFlags;
4281 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004282 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283}
4284
4285void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004286 if (DEBUG_INBOUND_EVENT_DETAILS) {
4287 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4288 args->deviceId);
4289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290
Antonio Kantekf16f2832021-09-28 04:39:20 +00004291 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004292 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004293 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004295 std::unique_ptr<DeviceResetEntry> newEntry =
4296 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4297 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298 } // release lock
4299
4300 if (needWake) {
4301 mLooper->wake();
4302 }
4303}
4304
Prabir Pradhan7e186182020-11-10 13:56:45 -08004305void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004306 if (DEBUG_INBOUND_EVENT_DETAILS) {
4307 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004308 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004309 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004310
Antonio Kantekf16f2832021-09-28 04:39:20 +00004311 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004312 { // acquire lock
4313 std::scoped_lock _l(mLock);
4314 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004315 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004316 needWake = enqueueInboundEventLocked(std::move(entry));
4317 } // release lock
4318
4319 if (needWake) {
4320 mLooper->wake();
4321 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004322}
4323
Prabir Pradhan5735a322022-04-11 17:23:34 +00004324InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4325 std::optional<int32_t> targetUid,
4326 InputEventInjectionSync syncMode,
4327 std::chrono::milliseconds timeout,
4328 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004329 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004330 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4331 "policyFlags=0x%08x",
4332 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4333 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004334 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004335 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336
Prabir Pradhan5735a322022-04-11 17:23:34 +00004337 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004339 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004340 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4341 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4342 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4343 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4344 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004345 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004346 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004347 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004348 }
4349
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004350 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004352 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004353 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4354 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004355 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004356 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004357 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004359 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004360 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4361 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4362 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004363 int32_t keyCode = incomingKey.getKeyCode();
4364 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004365 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004366 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004367 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004368 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004369 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4370 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4371 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004373 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4374 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004375 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004376
4377 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4378 android::base::Timer t;
4379 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4380 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4381 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4382 std::to_string(t.duration().count()).c_str());
4383 }
4384 }
4385
4386 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004387 std::unique_ptr<KeyEntry> injectedEntry =
4388 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004389 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004390 incomingKey.getDisplayId(), policyFlags, action,
4391 flags, keyCode, incomingKey.getScanCode(), metaState,
4392 incomingKey.getRepeatCount(),
4393 incomingKey.getDownTime());
4394 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004395 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396 }
4397
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004398 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004399 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004400 const int32_t action = motionEvent.getAction();
4401 const bool isPointerEvent =
4402 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4403 // If a pointer event has no displayId specified, inject it to the default display.
4404 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4405 ? ADISPLAY_ID_DEFAULT
4406 : event->getDisplayId();
4407 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004408 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004409 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004410 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004411 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004412 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004413 }
4414
4415 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004416 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004417 android::base::Timer t;
4418 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4419 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4420 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4421 std::to_string(t.duration().count()).c_str());
4422 }
4423 }
4424
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004425 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4426 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4427 }
4428
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004429 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004430 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4431 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004432 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004433 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4434 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004435 displayId, policyFlags, action, actionButton,
4436 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004437 motionEvent.getButtonState(),
4438 motionEvent.getClassification(),
4439 motionEvent.getEdgeFlags(),
4440 motionEvent.getXPrecision(),
4441 motionEvent.getYPrecision(),
4442 motionEvent.getRawXCursorPosition(),
4443 motionEvent.getRawYCursorPosition(),
4444 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004445 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004446 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004447 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004448 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004449 sampleEventTimes += 1;
4450 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004451 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004452 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4453 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004454 displayId, policyFlags, action, actionButton,
4455 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004456 motionEvent.getButtonState(),
4457 motionEvent.getClassification(),
4458 motionEvent.getEdgeFlags(),
4459 motionEvent.getXPrecision(),
4460 motionEvent.getYPrecision(),
4461 motionEvent.getRawXCursorPosition(),
4462 motionEvent.getRawYCursorPosition(),
4463 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004464 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004465 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004466 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4467 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004468 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004469 }
4470 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004472
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004473 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004474 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004475 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004476 }
4477
Prabir Pradhan5735a322022-04-11 17:23:34 +00004478 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004479 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004480 injectionState->injectionIsAsync = true;
4481 }
4482
4483 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004484 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004485
4486 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004487 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004488 if (DEBUG_INJECTION) {
4489 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4490 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004491 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004492 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493 }
4494
4495 mLock.unlock();
4496
4497 if (needWake) {
4498 mLooper->wake();
4499 }
4500
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004501 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004502 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004503 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004505 if (syncMode == InputEventInjectionSync::NONE) {
4506 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004507 } else {
4508 for (;;) {
4509 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004510 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004511 break;
4512 }
4513
4514 nsecs_t remainingTimeout = endTime - now();
4515 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004516 if (DEBUG_INJECTION) {
4517 ALOGD("injectInputEvent - Timed out waiting for injection result "
4518 "to become available.");
4519 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004520 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004521 break;
4522 }
4523
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004524 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525 }
4526
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004527 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4528 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004529 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004530 if (DEBUG_INJECTION) {
4531 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4532 injectionState->pendingForegroundDispatches);
4533 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534 nsecs_t remainingTimeout = endTime - now();
4535 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004536 if (DEBUG_INJECTION) {
4537 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4538 "dispatches to finish.");
4539 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004540 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004541 break;
4542 }
4543
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004544 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004545 }
4546 }
4547 }
4548
4549 injectionState->release();
4550 } // release lock
4551
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004552 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004553 LOG(DEBUG) << "injectInputEvent - Finished with result "
4554 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004555 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004556
4557 return injectionResult;
4558}
4559
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004560std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004561 std::array<uint8_t, 32> calculatedHmac;
4562 std::unique_ptr<VerifiedInputEvent> result;
4563 switch (event.getType()) {
4564 case AINPUT_EVENT_TYPE_KEY: {
4565 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4566 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4567 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004568 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004569 break;
4570 }
4571 case AINPUT_EVENT_TYPE_MOTION: {
4572 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4573 VerifiedMotionEvent verifiedMotionEvent =
4574 verifiedMotionEventFromMotionEvent(motionEvent);
4575 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004576 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004577 break;
4578 }
4579 default: {
4580 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4581 return nullptr;
4582 }
4583 }
4584 if (calculatedHmac == INVALID_HMAC) {
4585 return nullptr;
4586 }
4587 if (calculatedHmac != event.getHmac()) {
4588 return nullptr;
4589 }
4590 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004591}
4592
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004593void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004594 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004595 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004596 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004597 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004598 LOG(DEBUG) << "Setting input event injection result to "
4599 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004600 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004601
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004602 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603 // Log the outcome since the injector did not wait for the injection result.
4604 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004605 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004606 ALOGV("Asynchronous input event injection succeeded.");
4607 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004608 case InputEventInjectionResult::TARGET_MISMATCH:
4609 ALOGV("Asynchronous input event injection target mismatch.");
4610 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004611 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004612 ALOGW("Asynchronous input event injection failed.");
4613 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004614 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004615 ALOGW("Asynchronous input event injection timed out.");
4616 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004617 case InputEventInjectionResult::PENDING:
4618 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4619 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004620 }
4621 }
4622
4623 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004624 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004625 }
4626}
4627
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004628void InputDispatcher::transformMotionEntryForInjectionLocked(
4629 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004630 // Input injection works in the logical display coordinate space, but the input pipeline works
4631 // display space, so we need to transform the injected events accordingly.
4632 const auto it = mDisplayInfos.find(entry.displayId);
4633 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004634 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004635
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004636 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4637 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4638 const vec2 cursor =
4639 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4640 {entry.xCursorPosition, entry.yCursorPosition});
4641 entry.xCursorPosition = cursor.x;
4642 entry.yCursorPosition = cursor.y;
4643 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004644 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004645 entry.pointerCoords[i] =
4646 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4647 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004648 }
4649}
4650
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004651void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4652 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004653 if (injectionState) {
4654 injectionState->pendingForegroundDispatches += 1;
4655 }
4656}
4657
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004658void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4659 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004660 if (injectionState) {
4661 injectionState->pendingForegroundDispatches -= 1;
4662
4663 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004664 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004665 }
4666 }
4667}
4668
chaviw98318de2021-05-19 16:45:23 -05004669const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004670 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004671 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004672 auto it = mWindowHandlesByDisplay.find(displayId);
4673 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004674}
4675
chaviw98318de2021-05-19 16:45:23 -05004676sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004677 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004678 if (windowHandleToken == nullptr) {
4679 return nullptr;
4680 }
4681
Arthur Hungb92218b2018-08-14 12:00:21 +08004682 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004683 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4684 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004685 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004686 return windowHandle;
4687 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004688 }
4689 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004690 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004691}
4692
chaviw98318de2021-05-19 16:45:23 -05004693sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4694 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004695 if (windowHandleToken == nullptr) {
4696 return nullptr;
4697 }
4698
chaviw98318de2021-05-19 16:45:23 -05004699 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004700 if (windowHandle->getToken() == windowHandleToken) {
4701 return windowHandle;
4702 }
4703 }
4704 return nullptr;
4705}
4706
chaviw98318de2021-05-19 16:45:23 -05004707sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4708 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004709 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004710 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4711 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004712 if (handle->getId() == windowHandle->getId() &&
4713 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004714 if (windowHandle->getInfo()->displayId != it.first) {
4715 ALOGE("Found window %s in display %" PRId32
4716 ", but it should belong to display %" PRId32,
4717 windowHandle->getName().c_str(), it.first,
4718 windowHandle->getInfo()->displayId);
4719 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004720 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004721 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004722 }
4723 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004724 return nullptr;
4725}
4726
chaviw98318de2021-05-19 16:45:23 -05004727sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004728 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4729 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004730}
4731
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004732bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4733 const MotionEntry& motionEntry) const {
4734 const WindowInfo& info = *window->getInfo();
4735
4736 // Skip spy window targets that are not valid for targeted injection.
4737 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004738 return false;
4739 }
4740
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004741 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4742 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4743 return false;
4744 }
4745
4746 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4747 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4748 window->getName().c_str());
4749 return false;
4750 }
4751
4752 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004753 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004754 ALOGW("Not sending touch to %s because there's no corresponding connection",
4755 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004756 return false;
4757 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004758
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004759 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004760 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004761 return false;
4762 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004763
4764 // Drop events that can't be trusted due to occlusion
4765 const auto [x, y] = resolveTouchedPosition(motionEntry);
4766 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4767 if (!isTouchTrustedLocked(occlusionInfo)) {
4768 if (DEBUG_TOUCH_OCCLUSION) {
4769 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4770 for (const auto& log : occlusionInfo.debugInfo) {
4771 ALOGD("%s", log.c_str());
4772 }
4773 }
4774 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4775 occlusionInfo.obscuringUid);
4776 return false;
4777 }
4778
4779 // Drop touch events if requested by input feature
4780 if (shouldDropInput(motionEntry, window)) {
4781 return false;
4782 }
4783
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004784 return true;
4785}
4786
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004787std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4788 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004789 auto connectionIt = mConnectionsByToken.find(token);
4790 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004791 return nullptr;
4792 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004793 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004794}
4795
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004796void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004797 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4798 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004799 // Remove all handles on a display if there are no windows left.
4800 mWindowHandlesByDisplay.erase(displayId);
4801 return;
4802 }
4803
4804 // Since we compare the pointer of input window handles across window updates, we need
4805 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004806 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4807 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4808 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004809 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004810 }
4811
chaviw98318de2021-05-19 16:45:23 -05004812 std::vector<sp<WindowInfoHandle>> newHandles;
4813 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004814 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004815 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004816 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004817 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004818 const bool canReceiveInput =
4819 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4820 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004821 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004822 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004823 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004824 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004825 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004826 }
4827
4828 if (info->displayId != displayId) {
4829 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4830 handle->getName().c_str(), displayId, info->displayId);
4831 continue;
4832 }
4833
Robert Carredd13602020-04-13 17:24:34 -07004834 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4835 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004836 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004837 oldHandle->updateFrom(handle);
4838 newHandles.push_back(oldHandle);
4839 } else {
4840 newHandles.push_back(handle);
4841 }
4842 }
4843
4844 // Insert or replace
4845 mWindowHandlesByDisplay[displayId] = newHandles;
4846}
4847
Arthur Hung72d8dc32020-03-28 00:48:39 +00004848void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004849 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004850 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004851 { // acquire lock
4852 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004853 for (const auto& [displayId, handles] : handlesPerDisplay) {
4854 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004855 }
4856 }
4857 // Wake up poll loop since it may need to make new input dispatching choices.
4858 mLooper->wake();
4859}
4860
Arthur Hungb92218b2018-08-14 12:00:21 +08004861/**
4862 * Called from InputManagerService, update window handle list by displayId that can receive input.
4863 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4864 * If set an empty list, remove all handles from the specific display.
4865 * For focused handle, check if need to change and send a cancel event to previous one.
4866 * For removed handle, check if need to send a cancel event if already in touch.
4867 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004868void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004869 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004870 if (DEBUG_FOCUS) {
4871 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004872 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004873 windowList += iwh->getName() + " ";
4874 }
4875 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4876 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004877
Prabir Pradhand65552b2021-10-07 11:23:50 -07004878 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004879 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004880 const WindowInfo& info = *window->getInfo();
4881
4882 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004883 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004884 if (noInputWindow && window->getToken() != nullptr) {
4885 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4886 window->getName().c_str());
4887 window->releaseChannel();
4888 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004889
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004890 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004891 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4892 !info.inputConfig.test(
4893 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004894 "%s has feature SPY, but is not a trusted overlay.",
4895 window->getName().c_str());
4896
Prabir Pradhand65552b2021-10-07 11:23:50 -07004897 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004898 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4899 !info.inputConfig.test(
4900 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004901 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4902 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004903 }
4904
Arthur Hung72d8dc32020-03-28 00:48:39 +00004905 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004906 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004907
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004908 // Save the old windows' orientation by ID before it gets updated.
4909 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004910 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004911 oldWindowOrientations.emplace(handle->getId(),
4912 handle->getInfo()->transform.getOrientation());
4913 }
4914
chaviw98318de2021-05-19 16:45:23 -05004915 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004916
chaviw98318de2021-05-19 16:45:23 -05004917 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004918
Vishnu Nairc519ff72021-01-21 08:23:08 -08004919 std::optional<FocusResolver::FocusChanges> changes =
4920 mFocusResolver.setInputWindows(displayId, windowHandles);
4921 if (changes) {
4922 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004923 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004925 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4926 mTouchStatesByDisplay.find(displayId);
4927 if (stateIt != mTouchStatesByDisplay.end()) {
4928 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004929 for (size_t i = 0; i < state.windows.size();) {
4930 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004931 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004932 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004933 ALOGD("Touched window was removed: %s in display %" PRId32,
4934 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004935 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004936 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004937 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4938 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004939 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00004940 "touched window was removed");
4941 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004942 // Since we are about to drop the touch, cancel the events for the wallpaper as
4943 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004944 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004945 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4946 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004947 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004948 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004950 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004951 state.windows.erase(state.windows.begin() + i);
4952 } else {
4953 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004954 }
4955 }
arthurhungb89ccb02020-12-30 16:19:01 +08004956
arthurhung6d4bed92021-03-17 11:59:33 +08004957 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004958 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004959 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004960 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004961 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004962 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4963 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004964 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004965 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004966 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004967
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004968 // Determine if the orientation of any of the input windows have changed, and cancel all
4969 // pointer events if necessary.
4970 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4971 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4972 if (newWindowHandle != nullptr &&
4973 newWindowHandle->getInfo()->transform.getOrientation() !=
4974 oldWindowOrientations[oldWindowHandle->getId()]) {
4975 std::shared_ptr<InputChannel> inputChannel =
4976 getInputChannelLocked(newWindowHandle->getToken());
4977 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004978 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004979 "touched window's orientation changed");
4980 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004981 }
4982 }
4983 }
4984
Arthur Hung72d8dc32020-03-28 00:48:39 +00004985 // Release information for windows that are no longer present.
4986 // This ensures that unused input channels are released promptly.
4987 // Otherwise, they might stick around until the window handle is destroyed
4988 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004989 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004990 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004991 if (DEBUG_FOCUS) {
4992 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004993 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004994 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004995 }
chaviw291d88a2019-02-14 10:33:58 -08004996 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004997}
4998
4999void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005000 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005001 if (DEBUG_FOCUS) {
5002 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5003 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5004 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005005 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005006 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005007 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005008 } // release lock
5009
5010 // Wake up poll loop since it may need to make new input dispatching choices.
5011 mLooper->wake();
5012}
5013
Vishnu Nair599f1412021-06-21 10:39:58 -07005014void InputDispatcher::setFocusedApplicationLocked(
5015 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5016 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5017 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5018
5019 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5020 return; // This application is already focused. No need to wake up or change anything.
5021 }
5022
5023 // Set the new application handle.
5024 if (inputApplicationHandle != nullptr) {
5025 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5026 } else {
5027 mFocusedApplicationHandlesByDisplay.erase(displayId);
5028 }
5029
5030 // No matter what the old focused application was, stop waiting on it because it is
5031 // no longer focused.
5032 resetNoFocusedWindowTimeoutLocked();
5033}
5034
Tiger Huang721e26f2018-07-24 22:26:19 +08005035/**
5036 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5037 * the display not specified.
5038 *
5039 * We track any unreleased events for each window. If a window loses the ability to receive the
5040 * released event, we will send a cancel event to it. So when the focused display is changed, we
5041 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5042 * display. The display-specified events won't be affected.
5043 */
5044void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005045 if (DEBUG_FOCUS) {
5046 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5047 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005048 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005049 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005050
5051 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005052 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005053 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005054 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005055 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005056 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005057 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005058 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005059 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005060 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005061 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005062 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5063 }
5064 }
5065 mFocusedDisplayId = displayId;
5066
Chris Ye3c2d6f52020-08-09 10:39:48 -07005067 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005068 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005069 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005070
Vishnu Nairad321cd2020-08-20 16:40:21 -07005071 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005072 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005073 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005074 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005075 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005076 }
5077 }
5078 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005079 } // release lock
5080
5081 // Wake up poll loop since it may need to make new input dispatching choices.
5082 mLooper->wake();
5083}
5084
Michael Wrightd02c5b62014-02-10 15:10:22 -08005085void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005086 if (DEBUG_FOCUS) {
5087 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5088 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005089
5090 bool changed;
5091 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005092 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005093
5094 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5095 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005096 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005097 }
5098
5099 if (mDispatchEnabled && !enabled) {
5100 resetAndDropEverythingLocked("dispatcher is being disabled");
5101 }
5102
5103 mDispatchEnabled = enabled;
5104 mDispatchFrozen = frozen;
5105 changed = true;
5106 } else {
5107 changed = false;
5108 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005109 } // release lock
5110
5111 if (changed) {
5112 // Wake up poll loop since it may need to make new input dispatching choices.
5113 mLooper->wake();
5114 }
5115}
5116
5117void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005118 if (DEBUG_FOCUS) {
5119 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5120 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005121
5122 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005123 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124
5125 if (mInputFilterEnabled == enabled) {
5126 return;
5127 }
5128
5129 mInputFilterEnabled = enabled;
5130 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5131 } // release lock
5132
5133 // Wake up poll loop since there might be work to do to drop everything.
5134 mLooper->wake();
5135}
5136
Antonio Kanteka042c022022-07-06 16:51:07 -07005137bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5138 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005139 bool needWake = false;
5140 {
5141 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005142 ALOGD_IF(DEBUG_TOUCH_MODE,
5143 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5144 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5145 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5146 mTouchModePerDisplay.count(displayId) == 0
5147 ? "not set"
5148 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5149
Antonio Kantek15beb512022-06-13 22:35:41 +00005150 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5151 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005152 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005153 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005154 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005155 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5156 !recentWindowsAreOwnedByLocked(pid, uid)) {
5157 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5158 "window nor none of the previously interacted window",
5159 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005160 return false;
5161 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005162 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005163 mTouchModePerDisplay[displayId] = inTouchMode;
5164 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5165 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005166 needWake = enqueueInboundEventLocked(std::move(entry));
5167 } // release lock
5168
5169 if (needWake) {
5170 mLooper->wake();
5171 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005172 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005173}
5174
Antonio Kantek48710e42022-03-24 14:19:30 -07005175bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5176 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5177 if (focusedToken == nullptr) {
5178 return false;
5179 }
5180 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5181 return isWindowOwnedBy(windowHandle, pid, uid);
5182}
5183
5184bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5185 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5186 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5187 const sp<WindowInfoHandle> windowHandle =
5188 getWindowHandleLocked(connectionToken);
5189 return isWindowOwnedBy(windowHandle, pid, uid);
5190 }) != mInteractionConnectionTokens.end();
5191}
5192
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005193void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5194 if (opacity < 0 || opacity > 1) {
5195 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5196 return;
5197 }
5198
5199 std::scoped_lock lock(mLock);
5200 mMaximumObscuringOpacityForTouch = opacity;
5201}
5202
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005203std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5204InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005205 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5206 for (TouchedWindow& w : state.windows) {
5207 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005208 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005209 }
5210 }
5211 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005212 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005213}
5214
arthurhungb89ccb02020-12-30 16:19:01 +08005215bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5216 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005217 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005218 if (DEBUG_FOCUS) {
5219 ALOGD("Trivial transfer to same window.");
5220 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005221 return true;
5222 }
5223
Michael Wrightd02c5b62014-02-10 15:10:22 -08005224 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005225 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005226
Arthur Hungabbb9d82021-09-01 14:52:30 +00005227 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005228 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005229 if (state == nullptr || touchedWindow == nullptr) {
5230 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231 return false;
5232 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005233
Arthur Hungabbb9d82021-09-01 14:52:30 +00005234 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5235 if (toWindowHandle == nullptr) {
5236 ALOGW("Cannot transfer focus because to window not found.");
5237 return false;
5238 }
5239
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005240 if (DEBUG_FOCUS) {
5241 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005242 touchedWindow->windowHandle->getName().c_str(),
5243 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005244 }
5245
Arthur Hungabbb9d82021-09-01 14:52:30 +00005246 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005247 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005248 BitSet32 pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005249 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005250 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005251
Arthur Hungabbb9d82021-09-01 14:52:30 +00005252 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005253 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005254 ftl::Flags<InputTarget::Flags> newTargetFlags =
5255 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005256 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005257 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005258 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005259 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005260
Arthur Hungabbb9d82021-09-01 14:52:30 +00005261 // Store the dragging window.
5262 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005263 if (pointerIds.count() != 1) {
5264 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5265 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005266 return false;
5267 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005268 // Track the pointer id for drag window and generate the drag state.
5269 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005270 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005271 }
5272
Arthur Hungabbb9d82021-09-01 14:52:30 +00005273 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005274 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5275 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005276 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005277 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005278 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005279 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005280 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005281 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005282 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5283 newTargetFlags);
5284
5285 // Check if the wallpaper window should deliver the corresponding event.
5286 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5287 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005288 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005289 } // release lock
5290
5291 // Wake up poll loop since it may need to make new input dispatching choices.
5292 mLooper->wake();
5293 return true;
5294}
5295
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005296/**
5297 * Get the touched foreground window on the given display.
5298 * Return null if there are no windows touched on that display, or if more than one foreground
5299 * window is being touched.
5300 */
5301sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5302 auto stateIt = mTouchStatesByDisplay.find(displayId);
5303 if (stateIt == mTouchStatesByDisplay.end()) {
5304 ALOGI("No touch state on display %" PRId32, displayId);
5305 return nullptr;
5306 }
5307
5308 const TouchState& state = stateIt->second;
5309 sp<WindowInfoHandle> touchedForegroundWindow;
5310 // If multiple foreground windows are touched, return nullptr
5311 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005312 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005313 if (touchedForegroundWindow != nullptr) {
5314 ALOGI("Two or more foreground windows: %s and %s",
5315 touchedForegroundWindow->getName().c_str(),
5316 window.windowHandle->getName().c_str());
5317 return nullptr;
5318 }
5319 touchedForegroundWindow = window.windowHandle;
5320 }
5321 }
5322 return touchedForegroundWindow;
5323}
5324
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005325// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005326bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005327 sp<IBinder> fromToken;
5328 { // acquire lock
5329 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005330 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005331 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005332 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5333 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005334 return false;
5335 }
5336
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005337 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5338 if (from == nullptr) {
5339 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5340 return false;
5341 }
5342
5343 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005344 } // release lock
5345
5346 return transferTouchFocus(fromToken, destChannelToken);
5347}
5348
Michael Wrightd02c5b62014-02-10 15:10:22 -08005349void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005350 if (DEBUG_FOCUS) {
5351 ALOGD("Resetting and dropping all events (%s).", reason);
5352 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005353
Michael Wrightfb04fd52022-11-24 22:31:11 +00005354 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005355 synthesizeCancelationEventsForAllConnectionsLocked(options);
5356
5357 resetKeyRepeatLocked();
5358 releasePendingEventLocked();
5359 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005360 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005361
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005362 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005363 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005364 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005365}
5366
5367void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005368 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005369 dumpDispatchStateLocked(dump);
5370
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005371 std::istringstream stream(dump);
5372 std::string line;
5373
5374 while (std::getline(stream, line, '\n')) {
5375 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005376 }
5377}
5378
Prabir Pradhan99987712020-11-10 18:43:05 -08005379std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5380 std::string dump;
5381
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005382 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5383 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005384
5385 std::string windowName = "None";
5386 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005387 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005388 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5389 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5390 : "token has capture without window";
5391 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005392 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005393
5394 return dump;
5395}
5396
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005397void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005398 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5399 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5400 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005401 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005402
Tiger Huang721e26f2018-07-24 22:26:19 +08005403 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5404 dump += StringPrintf(INDENT "FocusedApplications:\n");
5405 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5406 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005407 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005408 const std::chrono::duration timeout =
5409 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005410 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005411 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005412 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005413 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005414 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005415 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005416 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005417
Vishnu Nairc519ff72021-01-21 08:23:08 -08005418 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005419 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005420
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005421 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005422 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005423 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005424 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5425 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005426 }
5427 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005428 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005429 }
5430
arthurhung6d4bed92021-03-17 11:59:33 +08005431 if (mDragState) {
5432 dump += StringPrintf(INDENT "DragState:\n");
5433 mDragState->dump(dump, INDENT2);
5434 }
5435
Arthur Hungb92218b2018-08-14 12:00:21 +08005436 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005437 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5438 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5439 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5440 const auto& displayInfo = it->second;
5441 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5442 displayInfo.logicalHeight);
5443 displayInfo.transform.dump(dump, "transform", INDENT4);
5444 } else {
5445 dump += INDENT2 "No DisplayInfo found!\n";
5446 }
5447
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005448 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005449 dump += INDENT2 "Windows:\n";
5450 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005451 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5452 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005453
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005454 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005455 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005456 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005457 "applicationInfo.name=%s, "
5458 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005459 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005460 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005461 windowInfo->displayId,
5462 windowInfo->inputConfig.string().c_str(),
5463 windowInfo->alpha, windowInfo->frameLeft,
5464 windowInfo->frameTop, windowInfo->frameRight,
5465 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005466 windowInfo->applicationInfo.name.c_str(),
5467 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005468 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005469 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005470 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005471 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005472 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005473 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005474 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005475 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005476 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005477 }
5478 } else {
5479 dump += INDENT2 "Windows: <none>\n";
5480 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005481 }
5482 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005483 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005484 }
5485
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005486 if (!mGlobalMonitorsByDisplay.empty()) {
5487 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5488 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005489 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005490 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005491 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005492 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005493 }
5494
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005495 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005496
5497 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005498 if (!mRecentQueue.empty()) {
5499 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005500 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005501 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005502 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005503 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005504 }
5505 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005506 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005507 }
5508
5509 // Dump event currently being dispatched.
5510 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005511 dump += INDENT "PendingEvent:\n";
5512 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005513 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005514 dump += StringPrintf(", age=%" PRId64 "ms\n",
5515 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005516 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005517 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005518 }
5519
5520 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005521 if (!mInboundQueue.empty()) {
5522 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005523 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005524 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005525 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005526 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005527 }
5528 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005529 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005530 }
5531
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005532 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005533 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005534 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005535 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005536 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005537 }
5538 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005539 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005540 }
5541
Prabir Pradhancef936d2021-07-21 16:17:52 +00005542 if (!mCommandQueue.empty()) {
5543 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5544 } else {
5545 dump += INDENT "CommandQueue: <empty>\n";
5546 }
5547
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005548 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005549 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005550 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005551 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005552 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005553 connection->inputChannel->getFd().get(),
5554 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005555 connection->getWindowName().c_str(),
5556 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005557 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005558
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005559 if (!connection->outboundQueue.empty()) {
5560 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5561 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005562 dump += dumpQueue(connection->outboundQueue, currentTime);
5563
Michael Wrightd02c5b62014-02-10 15:10:22 -08005564 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005565 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005566 }
5567
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005568 if (!connection->waitQueue.empty()) {
5569 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5570 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005571 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005572 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005573 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005574 }
5575 }
5576 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005577 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005578 }
5579
5580 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005581 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5582 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005583 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005584 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005585 }
5586
Antonio Kantek15beb512022-06-13 22:35:41 +00005587 if (!mTouchModePerDisplay.empty()) {
5588 dump += INDENT "TouchModePerDisplay:\n";
5589 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5590 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5591 std::to_string(touchMode).c_str());
5592 }
5593 } else {
5594 dump += INDENT "TouchModePerDisplay: <none>\n";
5595 }
5596
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005597 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005598 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5599 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5600 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005601 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005602 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005603}
5604
Michael Wright3dd60e22019-03-27 22:06:44 +00005605void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5606 const size_t numMonitors = monitors.size();
5607 for (size_t i = 0; i < numMonitors; i++) {
5608 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005609 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005610 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5611 dump += "\n";
5612 }
5613}
5614
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005615class LooperEventCallback : public LooperCallback {
5616public:
5617 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5618 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5619
5620private:
5621 std::function<int(int events)> mCallback;
5622};
5623
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005624Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005625 if (DEBUG_CHANNEL_CREATION) {
5626 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5627 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005628
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005629 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005630 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005631 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005632
5633 if (result) {
5634 return base::Error(result) << "Failed to open input channel pair with name " << name;
5635 }
5636
Michael Wrightd02c5b62014-02-10 15:10:22 -08005637 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005638 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005639 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005640 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005641 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005642 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005643
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005644 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5645 ALOGE("Created a new connection, but the token %p is already known", token.get());
5646 }
5647 mConnectionsByToken.emplace(token, connection);
5648
5649 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5650 this, std::placeholders::_1, token);
5651
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005652 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5653 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005654 } // release lock
5655
5656 // Wake the looper because some connections have changed.
5657 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005658 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005659}
5660
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005661Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005662 const std::string& name,
5663 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005664 std::shared_ptr<InputChannel> serverChannel;
5665 std::unique_ptr<InputChannel> clientChannel;
5666 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5667 if (result) {
5668 return base::Error(result) << "Failed to open input channel pair with name " << name;
5669 }
5670
Michael Wright3dd60e22019-03-27 22:06:44 +00005671 { // acquire lock
5672 std::scoped_lock _l(mLock);
5673
5674 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005675 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5676 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005677 }
5678
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005679 sp<Connection> connection =
5680 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005681 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005682 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005683
5684 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5685 ALOGE("Created a new connection, but the token %p is already known", token.get());
5686 }
5687 mConnectionsByToken.emplace(token, connection);
5688 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5689 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005690
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005691 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005692
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005693 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5694 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005695 }
Garfield Tan15601662020-09-22 15:32:38 -07005696
Michael Wright3dd60e22019-03-27 22:06:44 +00005697 // Wake the looper because some connections have changed.
5698 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005699 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005700}
5701
Garfield Tan15601662020-09-22 15:32:38 -07005702status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005703 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005704 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005705
Garfield Tan15601662020-09-22 15:32:38 -07005706 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005707 if (status) {
5708 return status;
5709 }
5710 } // release lock
5711
5712 // Wake the poll loop because removing the connection may have changed the current
5713 // synchronization state.
5714 mLooper->wake();
5715 return OK;
5716}
5717
Garfield Tan15601662020-09-22 15:32:38 -07005718status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5719 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005720 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005721 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005722 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005723 return BAD_VALUE;
5724 }
5725
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005726 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005727
Michael Wrightd02c5b62014-02-10 15:10:22 -08005728 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005729 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005730 }
5731
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005732 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005733
5734 nsecs_t currentTime = now();
5735 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5736
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005737 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005738 return OK;
5739}
5740
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005741void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005742 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5743 auto& [displayId, monitors] = *it;
5744 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5745 return monitor.inputChannel->getConnectionToken() == connectionToken;
5746 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005747
Michael Wright3dd60e22019-03-27 22:06:44 +00005748 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005749 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005750 } else {
5751 ++it;
5752 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005753 }
5754}
5755
Michael Wright3dd60e22019-03-27 22:06:44 +00005756status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005757 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005758 return pilferPointersLocked(token);
5759}
Michael Wright3dd60e22019-03-27 22:06:44 +00005760
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005761status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005762 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5763 if (!requestingChannel) {
5764 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5765 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005766 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005767
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005768 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07005769 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.isEmpty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005770 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5771 " Ignoring.");
5772 return BAD_VALUE;
5773 }
5774
5775 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005776 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005777 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005778 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005779 "input channel stole pointer stream");
5780 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005781 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005782 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005783 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005784 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005785 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005786 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005787 if (channel != nullptr && channel->getConnectionToken() != token) {
5788 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5789 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5790 canceledWindows += channel->getName();
5791 }
5792 }
5793 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5794 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5795 canceledWindows.c_str());
5796
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005797 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005798 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08005799 for (BitSet32 idBits(window.pointerIds); !idBits.isEmpty();) {
5800 uint32_t id = idBits.clearFirstMarkedBit();
5801 window.pilferedPointerIds.set(id);
5802 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005803
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005804 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005805 return OK;
5806}
5807
Prabir Pradhan99987712020-11-10 18:43:05 -08005808void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5809 { // acquire lock
5810 std::scoped_lock _l(mLock);
5811 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005812 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005813 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5814 windowHandle != nullptr ? windowHandle->getName().c_str()
5815 : "token without window");
5816 }
5817
Vishnu Nairc519ff72021-01-21 08:23:08 -08005818 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005819 if (focusedToken != windowToken) {
5820 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5821 enabled ? "enable" : "disable");
5822 return;
5823 }
5824
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005825 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005826 ALOGW("Ignoring request to %s Pointer Capture: "
5827 "window has %s requested pointer capture.",
5828 enabled ? "enable" : "disable", enabled ? "already" : "not");
5829 return;
5830 }
5831
Christine Franksb768bb42021-11-29 12:11:31 -08005832 if (enabled) {
5833 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5834 mIneligibleDisplaysForPointerCapture.end(),
5835 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5836 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5837 return;
5838 }
5839 }
5840
Prabir Pradhan99987712020-11-10 18:43:05 -08005841 setPointerCaptureLocked(enabled);
5842 } // release lock
5843
5844 // Wake the thread to process command entries.
5845 mLooper->wake();
5846}
5847
Christine Franksb768bb42021-11-29 12:11:31 -08005848void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5849 { // acquire lock
5850 std::scoped_lock _l(mLock);
5851 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5852 if (!isEligible) {
5853 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5854 }
5855 } // release lock
5856}
5857
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005858std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5859 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005860 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005861 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005862 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005863 }
5864 }
5865 }
5866 return std::nullopt;
5867}
5868
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005869sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005870 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005871 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005872 }
5873
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005874 for (const auto& [token, connection] : mConnectionsByToken) {
5875 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005876 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005877 }
5878 }
Robert Carr4e670e52018-08-15 13:26:12 -07005879
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005880 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005881}
5882
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005883std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5884 sp<Connection> connection = getConnectionLocked(connectionToken);
5885 if (connection == nullptr) {
5886 return "<nullptr>";
5887 }
5888 return connection->getInputChannelName();
5889}
5890
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005891void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005892 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005893 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005894}
5895
Prabir Pradhancef936d2021-07-21 16:17:52 +00005896void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5897 const sp<Connection>& connection, uint32_t seq,
5898 bool handled, nsecs_t consumeTime) {
5899 // Handle post-event policy actions.
5900 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5901 if (dispatchEntryIt == connection->waitQueue.end()) {
5902 return;
5903 }
5904 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5905 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5906 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5907 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5908 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5909 }
5910 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5911 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5912 connection->inputChannel->getConnectionToken(),
5913 dispatchEntry->deliveryTime, consumeTime, finishTime);
5914 }
5915
5916 bool restartEvent;
5917 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5918 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5919 restartEvent =
5920 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5921 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5922 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5923 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5924 handled);
5925 } else {
5926 restartEvent = false;
5927 }
5928
5929 // Dequeue the event and start the next cycle.
5930 // Because the lock might have been released, it is possible that the
5931 // contents of the wait queue to have been drained, so we need to double-check
5932 // a few things.
5933 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5934 if (dispatchEntryIt != connection->waitQueue.end()) {
5935 dispatchEntry = *dispatchEntryIt;
5936 connection->waitQueue.erase(dispatchEntryIt);
5937 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5938 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5939 if (!connection->responsive) {
5940 connection->responsive = isConnectionResponsive(*connection);
5941 if (connection->responsive) {
5942 // The connection was unresponsive, and now it's responsive.
5943 processConnectionResponsiveLocked(*connection);
5944 }
5945 }
5946 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005947 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005948 connection->outboundQueue.push_front(dispatchEntry);
5949 traceOutboundQueueLength(*connection);
5950 } else {
5951 releaseDispatchEntry(dispatchEntry);
5952 }
5953 }
5954
5955 // Start the next dispatch cycle for this connection.
5956 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005957}
5958
Prabir Pradhancef936d2021-07-21 16:17:52 +00005959void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5960 const sp<IBinder>& newToken) {
5961 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5962 scoped_unlock unlock(mLock);
5963 mPolicy->notifyFocusChanged(oldToken, newToken);
5964 };
5965 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005966}
5967
Prabir Pradhancef936d2021-07-21 16:17:52 +00005968void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5969 auto command = [this, token, x, y]() REQUIRES(mLock) {
5970 scoped_unlock unlock(mLock);
5971 mPolicy->notifyDropWindow(token, x, y);
5972 };
5973 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005974}
5975
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005976void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5977 if (connection == nullptr) {
5978 LOG_ALWAYS_FATAL("Caller must check for nullness");
5979 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005980 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5981 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005982 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005983 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005984 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005985 return;
5986 }
5987 /**
5988 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5989 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5990 * has changed. This could cause newer entries to time out before the already dispatched
5991 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5992 * processes the events linearly. So providing information about the oldest entry seems to be
5993 * most useful.
5994 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005995 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005996 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5997 std::string reason =
5998 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005999 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006000 ns2ms(currentWait),
6001 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006002 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006003 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006004
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006005 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6006
6007 // Stop waking up for events on this connection, it is already unresponsive
6008 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006009}
6010
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006011void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6012 std::string reason =
6013 StringPrintf("%s does not have a focused window", application->getName().c_str());
6014 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006015
Prabir Pradhancef936d2021-07-21 16:17:52 +00006016 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
6017 scoped_unlock unlock(mLock);
6018 mPolicy->notifyNoFocusedWindowAnr(application);
6019 };
6020 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006021}
6022
chaviw98318de2021-05-19 16:45:23 -05006023void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006024 const std::string& reason) {
6025 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6026 updateLastAnrStateLocked(windowLabel, reason);
6027}
6028
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006029void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6030 const std::string& reason) {
6031 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006032 updateLastAnrStateLocked(windowLabel, reason);
6033}
6034
6035void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6036 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006037 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006038 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006039 struct tm tm;
6040 localtime_r(&t, &tm);
6041 char timestr[64];
6042 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006043 mLastAnrState.clear();
6044 mLastAnrState += INDENT "ANR:\n";
6045 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006046 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6047 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006048 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006049}
6050
Prabir Pradhancef936d2021-07-21 16:17:52 +00006051void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6052 KeyEntry& entry) {
6053 const KeyEvent event = createKeyEvent(entry);
6054 nsecs_t delay = 0;
6055 { // release lock
6056 scoped_unlock unlock(mLock);
6057 android::base::Timer t;
6058 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
6059 entry.policyFlags);
6060 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6061 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6062 std::to_string(t.duration().count()).c_str());
6063 }
6064 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006065
6066 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006067 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006068 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006069 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006070 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006071 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006072 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006073 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006074}
6075
Prabir Pradhancef936d2021-07-21 16:17:52 +00006076void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006077 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006078 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006079 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006080 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006081 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006082 };
6083 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006084}
6085
Prabir Pradhanedd96402022-02-15 01:46:16 -08006086void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6087 std::optional<int32_t> pid) {
6088 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006089 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006090 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006091 };
6092 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006093}
6094
6095/**
6096 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6097 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6098 * command entry to the command queue.
6099 */
6100void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6101 std::string reason) {
6102 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006103 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006104 if (connection.monitor) {
6105 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6106 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006107 pid = findMonitorPidByTokenLocked(connectionToken);
6108 } else {
6109 // The connection is a window
6110 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6111 reason.c_str());
6112 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6113 if (handle != nullptr) {
6114 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006115 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006116 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006117 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006118}
6119
6120/**
6121 * Tell the policy that a connection has become responsive so that it can stop ANR.
6122 */
6123void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6124 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006125 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006126 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006127 pid = findMonitorPidByTokenLocked(connectionToken);
6128 } else {
6129 // The connection is a window
6130 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6131 if (handle != nullptr) {
6132 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006133 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006134 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006135 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006136}
6137
Prabir Pradhancef936d2021-07-21 16:17:52 +00006138bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006139 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006140 KeyEntry& keyEntry, bool handled) {
6141 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006142 if (!handled) {
6143 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006144 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006145 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006146 return false;
6147 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006148
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006149 // Get the fallback key state.
6150 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006151 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006152 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006153 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006154 connection->inputState.removeFallbackKey(originalKeyCode);
6155 }
6156
6157 if (handled || !dispatchEntry->hasForegroundTarget()) {
6158 // If the application handles the original key for which we previously
6159 // generated a fallback or if the window is not a foreground window,
6160 // then cancel the associated fallback key, if any.
6161 if (fallbackKeyCode != -1) {
6162 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006163 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6164 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6165 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6166 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6167 keyEntry.policyFlags);
6168 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006169 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006170 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006171
6172 mLock.unlock();
6173
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006174 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006175 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006176
6177 mLock.lock();
6178
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006179 // Cancel the fallback key.
6180 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006181 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006182 "application handled the original non-fallback key "
6183 "or is no longer a foreground target, "
6184 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006185 options.keyCode = fallbackKeyCode;
6186 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006187 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006188 connection->inputState.removeFallbackKey(originalKeyCode);
6189 }
6190 } else {
6191 // If the application did not handle a non-fallback key, first check
6192 // that we are in a good state to perform unhandled key event processing
6193 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006194 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006195 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006196 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6197 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6198 "since this is not an initial down. "
6199 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6200 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6201 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006202 return false;
6203 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006204
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006205 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006206 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6207 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6208 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6209 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6210 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006211 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006212
6213 mLock.unlock();
6214
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006215 bool fallback =
6216 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006217 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006218
6219 mLock.lock();
6220
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006221 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006222 connection->inputState.removeFallbackKey(originalKeyCode);
6223 return false;
6224 }
6225
6226 // Latch the fallback keycode for this key on an initial down.
6227 // The fallback keycode cannot change at any other point in the lifecycle.
6228 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006229 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006230 fallbackKeyCode = event.getKeyCode();
6231 } else {
6232 fallbackKeyCode = AKEYCODE_UNKNOWN;
6233 }
6234 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6235 }
6236
6237 ALOG_ASSERT(fallbackKeyCode != -1);
6238
6239 // Cancel the fallback key if the policy decides not to send it anymore.
6240 // We will continue to dispatch the key to the policy but we will no
6241 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006242 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6243 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006244 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6245 if (fallback) {
6246 ALOGD("Unhandled key event: Policy requested to send key %d"
6247 "as a fallback for %d, but on the DOWN it had requested "
6248 "to send %d instead. Fallback canceled.",
6249 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6250 } else {
6251 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6252 "but on the DOWN it had requested to send %d. "
6253 "Fallback canceled.",
6254 originalKeyCode, fallbackKeyCode);
6255 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006256 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006257
Michael Wrightfb04fd52022-11-24 22:31:11 +00006258 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006259 "canceling fallback, policy no longer desires it");
6260 options.keyCode = fallbackKeyCode;
6261 synthesizeCancelationEventsForConnectionLocked(connection, options);
6262
6263 fallback = false;
6264 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006265 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006266 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006267 }
6268 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006269
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006270 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6271 {
6272 std::string msg;
6273 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6274 connection->inputState.getFallbackKeys();
6275 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6276 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6277 }
6278 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6279 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006280 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006281 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006282
6283 if (fallback) {
6284 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006285 keyEntry.eventTime = event.getEventTime();
6286 keyEntry.deviceId = event.getDeviceId();
6287 keyEntry.source = event.getSource();
6288 keyEntry.displayId = event.getDisplayId();
6289 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6290 keyEntry.keyCode = fallbackKeyCode;
6291 keyEntry.scanCode = event.getScanCode();
6292 keyEntry.metaState = event.getMetaState();
6293 keyEntry.repeatCount = event.getRepeatCount();
6294 keyEntry.downTime = event.getDownTime();
6295 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006296
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006297 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6298 ALOGD("Unhandled key event: Dispatching fallback key. "
6299 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6300 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6301 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006302 return true; // restart the event
6303 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006304 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6305 ALOGD("Unhandled key event: No fallback key.");
6306 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006307
6308 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006309 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006310 }
6311 }
6312 return false;
6313}
6314
Prabir Pradhancef936d2021-07-21 16:17:52 +00006315bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006316 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006317 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006318 return false;
6319}
6320
Michael Wrightd02c5b62014-02-10 15:10:22 -08006321void InputDispatcher::traceInboundQueueLengthLocked() {
6322 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006323 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006324 }
6325}
6326
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006327void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006328 if (ATRACE_ENABLED()) {
6329 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006330 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6331 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006332 }
6333}
6334
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006335void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006336 if (ATRACE_ENABLED()) {
6337 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006338 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6339 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006340 }
6341}
6342
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006343void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006344 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006345
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006346 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006347 dumpDispatchStateLocked(dump);
6348
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006349 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006350 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006351 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006352 }
6353}
6354
6355void InputDispatcher::monitor() {
6356 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006357 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006358 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006359 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006360}
6361
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006362/**
6363 * Wake up the dispatcher and wait until it processes all events and commands.
6364 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6365 * this method can be safely called from any thread, as long as you've ensured that
6366 * the work you are interested in completing has already been queued.
6367 */
6368bool InputDispatcher::waitForIdle() {
6369 /**
6370 * Timeout should represent the longest possible time that a device might spend processing
6371 * events and commands.
6372 */
6373 constexpr std::chrono::duration TIMEOUT = 100ms;
6374 std::unique_lock lock(mLock);
6375 mLooper->wake();
6376 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6377 return result == std::cv_status::no_timeout;
6378}
6379
Vishnu Naire798b472020-07-23 13:52:21 -07006380/**
6381 * Sets focus to the window identified by the token. This must be called
6382 * after updating any input window handles.
6383 *
6384 * Params:
6385 * request.token - input channel token used to identify the window that should gain focus.
6386 * request.focusedToken - the token that the caller expects currently to be focused. If the
6387 * specified token does not match the currently focused window, this request will be dropped.
6388 * If the specified focused token matches the currently focused window, the call will succeed.
6389 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6390 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6391 * when requesting the focus change. This determines which request gets
6392 * precedence if there is a focus change request from another source such as pointer down.
6393 */
Vishnu Nair958da932020-08-21 17:12:37 -07006394void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6395 { // acquire lock
6396 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006397 std::optional<FocusResolver::FocusChanges> changes =
6398 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6399 if (changes) {
6400 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006401 }
6402 } // release lock
6403 // Wake up poll loop since it may need to make new input dispatching choices.
6404 mLooper->wake();
6405}
6406
Vishnu Nairc519ff72021-01-21 08:23:08 -08006407void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6408 if (changes.oldFocus) {
6409 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006410 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006411 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006412 "focus left window");
6413 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006414 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006415 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006416 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006417 if (changes.newFocus) {
6418 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006419 }
6420
Prabir Pradhan99987712020-11-10 18:43:05 -08006421 // If a window has pointer capture, then it must have focus. We need to ensure that this
6422 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6423 // If the window loses focus before it loses pointer capture, then the window can be in a state
6424 // where it has pointer capture but not focus, violating the contract. Therefore we must
6425 // dispatch the pointer capture event before the focus event. Since focus events are added to
6426 // the front of the queue (above), we add the pointer capture event to the front of the queue
6427 // after the focus events are added. This ensures the pointer capture event ends up at the
6428 // front.
6429 disablePointerCaptureForcedLocked();
6430
Vishnu Nairc519ff72021-01-21 08:23:08 -08006431 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006432 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006433 }
6434}
Vishnu Nair958da932020-08-21 17:12:37 -07006435
Prabir Pradhan99987712020-11-10 18:43:05 -08006436void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006437 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006438 return;
6439 }
6440
6441 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6442
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006443 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006444 setPointerCaptureLocked(false);
6445 }
6446
6447 if (!mWindowTokenWithPointerCapture) {
6448 // No need to send capture changes because no window has capture.
6449 return;
6450 }
6451
6452 if (mPendingEvent != nullptr) {
6453 // Move the pending event to the front of the queue. This will give the chance
6454 // for the pending event to be dropped if it is a captured event.
6455 mInboundQueue.push_front(mPendingEvent);
6456 mPendingEvent = nullptr;
6457 }
6458
6459 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006460 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006461 mInboundQueue.push_front(std::move(entry));
6462}
6463
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006464void InputDispatcher::setPointerCaptureLocked(bool enable) {
6465 mCurrentPointerCaptureRequest.enable = enable;
6466 mCurrentPointerCaptureRequest.seq++;
6467 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006468 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006469 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006470 };
6471 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006472}
6473
Vishnu Nair599f1412021-06-21 10:39:58 -07006474void InputDispatcher::displayRemoved(int32_t displayId) {
6475 { // acquire lock
6476 std::scoped_lock _l(mLock);
6477 // Set an empty list to remove all handles from the specific display.
6478 setInputWindowsLocked(/* window handles */ {}, displayId);
6479 setFocusedApplicationLocked(displayId, nullptr);
6480 // Call focus resolver to clean up stale requests. This must be called after input windows
6481 // have been removed for the removed display.
6482 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006483 // Reset pointer capture eligibility, regardless of previous state.
6484 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006485 // Remove the associated touch mode state.
6486 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006487 } // release lock
6488
6489 // Wake up poll loop since it may need to make new input dispatching choices.
6490 mLooper->wake();
6491}
6492
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006493void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6494 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006495 // The listener sends the windows as a flattened array. Separate the windows by display for
6496 // more convenient parsing.
6497 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006498 for (const auto& info : windowInfos) {
6499 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006500 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006501 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006502
6503 { // acquire lock
6504 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006505
6506 // Ensure that we have an entry created for all existing displays so that if a displayId has
6507 // no windows, we can tell that the windows were removed from the display.
6508 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6509 handlesPerDisplay[displayId];
6510 }
6511
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006512 mDisplayInfos.clear();
6513 for (const auto& displayInfo : displayInfos) {
6514 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6515 }
6516
6517 for (const auto& [displayId, handles] : handlesPerDisplay) {
6518 setInputWindowsLocked(handles, displayId);
6519 }
6520 }
6521 // Wake up poll loop since it may need to make new input dispatching choices.
6522 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006523}
6524
Vishnu Nair062a8672021-09-03 16:07:44 -07006525bool InputDispatcher::shouldDropInput(
6526 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006527 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6528 (windowHandle->getInfo()->inputConfig.test(
6529 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006530 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006531 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6532 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006533 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006534 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006535 windowHandle->getInfo()->displayId);
6536 return true;
6537 }
6538 return false;
6539}
6540
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006541void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6542 const std::vector<gui::WindowInfo>& windowInfos,
6543 const std::vector<DisplayInfo>& displayInfos) {
6544 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6545}
6546
Arthur Hungdfd528e2021-12-08 13:23:04 +00006547void InputDispatcher::cancelCurrentTouch() {
6548 {
6549 std::scoped_lock _l(mLock);
6550 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006551 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006552 "cancel current touch");
6553 synthesizeCancelationEventsForAllConnectionsLocked(options);
6554
6555 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006556 }
6557 // Wake up poll loop since there might be work to do.
6558 mLooper->wake();
6559}
6560
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006561void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6562 std::scoped_lock _l(mLock);
6563 mMonitorDispatchingTimeout = timeout;
6564}
6565
Arthur Hungc539dbb2022-12-08 07:45:36 +00006566void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6567 const sp<WindowInfoHandle>& oldWindowHandle,
6568 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006569 TouchState& state, int32_t pointerId,
6570 std::vector<InputTarget>& targets) {
6571 BitSet32 pointerIds;
6572 pointerIds.markBit(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006573 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6574 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6575 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6576 newWindowHandle->getInfo()->inputConfig.test(
6577 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6578 const sp<WindowInfoHandle> oldWallpaper =
6579 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6580 const sp<WindowInfoHandle> newWallpaper =
6581 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6582 if (oldWallpaper == newWallpaper) {
6583 return;
6584 }
6585
6586 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006587 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6588 addWindowTargetLocked(oldWallpaper,
6589 oldTouchedWindow.targetFlags |
6590 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6591 pointerIds, oldTouchedWindow.firstDownTimeInTarget, targets);
6592 state.removeTouchedPointerFromWindow(pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006593 }
6594
6595 if (newWallpaper != nullptr) {
6596 state.addOrUpdateWindow(newWallpaper,
6597 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6598 InputTarget::Flags::WINDOW_IS_OBSCURED |
6599 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6600 pointerIds);
6601 }
6602}
6603
6604void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6605 ftl::Flags<InputTarget::Flags> newTargetFlags,
6606 const sp<WindowInfoHandle> fromWindowHandle,
6607 const sp<WindowInfoHandle> toWindowHandle,
6608 TouchState& state, const BitSet32& pointerIds) {
6609 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6610 fromWindowHandle->getInfo()->inputConfig.test(
6611 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6612 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6613 toWindowHandle->getInfo()->inputConfig.test(
6614 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6615
6616 const sp<WindowInfoHandle> oldWallpaper =
6617 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6618 const sp<WindowInfoHandle> newWallpaper =
6619 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6620 if (oldWallpaper == newWallpaper) {
6621 return;
6622 }
6623
6624 if (oldWallpaper != nullptr) {
6625 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6626 "transferring touch focus to another window");
6627 state.removeWindowByToken(oldWallpaper->getToken());
6628 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6629 }
6630
6631 if (newWallpaper != nullptr) {
6632 nsecs_t downTimeInTarget = now();
6633 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6634 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6635 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6636 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6637 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
6638 sp<Connection> wallpaperConnection = getConnectionLocked(newWallpaper->getToken());
6639 if (wallpaperConnection != nullptr) {
6640 sp<Connection> toConnection = getConnectionLocked(toWindowHandle->getToken());
6641 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6642 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6643 wallpaperFlags);
6644 }
6645 }
6646}
6647
6648sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6649 const sp<WindowInfoHandle>& windowHandle) const {
6650 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6651 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6652 bool foundWindow = false;
6653 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6654 if (!foundWindow && otherHandle != windowHandle) {
6655 continue;
6656 }
6657 if (windowHandle == otherHandle) {
6658 foundWindow = true;
6659 continue;
6660 }
6661
6662 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6663 return otherHandle;
6664 }
6665 }
6666 return nullptr;
6667}
6668
Garfield Tane84e6f92019-08-29 17:28:41 -07006669} // namespace android::inputdispatcher