blob: 466c51eb882fa22b204db50e77440029dcd992c0 [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>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080023#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080024#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050025#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070026#include <binder/Binder.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080027#include <ftl/enum.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070028#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050029#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070030#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080031#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080032#include <input/PrintTools.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070033#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010034#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070035#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080036
Michael Wright44753b12020-07-08 13:48:11 +010037#include <cerrno>
38#include <cinttypes>
39#include <climits>
40#include <cstddef>
41#include <ctime>
42#include <queue>
43#include <sstream>
44
45#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000046#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070047#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010048
Michael Wrightd02c5b62014-02-10 15:10:22 -080049#define INDENT " "
50#define INDENT2 " "
51#define INDENT3 " "
52#define INDENT4 " "
53
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080054using namespace android::ftl::flag_operators;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080055using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000056using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080057using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070058using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050059using android::gui::FocusRequest;
60using android::gui::TouchOcclusionMode;
61using android::gui::WindowInfo;
62using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080063using android::os::InputEventInjectionResult;
64using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080065
Garfield Tane84e6f92019-08-29 17:28:41 -070066namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080067
Prabir Pradhancef936d2021-07-21 16:17:52 +000068namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000069// Temporarily releases a held mutex for the lifetime of the instance.
70// Named to match std::scoped_lock
71class scoped_unlock {
72public:
73 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
74 ~scoped_unlock() { mMutex.lock(); }
75
76private:
77 std::mutex& mMutex;
78};
79
Michael Wrightd02c5b62014-02-10 15:10:22 -080080// Default input dispatching timeout if there is no focused application or paused window
81// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080082const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
83 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
84 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080085
86// Amount of time to allow for all pending events to be processed when an app switch
87// key is on the way. This is used to preempt input dispatch and drop input events
88// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000089constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080090
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080091const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080092
Michael Wrightd02c5b62014-02-10 15:10:22 -080093// 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 +000094constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
95
96// Log a warning when an interception call takes longer than this to process.
97constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080098
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -070099// Additional key latency in case a connection is still processing some motion events.
100// This will help with the case when a user touched a button that opens a new window,
101// and gives us the chance to dispatch the key to this new window.
102constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
103
Michael Wrightd02c5b62014-02-10 15:10:22 -0800104// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000105constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
106
Antonio Kantekea47acb2021-12-23 12:41:25 -0800107// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000108constexpr int LOGTAG_INPUT_INTERACTION = 62000;
109constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000110constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000111
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000112inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800113 return systemTime(SYSTEM_TIME_MONOTONIC);
114}
115
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000116inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800117 return value ? "true" : "false";
118}
119
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000120inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000121 if (binder == nullptr) {
122 return "<null>";
123 }
124 return StringPrintf("%p", binder.get());
125}
126
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000127inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700128 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
129 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800130}
131
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000132bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800133 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700134 case AKEY_EVENT_ACTION_DOWN:
135 case AKEY_EVENT_ACTION_UP:
136 return true;
137 default:
138 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139 }
140}
141
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000142bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700143 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144 ALOGE("Key event has invalid action code 0x%x", action);
145 return false;
146 }
147 return true;
148}
149
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000150bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800151 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700152 case AMOTION_EVENT_ACTION_DOWN:
153 case AMOTION_EVENT_ACTION_UP:
154 case AMOTION_EVENT_ACTION_CANCEL:
155 case AMOTION_EVENT_ACTION_MOVE:
156 case AMOTION_EVENT_ACTION_OUTSIDE:
157 case AMOTION_EVENT_ACTION_HOVER_ENTER:
158 case AMOTION_EVENT_ACTION_HOVER_MOVE:
159 case AMOTION_EVENT_ACTION_HOVER_EXIT:
160 case AMOTION_EVENT_ACTION_SCROLL:
161 return true;
162 case AMOTION_EVENT_ACTION_POINTER_DOWN:
163 case AMOTION_EVENT_ACTION_POINTER_UP: {
164 int32_t index = getMotionEventActionPointerIndex(action);
165 return index >= 0 && index < pointerCount;
166 }
167 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
168 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
169 return actionButton != 0;
170 default:
171 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800172 }
173}
174
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000175int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500176 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
177}
178
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000179bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
180 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700181 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800182 ALOGE("Motion event has invalid action code 0x%x", action);
183 return false;
184 }
185 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800186 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %zu.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700187 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800188 return false;
189 }
190 BitSet32 pointerIdBits;
191 for (size_t i = 0; i < pointerCount; i++) {
192 int32_t id = pointerProperties[i].id;
193 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700194 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
195 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800196 return false;
197 }
198 if (pointerIdBits.hasBit(id)) {
199 ALOGE("Motion event has duplicate pointer id %d", id);
200 return false;
201 }
202 pointerIdBits.markBit(id);
203 }
204 return true;
205}
206
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000207std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800208 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000209 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800210 }
211
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000212 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800213 bool first = true;
214 Region::const_iterator cur = region.begin();
215 Region::const_iterator const tail = region.end();
216 while (cur != tail) {
217 if (first) {
218 first = false;
219 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800220 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800222 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 cur++;
224 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000225 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226}
227
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000228std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500229 constexpr size_t maxEntries = 50; // max events to print
230 constexpr size_t skipBegin = maxEntries / 2;
231 const size_t skipEnd = queue.size() - maxEntries / 2;
232 // skip from maxEntries / 2 ... size() - maxEntries/2
233 // only print from 0 .. skipBegin and then from skipEnd .. size()
234
235 std::string dump;
236 for (size_t i = 0; i < queue.size(); i++) {
237 const DispatchEntry& entry = *queue[i];
238 if (i >= skipBegin && i < skipEnd) {
239 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
240 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
241 continue;
242 }
243 dump.append(INDENT4);
244 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800245 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
246 "ms",
247 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500248 ns2ms(currentTime - entry.eventEntry->eventTime));
249 if (entry.deliveryTime != 0) {
250 // This entry was delivered, so add information on how long we've been waiting
251 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
252 }
253 dump.append("\n");
254 }
255 return dump;
256}
257
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700258/**
259 * Find the entry in std::unordered_map by key, and return it.
260 * If the entry is not found, return a default constructed entry.
261 *
262 * Useful when the entries are vectors, since an empty vector will be returned
263 * if the entry is not found.
264 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
265 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700266template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000267V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700268 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700269 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800270}
271
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000272bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700273 if (first == second) {
274 return true;
275 }
276
277 if (first == nullptr || second == nullptr) {
278 return false;
279 }
280
281 return first->getToken() == second->getToken();
282}
283
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000284bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000285 if (first == nullptr || second == nullptr) {
286 return false;
287 }
288 return first->applicationInfo.token != nullptr &&
289 first->applicationInfo.token == second->applicationInfo.token;
290}
291
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800292std::unique_ptr<DispatchEntry> createDispatchEntry(
293 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
294 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700295 if (inputTarget.useDefaultPointerTransform()) {
296 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700297 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700298 inputTarget.displayTransform,
299 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000300 }
301
302 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
303 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
304
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700305 std::vector<PointerCoords> pointerCoords;
306 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000307
308 // Use the first pointer information to normalize all other pointers. This could be any pointer
309 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700310 // uses the transform for the normalized pointer.
311 const ui::Transform& firstPointerTransform =
312 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
313 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000314
315 // Iterate through all pointers in the event to normalize against the first.
316 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
317 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
318 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700319 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000320
321 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700322 // First, apply the current pointer's transform to update the coordinates into
323 // window space.
324 pointerCoords[pointerIndex].transform(currTransform);
325 // Next, apply the inverse transform of the normalized coordinates so the
326 // current coordinates are transformed into the normalized coordinate space.
327 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000328 }
329
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700330 std::unique_ptr<MotionEntry> combinedMotionEntry =
331 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
332 motionEntry.deviceId, motionEntry.source,
333 motionEntry.displayId, motionEntry.policyFlags,
334 motionEntry.action, motionEntry.actionButton,
335 motionEntry.flags, motionEntry.metaState,
336 motionEntry.buttonState, motionEntry.classification,
337 motionEntry.edgeFlags, motionEntry.xPrecision,
338 motionEntry.yPrecision, motionEntry.xCursorPosition,
339 motionEntry.yCursorPosition, motionEntry.downTime,
340 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000341 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000342
343 if (motionEntry.injectionState) {
344 combinedMotionEntry->injectionState = motionEntry.injectionState;
345 combinedMotionEntry->injectionState->refCount += 1;
346 }
347
348 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700349 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700350 firstPointerTransform, inputTarget.displayTransform,
351 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000352 return dispatchEntry;
353}
354
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000355status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
356 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700357 std::unique_ptr<InputChannel> uniqueServerChannel;
358 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
359
360 serverChannel = std::move(uniqueServerChannel);
361 return result;
362}
363
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500364template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000365bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500366 if (lhs == nullptr && rhs == nullptr) {
367 return true;
368 }
369 if (lhs == nullptr || rhs == nullptr) {
370 return false;
371 }
372 return *lhs == *rhs;
373}
374
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000375KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000376 KeyEvent event;
377 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
378 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
379 entry.repeatCount, entry.downTime, entry.eventTime);
380 return event;
381}
382
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000383bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000384 // Do not keep track of gesture monitors. They receive every event and would disproportionately
385 // affect the statistics.
386 if (connection.monitor) {
387 return false;
388 }
389 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
390 if (!connection.responsive) {
391 return false;
392 }
393 return true;
394}
395
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000396bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000397 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
398 const int32_t& inputEventId = eventEntry.id;
399 if (inputEventId != dispatchEntry.resolvedEventId) {
400 // Event was transmuted
401 return false;
402 }
403 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
404 return false;
405 }
406 // Only track latency for events that originated from hardware
407 if (eventEntry.isSynthesized()) {
408 return false;
409 }
410 const EventEntry::Type& inputEventEntryType = eventEntry.type;
411 if (inputEventEntryType == EventEntry::Type::KEY) {
412 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
413 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
414 return false;
415 }
416 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
417 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
418 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
419 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
420 return false;
421 }
422 } else {
423 // Not a key or a motion
424 return false;
425 }
426 if (!shouldReportMetricsForConnection(connection)) {
427 return false;
428 }
429 return true;
430}
431
Prabir Pradhancef936d2021-07-21 16:17:52 +0000432/**
433 * Connection is responsive if it has no events in the waitQueue that are older than the
434 * current time.
435 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000436bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000437 const nsecs_t currentTime = now();
438 for (const DispatchEntry* entry : connection.waitQueue) {
439 if (entry->timeoutTime < currentTime) {
440 return false;
441 }
442 }
443 return true;
444}
445
Antonio Kantekf16f2832021-09-28 04:39:20 +0000446// Returns true if the event type passed as argument represents a user activity.
447bool isUserActivityEvent(const EventEntry& eventEntry) {
448 switch (eventEntry.type) {
449 case EventEntry::Type::FOCUS:
450 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
451 case EventEntry::Type::DRAG:
452 case EventEntry::Type::TOUCH_MODE_CHANGED:
453 case EventEntry::Type::SENSOR:
454 case EventEntry::Type::CONFIGURATION_CHANGED:
455 return false;
456 case EventEntry::Type::DEVICE_RESET:
457 case EventEntry::Type::KEY:
458 case EventEntry::Type::MOTION:
459 return true;
460 }
461}
462
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800463// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhand65552b2021-10-07 11:23:50 -0700464bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, int32_t x, int32_t y,
465 bool isStylus) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800466 const auto inputConfig = windowInfo.inputConfig;
467 if (windowInfo.displayId != displayId ||
468 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800469 return false;
470 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700471 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800472 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800473 return false;
474 }
Prabir Pradhan06349042022-02-04 09:19:17 -0800475 if (!windowInfo.touchableRegionContainsPoint(x, y)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800476 return false;
477 }
478 return true;
479}
480
Prabir Pradhand65552b2021-10-07 11:23:50 -0700481bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
482 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000483 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700484}
485
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800486// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000487// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
488// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
489// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800490// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000491bool canReceiveForegroundTouches(const WindowInfo& info) {
492 // A non-touchable window can still receive touch events (e.g. in the case of
493 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
494 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
495}
496
Antonio Kantek48710e42022-03-24 14:19:30 -0700497bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
498 if (windowHandle == nullptr) {
499 return false;
500 }
501 const WindowInfo* windowInfo = windowHandle->getInfo();
502 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
503 return true;
504 }
505 return false;
506}
507
Prabir Pradhan5735a322022-04-11 17:23:34 +0000508// Checks targeted injection using the window's owner's uid.
509// Returns an empty string if an entry can be sent to the given window, or an error message if the
510// entry is a targeted injection whose uid target doesn't match the window owner.
511std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
512 const EventEntry& entry) {
513 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
514 // The event was not injected, or the injected event does not target a window.
515 return {};
516 }
517 const int32_t uid = *entry.injectionState->targetUid;
518 if (window == nullptr) {
519 return StringPrintf("No valid window target for injection into uid %d.", uid);
520 }
521 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
522 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
523 "owned by uid %d.",
524 uid, window->getName().c_str(), window->getInfo()->ownerUid);
525 }
526 return {};
527}
528
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700529Point resolveTouchedPosition(const MotionEntry& entry) {
530 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
531 // Always dispatch mouse events to cursor position.
532 if (isFromMouse) {
533 return Point(static_cast<int32_t>(entry.xCursorPosition),
534 static_cast<int32_t>(entry.yCursorPosition));
535 }
536
537 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
538 return Point(static_cast<int32_t>(
539 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X)),
540 static_cast<int32_t>(
541 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)));
542}
543
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700544std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
545 if (eventEntry.type == EventEntry::Type::KEY) {
546 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
547 return keyEntry.downTime;
548 } else if (eventEntry.type == EventEntry::Type::MOTION) {
549 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
550 return motionEntry.downTime;
551 }
552 return std::nullopt;
553}
554
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000555} // namespace
556
Michael Wrightd02c5b62014-02-10 15:10:22 -0800557// --- InputDispatcher ---
558
Garfield Tan00f511d2019-06-12 16:55:40 -0700559InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800560 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
561
562InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
563 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700564 : mPolicy(policy),
565 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700566 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800567 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700568 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700569 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700570 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800571 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700572 mDispatchEnabled(false),
573 mDispatchFrozen(false),
574 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100575 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000576 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800577 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800578 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000579 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000580 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700581 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800582 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800583
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700584 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700585#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700586 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700587#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700588 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800589 policy->getDispatcherConfiguration(&mConfig);
590}
591
592InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000593 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800594
Prabir Pradhancef936d2021-07-21 16:17:52 +0000595 resetKeyRepeatLocked();
596 releasePendingEventLocked();
597 drainInboundQueueLocked();
598 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800599
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000600 while (!mConnectionsByToken.empty()) {
601 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000602 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
603 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800604 }
605}
606
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700607status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700608 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700609 return ALREADY_EXISTS;
610 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700611 mThread = std::make_unique<InputThread>(
612 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
613 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700614}
615
616status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700617 if (mThread && mThread->isCallingThread()) {
618 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700619 return INVALID_OPERATION;
620 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700621 mThread.reset();
622 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700623}
624
Michael Wrightd02c5b62014-02-10 15:10:22 -0800625void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700626 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800628 std::scoped_lock _l(mLock);
629 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800630
631 // Run a dispatch loop if there are no pending commands.
632 // The dispatch loop might enqueue commands to run afterwards.
633 if (!haveCommandsLocked()) {
634 dispatchOnceInnerLocked(&nextWakeupTime);
635 }
636
637 // Run all pending commands if there are any.
638 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000639 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700640 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800641 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800642
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700643 // If we are still waiting for ack on some events,
644 // we might have to wake up earlier to check if an app is anr'ing.
645 const nsecs_t nextAnrCheck = processAnrsLocked();
646 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
647
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800648 // We are about to enter an infinitely long sleep, because we have no commands or
649 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700650 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800651 mDispatcherEnteredIdle.notify_all();
652 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800653 } // release lock
654
655 // Wait for callback or timeout or wake. (make sure we round up, not down)
656 nsecs_t currentTime = now();
657 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
658 mLooper->pollOnce(timeoutMillis);
659}
660
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700661/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500662 * Raise ANR if there is no focused window.
663 * Before the ANR is raised, do a final state check:
664 * 1. The currently focused application must be the same one we are waiting for.
665 * 2. Ensure we still don't have a focused window.
666 */
667void InputDispatcher::processNoFocusedWindowAnrLocked() {
668 // Check if the application that we are waiting for is still focused.
669 std::shared_ptr<InputApplicationHandle> focusedApplication =
670 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
671 if (focusedApplication == nullptr ||
672 focusedApplication->getApplicationToken() !=
673 mAwaitedFocusedApplication->getApplicationToken()) {
674 // Unexpected because we should have reset the ANR timer when focused application changed
675 ALOGE("Waited for a focused window, but focused application has already changed to %s",
676 focusedApplication->getName().c_str());
677 return; // The focused application has changed.
678 }
679
chaviw98318de2021-05-19 16:45:23 -0500680 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500681 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
682 if (focusedWindowHandle != nullptr) {
683 return; // We now have a focused window. No need for ANR.
684 }
685 onAnrLocked(mAwaitedFocusedApplication);
686}
687
688/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700689 * Check if any of the connections' wait queues have events that are too old.
690 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
691 * Return the time at which we should wake up next.
692 */
693nsecs_t InputDispatcher::processAnrsLocked() {
694 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700695 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700696 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
697 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
698 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500699 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700700 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500701 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700702 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700703 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500704 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700705 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
706 }
707 }
708
709 // Check if any connection ANRs are due
710 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
711 if (currentTime < nextAnrCheck) { // most likely scenario
712 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
713 }
714
715 // If we reached here, we have an unresponsive connection.
716 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
717 if (connection == nullptr) {
718 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
719 return nextAnrCheck;
720 }
721 connection->responsive = false;
722 // Stop waking up for this unresponsive connection
723 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000724 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700725 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700726}
727
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800728std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
729 const sp<Connection>& connection) {
730 if (connection->monitor) {
731 return mMonitorDispatchingTimeout;
732 }
733 const sp<WindowInfoHandle> window =
734 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700735 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500736 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700737 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500738 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700739}
740
Michael Wrightd02c5b62014-02-10 15:10:22 -0800741void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
742 nsecs_t currentTime = now();
743
Jeff Browndc5992e2014-04-11 01:27:26 -0700744 // Reset the key repeat timer whenever normal dispatch is suspended while the
745 // device is in a non-interactive state. This is to ensure that we abort a key
746 // repeat if the device is just coming out of sleep.
747 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800748 resetKeyRepeatLocked();
749 }
750
751 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
752 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100753 if (DEBUG_FOCUS) {
754 ALOGD("Dispatch frozen. Waiting some more.");
755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756 return;
757 }
758
759 // Optimize latency of app switches.
760 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
761 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
762 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
763 if (mAppSwitchDueTime < *nextWakeupTime) {
764 *nextWakeupTime = mAppSwitchDueTime;
765 }
766
767 // Ready to start a new event.
768 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700769 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700770 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771 if (isAppSwitchDue) {
772 // The inbound queue is empty so the app switch key we were waiting
773 // for will never arrive. Stop waiting for it.
774 resetPendingAppSwitchLocked(false);
775 isAppSwitchDue = false;
776 }
777
778 // Synthesize a key repeat if appropriate.
779 if (mKeyRepeatState.lastKeyEntry) {
780 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
781 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
782 } else {
783 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
784 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
785 }
786 }
787 }
788
789 // Nothing to do if there is no pending event.
790 if (!mPendingEvent) {
791 return;
792 }
793 } else {
794 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700795 mPendingEvent = mInboundQueue.front();
796 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800797 traceInboundQueueLengthLocked();
798 }
799
800 // Poke user activity for this event.
801 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700802 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800803 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804 }
805
806 // Now we have an event to dispatch.
807 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700808 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800809 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700810 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800811 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700812 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700814 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800815 }
816
817 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700818 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819 }
820
821 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700822 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700823 const ConfigurationChangedEntry& typedEntry =
824 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700825 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700826 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700827 break;
828 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800829
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700830 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700831 const DeviceResetEntry& typedEntry =
832 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700833 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700834 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700835 break;
836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100838 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700839 std::shared_ptr<FocusEntry> typedEntry =
840 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100841 dispatchFocusLocked(currentTime, typedEntry);
842 done = true;
843 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
844 break;
845 }
846
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700847 case EventEntry::Type::TOUCH_MODE_CHANGED: {
848 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
849 dispatchTouchModeChangeLocked(currentTime, typedEntry);
850 done = true;
851 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
852 break;
853 }
854
Prabir Pradhan99987712020-11-10 18:43:05 -0800855 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
856 const auto typedEntry =
857 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
858 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
859 done = true;
860 break;
861 }
862
arthurhungb89ccb02020-12-30 16:19:01 +0800863 case EventEntry::Type::DRAG: {
864 std::shared_ptr<DragEntry> typedEntry =
865 std::static_pointer_cast<DragEntry>(mPendingEvent);
866 dispatchDragLocked(currentTime, typedEntry);
867 done = true;
868 break;
869 }
870
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700871 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700872 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700873 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700874 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700875 resetPendingAppSwitchLocked(true);
876 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700877 } else if (dropReason == DropReason::NOT_DROPPED) {
878 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700879 }
880 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700881 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700882 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700883 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700884 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
885 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700886 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700887 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700888 break;
889 }
890
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700891 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700892 std::shared_ptr<MotionEntry> motionEntry =
893 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700894 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
895 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700897 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700898 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700899 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700900 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
901 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700902 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700903 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700904 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 }
Chris Yef59a2f42020-10-16 12:55:26 -0700906
907 case EventEntry::Type::SENSOR: {
908 std::shared_ptr<SensorEntry> sensorEntry =
909 std::static_pointer_cast<SensorEntry>(mPendingEvent);
910 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
911 dropReason = DropReason::APP_SWITCH;
912 }
913 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
914 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
915 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
916 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
917 dropReason = DropReason::STALE;
918 }
919 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
920 done = true;
921 break;
922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 }
924
925 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700926 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700927 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928 }
Michael Wright3a981722015-06-10 15:26:13 +0100929 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930
931 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -0700932 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933 }
934}
935
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800936bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
937 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
938}
939
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700940/**
941 * Return true if the events preceding this incoming motion event should be dropped
942 * Return false otherwise (the default behaviour)
943 */
944bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700945 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700946 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700947
948 // Optimize case where the current application is unresponsive and the user
949 // decides to touch a window in a different application.
950 // If the application takes too long to catch up then we drop all events preceding
951 // the touch into the other window.
952 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -0700953 const int32_t displayId = motionEntry.displayId;
954 const auto [x, y] = resolveTouchedPosition(motionEntry);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700955 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -0700956
chaviw98318de2021-05-19 16:45:23 -0500957 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700958 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700959 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700960 touchedWindowHandle->getApplicationToken() !=
961 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700962 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700963 ALOGI("Pruning input queue because user touched a different application while waiting "
964 "for %s",
965 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700966 return true;
967 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700968
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800969 // Alternatively, maybe there's a spy window that could handle this event.
970 const std::vector<sp<WindowInfoHandle>> touchedSpies =
971 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
972 for (const auto& windowHandle : touchedSpies) {
973 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000974 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800975 // This spy window could take more input. Drop all events preceding this
976 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700977 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800978 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700979 mAwaitedFocusedApplication->getName().c_str());
980 return true;
981 }
982 }
983 }
984
985 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
986 // yet been processed by some connections, the dispatcher will wait for these motion
987 // events to be processed before dispatching the key event. This is because these motion events
988 // may cause a new window to be launched, which the user might expect to receive focus.
989 // To prevent waiting forever for such events, just send the key to the currently focused window
990 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
991 ALOGD("Received a new pointer down event, stop waiting for events to process and "
992 "just send the pending key event to the focused window.");
993 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700994 }
995 return false;
996}
997
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700998bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700999 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001000 mInboundQueue.push_back(std::move(newEntry));
1001 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001002 traceInboundQueueLengthLocked();
1003
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001004 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001005 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001006 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1007 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001008 // Optimize app switch latency.
1009 // If the application takes too long to catch up then we drop all events preceding
1010 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001011 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001012 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001013 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001014 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001015 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001016 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001017 if (DEBUG_APP_SWITCH) {
1018 ALOGD("App switch is pending!");
1019 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001020 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001021 mAppSwitchSawKeyDown = false;
1022 needWake = true;
1023 }
1024 }
1025 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001026
1027 // If a new up event comes in, and the pending event with same key code has been asked
1028 // to try again later because of the policy. We have to reset the intercept key wake up
1029 // time for it may have been handled in the policy and could be dropped.
1030 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1031 mPendingEvent->type == EventEntry::Type::KEY) {
1032 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1033 if (pendingKey.keyCode == keyEntry.keyCode &&
1034 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001035 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1036 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001037 pendingKey.interceptKeyWakeupTime = 0;
1038 needWake = true;
1039 }
1040 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001041 break;
1042 }
1043
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001044 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001045 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1046 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001047 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1048 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001049 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001051 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001052 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001053 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001054 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1055 break;
1056 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001057 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001058 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001059 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001060 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001061 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1062 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001063 // nothing to do
1064 break;
1065 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066 }
1067
1068 return needWake;
1069}
1070
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001071void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001072 // Do not store sensor event in recent queue to avoid flooding the queue.
1073 if (entry->type != EventEntry::Type::SENSOR) {
1074 mRecentQueue.push_back(entry);
1075 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001076 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001077 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078 }
1079}
1080
chaviw98318de2021-05-19 16:45:23 -05001081sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1082 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001083 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001084 bool addOutsideTargets,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07001085 bool ignoreDragWindow) const {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001086 if (addOutsideTargets && touchState == nullptr) {
1087 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001088 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001090 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001091 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001092 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001093 continue;
1094 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001095
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001096 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001097 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001098 return windowHandle;
1099 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001100
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001101 if (addOutsideTargets &&
1102 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001103 touchState->addOrUpdateWindow(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001104 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001105 }
1106 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001107 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001108}
1109
Prabir Pradhand65552b2021-10-07 11:23:50 -07001110std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1111 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001112 // Traverse windows from front to back and gather the touched spy windows.
1113 std::vector<sp<WindowInfoHandle>> spyWindows;
1114 const auto& windowHandles = getWindowHandlesLocked(displayId);
1115 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1116 const WindowInfo& info = *windowHandle->getInfo();
1117
Prabir Pradhand65552b2021-10-07 11:23:50 -07001118 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001119 continue;
1120 }
1121 if (!info.isSpy()) {
1122 // The first touched non-spy window was found, so return the spy windows touched so far.
1123 return spyWindows;
1124 }
1125 spyWindows.push_back(windowHandle);
1126 }
1127 return spyWindows;
1128}
1129
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001130void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131 const char* reason;
1132 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001133 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001134 if (DEBUG_INBOUND_EVENT_DETAILS) {
1135 ALOGD("Dropped event because policy consumed it.");
1136 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001137 reason = "inbound event was dropped because the policy consumed it";
1138 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001139 case DropReason::DISABLED:
1140 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001141 ALOGI("Dropped event because input dispatch is disabled.");
1142 }
1143 reason = "inbound event was dropped because input dispatch is disabled";
1144 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001145 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001146 ALOGI("Dropped event because of pending overdue app switch.");
1147 reason = "inbound event was dropped because of pending overdue app switch";
1148 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001149 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001150 ALOGI("Dropped event because the current application is not responding and the user "
1151 "has started interacting with a different application.");
1152 reason = "inbound event was dropped because the current application is not responding "
1153 "and the user has started interacting with a different application";
1154 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001155 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001156 ALOGI("Dropped event because it is stale.");
1157 reason = "inbound event was dropped because it is stale";
1158 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001159 case DropReason::NO_POINTER_CAPTURE:
1160 ALOGI("Dropped event because there is no window with Pointer Capture.");
1161 reason = "inbound event was dropped because there is no window with Pointer Capture";
1162 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001163 case DropReason::NOT_DROPPED: {
1164 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001165 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001166 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167 }
1168
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001169 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001170 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001171 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001172 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001173 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001175 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001176 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1177 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001178 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001179 synthesizeCancelationEventsForAllConnectionsLocked(options);
1180 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001181 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1182 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001183 synthesizeCancelationEventsForAllConnectionsLocked(options);
1184 }
1185 break;
1186 }
Chris Yef59a2f42020-10-16 12:55:26 -07001187 case EventEntry::Type::SENSOR: {
1188 break;
1189 }
arthurhungb89ccb02020-12-30 16:19:01 +08001190 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1191 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001192 break;
1193 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001194 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001195 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001196 case EventEntry::Type::CONFIGURATION_CHANGED:
1197 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001198 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001199 break;
1200 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 }
1202}
1203
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001204static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001205 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1206 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207}
1208
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001209bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1210 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1211 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1212 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213}
1214
1215bool InputDispatcher::isAppSwitchPendingLocked() {
Colin Cross5b799302022-10-18 21:52:41 -07001216 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217}
1218
1219void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001220 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001222 if (DEBUG_APP_SWITCH) {
1223 if (handled) {
1224 ALOGD("App switch has arrived.");
1225 } else {
1226 ALOGD("App switch was abandoned.");
1227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229}
1230
Michael Wrightd02c5b62014-02-10 15:10:22 -08001231bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001232 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233}
1234
Prabir Pradhancef936d2021-07-21 16:17:52 +00001235bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001236 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 return false;
1238 }
1239
1240 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001241 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001242 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001243 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1244 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001245 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001246 return true;
1247}
1248
Prabir Pradhancef936d2021-07-21 16:17:52 +00001249void InputDispatcher::postCommandLocked(Command&& command) {
1250 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251}
1252
1253void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001254 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001255 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001256 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257 releaseInboundEventLocked(entry);
1258 }
1259 traceInboundQueueLengthLocked();
1260}
1261
1262void InputDispatcher::releasePendingEventLocked() {
1263 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001265 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266 }
1267}
1268
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001269void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001271 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001272 if (DEBUG_DISPATCH_CYCLE) {
1273 ALOGD("Injected inbound event was dropped.");
1274 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001275 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 }
1277 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001278 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 }
1280 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001281}
1282
1283void InputDispatcher::resetKeyRepeatLocked() {
1284 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001285 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286 }
1287}
1288
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001289std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1290 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291
Michael Wright2e732952014-09-24 13:26:59 -07001292 uint32_t policyFlags = entry->policyFlags &
1293 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001295 std::shared_ptr<KeyEntry> newEntry =
1296 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1297 entry->source, entry->displayId, policyFlags, entry->action,
1298 entry->flags, entry->keyCode, entry->scanCode,
1299 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001300
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001301 newEntry->syntheticRepeat = true;
1302 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001304 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001305}
1306
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001307bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001308 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001309 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1310 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001312
1313 // Reset key repeating in case a keyboard device was added or removed or something.
1314 resetKeyRepeatLocked();
1315
1316 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001317 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1318 scoped_unlock unlock(mLock);
1319 mPolicy->notifyConfigurationChanged(eventTime);
1320 };
1321 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 return true;
1323}
1324
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001325bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1326 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001327 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1328 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1329 entry.deviceId);
1330 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331
liushenxiang42232912021-05-21 20:24:09 +08001332 // Reset key repeating in case a keyboard device was disabled or enabled.
1333 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1334 resetKeyRepeatLocked();
1335 }
1336
Michael Wrightfb04fd52022-11-24 22:31:11 +00001337 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001338 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 synthesizeCancelationEventsForAllConnectionsLocked(options);
1340 return true;
1341}
1342
Vishnu Nairad321cd2020-08-20 16:40:21 -07001343void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001344 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001345 if (mPendingEvent != nullptr) {
1346 // Move the pending event to the front of the queue. This will give the chance
1347 // for the pending event to get dispatched to the newly focused window
1348 mInboundQueue.push_front(mPendingEvent);
1349 mPendingEvent = nullptr;
1350 }
1351
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001352 std::unique_ptr<FocusEntry> focusEntry =
1353 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1354 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001355
1356 // This event should go to the front of the queue, but behind all other focus events
1357 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001358 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001359 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001360 [](const std::shared_ptr<EventEntry>& event) {
1361 return event->type == EventEntry::Type::FOCUS;
1362 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001363
1364 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001365 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001366}
1367
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001368void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001369 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001370 if (channel == nullptr) {
1371 return; // Window has gone away
1372 }
1373 InputTarget target;
1374 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001375 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001376 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001377 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1378 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001379 std::string reason = std::string("reason=").append(entry->reason);
1380 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001381 dispatchEventLocked(currentTime, entry, {target});
1382}
1383
Prabir Pradhan99987712020-11-10 18:43:05 -08001384void InputDispatcher::dispatchPointerCaptureChangedLocked(
1385 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1386 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001387 dropReason = DropReason::NOT_DROPPED;
1388
Prabir Pradhan99987712020-11-10 18:43:05 -08001389 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001390 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001391
1392 if (entry->pointerCaptureRequest.enable) {
1393 // Enable Pointer Capture.
1394 if (haveWindowWithPointerCapture &&
1395 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001396 // This can happen if pointer capture is disabled and re-enabled before we notify the
1397 // app of the state change, so there is no need to notify the app.
1398 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1399 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001400 }
1401 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001402 // This can happen if a window requests capture and immediately releases capture.
1403 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001404 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001405 return;
1406 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001407 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1408 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1409 return;
1410 }
1411
Vishnu Nairc519ff72021-01-21 08:23:08 -08001412 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001413 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1414 mWindowTokenWithPointerCapture = token;
1415 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001416 // Disable Pointer Capture.
1417 // We do not check if the sequence number matches for requests to disable Pointer Capture
1418 // for two reasons:
1419 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1420 // to disable capture with the same sequence number: one generated by
1421 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1422 // Capture being disabled in InputReader.
1423 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1424 // actual Pointer Capture state that affects events being generated by input devices is
1425 // in InputReader.
1426 if (!haveWindowWithPointerCapture) {
1427 // Pointer capture was already forcefully disabled because of focus change.
1428 dropReason = DropReason::NOT_DROPPED;
1429 return;
1430 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001431 token = mWindowTokenWithPointerCapture;
1432 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001433 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001434 setPointerCaptureLocked(false);
1435 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001436 }
1437
1438 auto channel = getInputChannelLocked(token);
1439 if (channel == nullptr) {
1440 // Window has gone away, clean up Pointer Capture state.
1441 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001442 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001443 setPointerCaptureLocked(false);
1444 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001445 return;
1446 }
1447 InputTarget target;
1448 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001449 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001450 entry->dispatchInProgress = true;
1451 dispatchEventLocked(currentTime, entry, {target});
1452
1453 dropReason = DropReason::NOT_DROPPED;
1454}
1455
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001456void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1457 const std::shared_ptr<TouchModeEntry>& entry) {
1458 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001459 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001460 if (windowHandles.empty()) {
1461 return;
1462 }
1463 const std::vector<InputTarget> inputTargets =
1464 getInputTargetsFromWindowHandlesLocked(windowHandles);
1465 if (inputTargets.empty()) {
1466 return;
1467 }
1468 entry->dispatchInProgress = true;
1469 dispatchEventLocked(currentTime, entry, inputTargets);
1470}
1471
1472std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1473 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1474 std::vector<InputTarget> inputTargets;
1475 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001476 const sp<IBinder>& token = handle->getToken();
1477 if (token == nullptr) {
1478 continue;
1479 }
1480 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1481 if (channel == nullptr) {
1482 continue; // Window has gone away
1483 }
1484 InputTarget target;
1485 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001486 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001487 inputTargets.push_back(target);
1488 }
1489 return inputTargets;
1490}
1491
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001492bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001493 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001495 if (!entry->dispatchInProgress) {
1496 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1497 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1498 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1499 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001500 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501 // We have seen two identical key downs in a row which indicates that the device
1502 // driver is automatically generating key repeats itself. We take note of the
1503 // repeat here, but we disable our own next key repeat timer since it is clear that
1504 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001505 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1506 // Make sure we don't get key down from a different device. If a different
1507 // device Id has same key pressed down, the new device Id will replace the
1508 // current one to hold the key repeat with repeat count reset.
1509 // In the future when got a KEY_UP on the device id, drop it and do not
1510 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1512 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001513 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 } else {
1515 // Not a repeat. Save key down state in case we do see a repeat later.
1516 resetKeyRepeatLocked();
1517 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1518 }
1519 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001520 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1521 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001522 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001523 if (DEBUG_INBOUND_EVENT_DETAILS) {
1524 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1525 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001526 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527 resetKeyRepeatLocked();
1528 }
1529
1530 if (entry->repeatCount == 1) {
1531 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1532 } else {
1533 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1534 }
1535
1536 entry->dispatchInProgress = true;
1537
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001538 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539 }
1540
1541 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001542 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543 if (currentTime < entry->interceptKeyWakeupTime) {
1544 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1545 *nextWakeupTime = entry->interceptKeyWakeupTime;
1546 }
1547 return false; // wait until next wakeup
1548 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001549 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 entry->interceptKeyWakeupTime = 0;
1551 }
1552
1553 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001554 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001556 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001557 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001558
1559 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1560 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1561 };
1562 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001563 return false; // wait for the command to run
1564 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001565 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001566 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001567 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001568 if (*dropReason == DropReason::NOT_DROPPED) {
1569 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 }
1571 }
1572
1573 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001574 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001575 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001576 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1577 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001578 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579 return true;
1580 }
1581
1582 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001583 InputEventInjectionResult injectionResult;
1584 sp<WindowInfoHandle> focusedWindow =
1585 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1586 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001587 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001588 return false;
1589 }
1590
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001591 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001592 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001593 return true;
1594 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001595 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1596
1597 std::vector<InputTarget> inputTargets;
1598 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001599 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001600 BitSet32(0), getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001601
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001602 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001603 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604
1605 // Dispatch the key.
1606 dispatchEventLocked(currentTime, entry, inputTargets);
1607 return true;
1608}
1609
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001610void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001611 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1612 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1613 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1614 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1615 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1616 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1617 entry.metaState, entry.repeatCount, entry.downTime);
1618 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001619}
1620
Prabir Pradhancef936d2021-07-21 16:17:52 +00001621void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1622 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001623 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001624 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1625 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1626 "source=0x%x, sensorType=%s",
1627 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001628 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001629 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001630 auto command = [this, entry]() REQUIRES(mLock) {
1631 scoped_unlock unlock(mLock);
1632
1633 if (entry->accuracyChanged) {
1634 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1635 }
1636 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1637 entry->hwTimestamp, entry->values);
1638 };
1639 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001640}
1641
1642bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001643 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1644 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001645 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001646 }
Chris Yef59a2f42020-10-16 12:55:26 -07001647 { // acquire lock
1648 std::scoped_lock _l(mLock);
1649
1650 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1651 std::shared_ptr<EventEntry> entry = *it;
1652 if (entry->type == EventEntry::Type::SENSOR) {
1653 it = mInboundQueue.erase(it);
1654 releaseInboundEventLocked(entry);
1655 }
1656 }
1657 }
1658 return true;
1659}
1660
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001661bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001662 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001663 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001665 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 entry->dispatchInProgress = true;
1667
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001668 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 }
1670
1671 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001672 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001673 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001674 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1675 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 return true;
1677 }
1678
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001679 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680
1681 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001682 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683
1684 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001685 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001686 if (isPointerEvent) {
1687 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001688
1689 if (mDragState &&
1690 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1691 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1692 pilferPointersLocked(mDragState->dragWindow->getToken());
1693 }
1694
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001695 std::vector<TouchedWindow> touchedWindows =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001696 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001697 /*byref*/ injectionResult);
1698 for (const TouchedWindow& touchedWindow : touchedWindows) {
1699 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED,
1700 "Shouldn't be adding window if the injection didn't succeed.");
1701 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1702 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
1703 inputTargets);
1704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001705 } else {
1706 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001707 sp<WindowInfoHandle> focusedWindow =
1708 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1709 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1710 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1711 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001712 InputTarget::Flags::FOREGROUND |
1713 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001714 BitSet32(0), getDownTime(*entry), inputTargets);
1715 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001717 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 return false;
1719 }
1720
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001721 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001722 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001723 return true;
1724 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001725 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001726 CancelationOptions::Mode mode(
1727 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1728 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001729 CancelationOptions options(mode, "input event injection failed");
1730 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001731 return true;
1732 }
1733
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001734 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001735 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736
1737 // Dispatch the motion.
1738 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001739 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001740 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741 synthesizeCancelationEventsForAllConnectionsLocked(options);
1742 }
1743 dispatchEventLocked(currentTime, entry, inputTargets);
1744 return true;
1745}
1746
chaviw98318de2021-05-19 16:45:23 -05001747void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001748 bool isExiting, const int32_t rawX,
1749 const int32_t rawY) {
1750 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001751 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001752 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1753 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001754
1755 enqueueInboundEventLocked(std::move(dragEntry));
1756}
1757
1758void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1759 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1760 if (channel == nullptr) {
1761 return; // Window has gone away
1762 }
1763 InputTarget target;
1764 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001765 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001766 entry->dispatchInProgress = true;
1767 dispatchEventLocked(currentTime, entry, {target});
1768}
1769
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001770void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001771 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001772 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001773 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001774 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001775 "metaState=0x%x, buttonState=0x%x,"
1776 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001777 prefix, entry.eventTime, entry.deviceId,
1778 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1779 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1780 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1781 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001783 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1784 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1785 "x=%f, y=%f, pressure=%f, size=%f, "
1786 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1787 "orientation=%f",
1788 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1789 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1790 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1791 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1792 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1793 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1794 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1795 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1796 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1797 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1798 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800}
1801
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001802void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1803 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001804 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001805 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001806 if (DEBUG_DISPATCH_CYCLE) {
1807 ALOGD("dispatchEventToCurrentInputTargets");
1808 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001810 updateInteractionTokensLocked(*eventEntry, inputTargets);
1811
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1813
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001814 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001815
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001816 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001817 sp<Connection> connection =
1818 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001819 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001820 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001822 if (DEBUG_FOCUS) {
1823 ALOGD("Dropping event delivery to target with channel '%s' because it "
1824 "is no longer registered with the input dispatcher.",
1825 inputTarget.inputChannel->getName().c_str());
1826 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 }
1828 }
1829}
1830
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001831void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1832 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1833 // If the policy decides to close the app, we will get a channel removal event via
1834 // unregisterInputChannel, and will clean up the connection that way. We are already not
1835 // sending new pointers to the connection when it blocked, but focused events will continue to
1836 // pile up.
1837 ALOGW("Canceling events for %s because it is unresponsive",
1838 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001839 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001840 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001841 "application not responding");
1842 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843 }
1844}
1845
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001846void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001847 if (DEBUG_FOCUS) {
1848 ALOGD("Resetting ANR timeouts.");
1849 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850
1851 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001852 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001853 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854}
1855
Tiger Huang721e26f2018-07-24 22:26:19 +08001856/**
1857 * Get the display id that the given event should go to. If this event specifies a valid display id,
1858 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1859 * Focused display is the display that the user most recently interacted with.
1860 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001861int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001862 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001863 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001864 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001865 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1866 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001867 break;
1868 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001869 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001870 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1871 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001872 break;
1873 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001874 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001875 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001876 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001877 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001878 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001879 case EventEntry::Type::SENSOR:
1880 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001881 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001882 return ADISPLAY_ID_NONE;
1883 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001884 }
1885 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1886}
1887
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001888bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1889 const char* focusedWindowName) {
1890 if (mAnrTracker.empty()) {
1891 // already processed all events that we waited for
1892 mKeyIsWaitingForEventsTimeout = std::nullopt;
1893 return false;
1894 }
1895
1896 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1897 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001898 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001899 mKeyIsWaitingForEventsTimeout = currentTime +
1900 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1901 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001902 return true;
1903 }
1904
1905 // We still have pending events, and already started the timer
1906 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1907 return true; // Still waiting
1908 }
1909
1910 // Waited too long, and some connection still hasn't processed all motions
1911 // Just send the key to the focused window
1912 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1913 focusedWindowName);
1914 mKeyIsWaitingForEventsTimeout = std::nullopt;
1915 return false;
1916}
1917
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001918sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
1919 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
1920 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001921 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001922 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923
Tiger Huang721e26f2018-07-24 22:26:19 +08001924 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001925 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001926 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001927 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1928
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 // If there is no currently focused window and no focused application
1930 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001931 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1932 ALOGI("Dropping %s event because there is no focused window or focused application in "
1933 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001934 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001935 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936 }
1937
Vishnu Nair062a8672021-09-03 16:07:44 -07001938 // Drop key events if requested by input feature
1939 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001940 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07001941 }
1942
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001943 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1944 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1945 // start interacting with another application via touch (app switch). This code can be removed
1946 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1947 // an app is expected to have a focused window.
1948 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1949 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1950 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001951 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1952 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1953 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001954 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001955 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001956 ALOGW("Waiting because no window has focus but %s may eventually add a "
1957 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001958 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001959 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001960 outInjectionResult = InputEventInjectionResult::PENDING;
1961 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001962 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1963 // Already raised ANR. Drop the event
1964 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001965 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001966 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001967 } else {
1968 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001969 outInjectionResult = InputEventInjectionResult::PENDING;
1970 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001971 }
1972 }
1973
1974 // we have a valid, non-null focused window
1975 resetNoFocusedWindowTimeoutLocked();
1976
Prabir Pradhan5735a322022-04-11 17:23:34 +00001977 // Verify targeted injection.
1978 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
1979 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001980 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
1981 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982 }
1983
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001984 if (focusedWindowHandle->getInfo()->inputConfig.test(
1985 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001986 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001987 outInjectionResult = InputEventInjectionResult::PENDING;
1988 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001989 }
1990
1991 // If the event is a key event, then we must wait for all previous events to
1992 // complete before delivering it because previous events may have the
1993 // side-effect of transferring focus to a different window and we want to
1994 // ensure that the following keys are sent to the new window.
1995 //
1996 // Suppose the user touches a button in a window then immediately presses "A".
1997 // If the button causes a pop-up window to appear then we want to ensure that
1998 // the "A" key is delivered to the new pop-up window. This is because users
1999 // often anticipate pending UI changes when typing on a keyboard.
2000 // To obtain this behavior, we must serialize key events with respect to all
2001 // prior input events.
2002 if (entry.type == EventEntry::Type::KEY) {
2003 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2004 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002005 outInjectionResult = InputEventInjectionResult::PENDING;
2006 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002007 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008 }
2009
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002010 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2011 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012}
2013
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002014/**
2015 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2016 * that are currently unresponsive.
2017 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002018std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2019 const std::vector<Monitor>& monitors) const {
2020 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002021 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002022 [this](const Monitor& monitor) REQUIRES(mLock) {
2023 sp<Connection> connection =
2024 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002025 if (connection == nullptr) {
2026 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002027 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002028 return false;
2029 }
2030 if (!connection->responsive) {
2031 ALOGW("Unresponsive monitor %s will not get the new gesture",
2032 connection->inputChannel->getName().c_str());
2033 return false;
2034 }
2035 return true;
2036 });
2037 return responsiveMonitors;
2038}
2039
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002040/**
2041 * In general, touch should be always split between windows. Some exceptions:
2042 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2043 * from the same device, *and* the window that's receiving the current pointer does not support
2044 * split touch.
2045 * 2. Don't split mouse events
2046 */
2047bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2048 const MotionEntry& entry) const {
2049 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2050 // We should never split mouse events
2051 return false;
2052 }
2053 for (const TouchedWindow& touchedWindow : touchState.windows) {
2054 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2055 // Spy windows should not affect whether or not touch is split.
2056 continue;
2057 }
2058 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2059 continue;
2060 }
2061 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2062 // being sent there. For now, use deviceId from touch state.
2063 if (entry.deviceId == touchState.deviceId && !touchedWindow.pointerIds.isEmpty()) {
2064 return false;
2065 }
2066 }
2067 return true;
2068}
2069
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002070std::vector<TouchedWindow> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002071 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2072 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002073 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002075 std::vector<TouchedWindow> touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076 // For security reasons, we defer updating the touch state until we are sure that
2077 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002078 const int32_t displayId = entry.displayId;
2079 const int32_t action = entry.action;
2080 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002081
2082 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002083 outInjectionResult = InputEventInjectionResult::PENDING;
chaviw98318de2021-05-19 16:45:23 -05002084 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2085 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002086
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002087 // Copy current touch state into tempTouchState.
2088 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2089 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002090 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002091 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002092 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2093 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002094 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002095 }
2096
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002097 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002098 const bool switchedDevice = (oldState != nullptr) &&
2099 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002100
2101 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2102 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2103 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2104 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2105 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002106 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107 if (newGesture) {
2108 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002109 if (switchedDevice && tempTouchState.isDown() && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002110 ALOGI("Dropping event because a pointer for a different device is already down "
2111 "in display %" PRId32,
2112 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002113 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002114 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakouf0ab2c82022-10-25 18:15:28 -07002115 return touchedWindows; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002116 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002117 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002118 tempTouchState.deviceId = entry.deviceId;
2119 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002121 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002122 ALOGI("Dropping move event because a pointer for a different device is already active "
2123 "in display %" PRId32,
2124 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002125 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002126 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakouf0ab2c82022-10-25 18:15:28 -07002127 return touchedWindows; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002128 }
2129
2130 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2131 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002132 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002133 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002134 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002135 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002136 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002137 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002138
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002140 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002141 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2142 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002144 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002145 }
2146
Prabir Pradhan5735a322022-04-11 17:23:34 +00002147 // Verify targeted injection.
2148 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2149 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002150 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002151 newTouchedWindowHandle = nullptr;
2152 goto Failed;
2153 }
2154
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002155 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002156 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002157 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2158 // New window supports splitting, but we should never split mouse events.
2159 isSplit = !isFromMouse;
2160 } else if (isSplit) {
2161 // New window does not support splitting but we have already split events.
2162 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002163 newTouchedWindowHandle = nullptr;
2164 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002165 } else {
2166 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002167 // be delivered to a new window which supports split touch. Pointers from a mouse device
2168 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002169 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002170 }
2171
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002172 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002173 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002174 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2175 newHoverWindowHandle = nullptr;
2176 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002177 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002178 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002179 }
2180
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002181 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002182 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002183 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002184 // Process the foreground window first so that it is the first to receive the event.
2185 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002186 }
2187
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002188 if (newTouchedWindows.empty()) {
2189 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2190 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002191 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002192 goto Failed;
2193 }
2194
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002195 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002196 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002197 continue;
2198 }
2199
2200 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002201 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002202
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002203 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2204 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002205 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002206 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002207
2208 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002209 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002210 }
2211 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002212 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002213 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002214 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002215 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002216
2217 // Update the temporary touch state.
2218 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002219 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002220
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002221 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
2222 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002223 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002224
2225 // If any existing window is pilfering pointers from newly added window, remove it
2226 BitSet32 canceledPointers = BitSet32(0);
2227 for (const TouchedWindow& window : tempTouchState.windows) {
2228 if (window.isPilferingPointers) {
2229 canceledPointers |= window.pointerIds;
2230 }
2231 }
2232 tempTouchState.cancelPointersForNonPilferingWindows(canceledPointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233 } else {
2234 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2235
2236 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002237 if (!tempTouchState.isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002238 ALOGD_IF(DEBUG_FOCUS,
2239 "Dropping event because the pointer is not down or we previously "
2240 "dropped the pointer down event in display %" PRId32 ": %s",
2241 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002242 outInjectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243 goto Failed;
2244 }
2245
arthurhung6d4bed92021-03-17 11:59:33 +08002246 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002247
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002249 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002250 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002251 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07002252 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002253 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002254 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002255 newTouchedWindowHandle =
2256 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002257
Prabir Pradhan5735a322022-04-11 17:23:34 +00002258 // Verify targeted injection.
2259 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2260 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002261 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002262 newTouchedWindowHandle = nullptr;
2263 goto Failed;
2264 }
2265
Vishnu Nair062a8672021-09-03 16:07:44 -07002266 // Drop touch events if requested by input feature
2267 if (newTouchedWindowHandle != nullptr &&
2268 shouldDropInput(entry, newTouchedWindowHandle)) {
2269 newTouchedWindowHandle = nullptr;
2270 }
2271
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002272 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2273 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002274 if (DEBUG_FOCUS) {
2275 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2276 oldTouchedWindowHandle->getName().c_str(),
2277 newTouchedWindowHandle->getName().c_str(), displayId);
2278 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002280 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002281 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002282 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283
2284 // Make a slippery entrance into the new window.
2285 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002286 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002287 }
2288
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002289 ftl::Flags<InputTarget::Flags> targetFlags =
2290 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002291 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002292 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002293 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002295 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296 }
2297 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002298 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002299 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002300 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 }
2302
2303 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002304 pointerIds.markBit(entry.pointerProperties[0].id);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002305 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2306 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002307 }
2308 }
Arthur Hung96483742022-11-15 03:30:48 +00002309
2310 // Update the pointerIds for non-splittable when it received pointer down.
2311 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2312 // If no split, we suppose all touched windows should receive pointer down.
2313 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2314 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2315 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2316 // Ignore drag window for it should just track one pointer.
2317 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2318 continue;
2319 }
2320 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2321 }
2322 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323 }
2324
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002325 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002327 // Let the previous window know that the hover sequence is over, unless we already did
2328 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002329 if (mLastHoverWindowHandle != nullptr &&
2330 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2331 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002332 if (DEBUG_HOVER) {
2333 ALOGD("Sending hover exit event to window %s.",
2334 mLastHoverWindowHandle->getName().c_str());
2335 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002336 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002337 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT,
2338 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339 }
2340
Garfield Tandf26e862020-07-01 20:18:19 -07002341 // Let the new window know that the hover sequence is starting, unless we already did it
2342 // when dispatching it as is to newTouchedWindowHandle.
2343 if (newHoverWindowHandle != nullptr &&
2344 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2345 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002346 if (DEBUG_HOVER) {
2347 ALOGD("Sending hover enter event to window %s.",
2348 newHoverWindowHandle->getName().c_str());
2349 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002350 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002351 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002352 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353 }
2354 }
2355
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002356 // Ensure that we have at least one foreground window or at least one window that cannot be a
2357 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2358 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2359 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002360 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2361 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002362 return !canReceiveForegroundTouches(
2363 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002364 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002365 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002366 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2367 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002368 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002369 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370 }
2371
Prabir Pradhan5735a322022-04-11 17:23:34 +00002372 // Ensure that all touched windows are valid for injection.
2373 if (entry.injectionState != nullptr) {
2374 std::string errs;
2375 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002376 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002377 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2378 // dispatched to any uid, since the coords will be zeroed out later.
2379 continue;
2380 }
2381 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2382 if (err) errs += "\n - " + *err;
2383 }
2384 if (!errs.empty()) {
2385 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2386 "%d:%s",
2387 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002388 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002389 goto Failed;
2390 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002391 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002392
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393 // Check whether windows listening for outside touches are owned by the same UID. If it is
2394 // set the policy flag that we will not reveal coordinate information to this window.
2395 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002396 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002397 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002398 if (foregroundWindowHandle) {
2399 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002400 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002401 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
chaviw98318de2021-05-19 16:45:23 -05002402 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2403 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2404 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002405 InputTarget::Flags::ZERO_COORDS,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002406 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002407 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002408 }
2409 }
2410 }
2411 }
2412
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413 // If this is the first pointer going down and the touched window has a wallpaper
2414 // then also add the touched wallpaper windows so they are locked in for the duration
2415 // of the touch gesture.
2416 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2417 // engine only supports touch events. We would need to add a mechanism similar
2418 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2419 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002420 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002421 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002422 if (foregroundWindowHandle &&
2423 foregroundWindowHandle->getInfo()->inputConfig.test(
2424 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002425 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002426 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002427 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2428 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002429 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002430 windowHandle->getInfo()->inputConfig.test(
2431 WindowInfo::InputConfig::IS_WALLPAPER)) {
Arthur Hung74c248d2022-11-23 07:09:59 +00002432 BitSet32 pointerIds;
2433 pointerIds.markBit(entry.pointerProperties[0].id);
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002434 tempTouchState.addOrUpdateWindow(windowHandle,
2435 InputTarget::Flags::WINDOW_IS_OBSCURED |
2436 InputTarget::Flags::
2437 WINDOW_IS_PARTIALLY_OBSCURED |
2438 InputTarget::Flags::DISPATCH_AS_IS,
Arthur Hung74c248d2022-11-23 07:09:59 +00002439 pointerIds, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440 }
2441 }
2442 }
2443 }
2444
2445 // Success! Output targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002446 touchedWindows = tempTouchState.windows;
2447 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448
2449 // Drop the outside or hover touch windows since we will not care about them
2450 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002451 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452
2453Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002454 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002455 if (switchedDevice) {
2456 if (DEBUG_FOCUS) {
2457 ALOGD("Conflicting pointer actions: Switched to a different device.");
2458 }
2459 *outConflictingPointerActions = true;
2460 }
2461
2462 if (isHoverAction) {
2463 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002464 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002465 ALOGD_IF(DEBUG_FOCUS,
2466 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002467 *outConflictingPointerActions = true;
2468 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002469 tempTouchState.reset();
2470 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2471 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2472 tempTouchState.deviceId = entry.deviceId;
2473 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002474 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002475 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2476 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2477 // All pointers up or canceled.
2478 tempTouchState.reset();
2479 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2480 // First pointer went down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002481 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002482 ALOGD("Conflicting pointer actions: Down received while already down.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002483 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002484 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002485 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2486 // One pointer went up.
2487 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2488 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002490 for (size_t i = 0; i < tempTouchState.windows.size();) {
2491 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2492 touchedWindow.pointerIds.clearBit(pointerId);
2493 if (touchedWindow.pointerIds.isEmpty()) {
2494 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2495 continue;
2496 }
2497 i += 1;
2498 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002499 }
2500
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002501 // Save changes unless the action was scroll in which case the temporary touch
2502 // state was only valid for this one action.
2503 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002504 if (displayId >= 0) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002505 mTouchStatesByDisplay[displayId] = tempTouchState;
2506 } else {
2507 mTouchStatesByDisplay.erase(displayId);
2508 }
2509 }
2510
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002511 if (tempTouchState.windows.empty()) {
2512 mTouchStatesByDisplay.erase(displayId);
2513 }
2514
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002515 // Update hover state.
2516 mLastHoverWindowHandle = newHoverWindowHandle;
2517
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002518 return touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002519}
2520
arthurhung6d4bed92021-03-17 11:59:33 +08002521void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002522 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2523 // have an explicit reason to support it.
2524 constexpr bool isStylus = false;
2525
chaviw98318de2021-05-19 16:45:23 -05002526 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002527 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002528 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002529 if (dropWindow) {
2530 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002531 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002532 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002533 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002534 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002535 }
2536 mDragState.reset();
2537}
2538
2539void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002540 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002541 return;
2542 }
2543
arthurhung6d4bed92021-03-17 11:59:33 +08002544 if (!mDragState->isStartDrag) {
2545 mDragState->isStartDrag = true;
2546 mDragState->isStylusButtonDownAtStart =
2547 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2548 }
2549
Arthur Hung54745652022-04-20 07:17:41 +00002550 // Find the pointer index by id.
2551 int32_t pointerIndex = 0;
2552 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2553 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2554 if (pointerProperties.id == mDragState->pointerId) {
2555 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002556 }
Arthur Hung54745652022-04-20 07:17:41 +00002557 }
arthurhung6d4bed92021-03-17 11:59:33 +08002558
Arthur Hung54745652022-04-20 07:17:41 +00002559 if (uint32_t(pointerIndex) == entry.pointerCount) {
2560 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002561 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002562 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002563 return;
2564 }
2565
2566 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2567 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2568 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2569
2570 switch (maskedAction) {
2571 case AMOTION_EVENT_ACTION_MOVE: {
2572 // Handle the special case : stylus button no longer pressed.
2573 bool isStylusButtonDown =
2574 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2575 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2576 finishDragAndDrop(entry.displayId, x, y);
2577 return;
2578 }
2579
2580 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2581 // until we have an explicit reason to support it.
2582 constexpr bool isStylus = false;
2583
2584 const sp<WindowInfoHandle> hoverWindowHandle =
2585 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2586 isStylus, false /*addOutsideTargets*/,
2587 true /*ignoreDragWindow*/);
2588 // enqueue drag exit if needed.
2589 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2590 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2591 if (mDragState->dragHoverWindowHandle != nullptr) {
2592 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2593 y);
2594 }
2595 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2596 }
2597 // enqueue drag location if needed.
2598 if (hoverWindowHandle != nullptr) {
2599 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2600 }
2601 break;
2602 }
2603
2604 case AMOTION_EVENT_ACTION_POINTER_UP:
2605 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2606 break;
2607 }
2608 // The drag pointer is up.
2609 [[fallthrough]];
2610 case AMOTION_EVENT_ACTION_UP:
2611 finishDragAndDrop(entry.displayId, x, y);
2612 break;
2613 case AMOTION_EVENT_ACTION_CANCEL: {
2614 ALOGD("Receiving cancel when drag and drop.");
2615 sendDropWindowCommandLocked(nullptr, 0, 0);
2616 mDragState.reset();
2617 break;
2618 }
arthurhungb89ccb02020-12-30 16:19:01 +08002619 }
2620}
2621
chaviw98318de2021-05-19 16:45:23 -05002622void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002623 ftl::Flags<InputTarget::Flags> targetFlags,
2624 BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002625 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002626 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002627 std::vector<InputTarget>::iterator it =
2628 std::find_if(inputTargets.begin(), inputTargets.end(),
2629 [&windowHandle](const InputTarget& inputTarget) {
2630 return inputTarget.inputChannel->getConnectionToken() ==
2631 windowHandle->getToken();
2632 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002633
chaviw98318de2021-05-19 16:45:23 -05002634 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002635
2636 if (it == inputTargets.end()) {
2637 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002638 std::shared_ptr<InputChannel> inputChannel =
2639 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002640 if (inputChannel == nullptr) {
2641 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2642 return;
2643 }
2644 inputTarget.inputChannel = inputChannel;
2645 inputTarget.flags = targetFlags;
2646 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002647 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002648 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2649 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002650 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002651 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002652 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002653 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002654 inputTargets.push_back(inputTarget);
2655 it = inputTargets.end() - 1;
2656 }
2657
2658 ALOG_ASSERT(it->flags == targetFlags);
2659 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2660
chaviw1ff3d1e2020-07-01 15:53:47 -07002661 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002662}
2663
Michael Wright3dd60e22019-03-27 22:06:44 +00002664void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002665 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002666 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2667 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002668
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002669 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2670 InputTarget target;
2671 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002672 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002673 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2674 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002675 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2676 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002677 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002678 target.setDefaultPointerTransform(target.displayTransform);
2679 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680 }
2681}
2682
Robert Carrc9bf1d32020-04-13 17:21:08 -07002683/**
2684 * Indicate whether one window handle should be considered as obscuring
2685 * another window handle. We only check a few preconditions. Actually
2686 * checking the bounds is left to the caller.
2687 */
chaviw98318de2021-05-19 16:45:23 -05002688static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2689 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002690 // Compare by token so cloned layers aren't counted
2691 if (haveSameToken(windowHandle, otherHandle)) {
2692 return false;
2693 }
2694 auto info = windowHandle->getInfo();
2695 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002696 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002697 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002698 } else if (otherInfo->alpha == 0 &&
2699 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002700 // Those act as if they were invisible, so we don't need to flag them.
2701 // We do want to potentially flag touchable windows even if they have 0
2702 // opacity, since they can consume touches and alter the effects of the
2703 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002704 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002705 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2706 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002707 } else if (info->ownerUid == otherInfo->ownerUid) {
2708 // If ownerUid is the same we don't generate occlusion events as there
2709 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002710 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002711 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002712 return false;
2713 } else if (otherInfo->displayId != info->displayId) {
2714 return false;
2715 }
2716 return true;
2717}
2718
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002719/**
2720 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2721 * untrusted, one should check:
2722 *
2723 * 1. If result.hasBlockingOcclusion is true.
2724 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2725 * BLOCK_UNTRUSTED.
2726 *
2727 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2728 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2729 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2730 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2731 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2732 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2733 *
2734 * If neither of those is true, then it means the touch can be allowed.
2735 */
2736InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002737 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2738 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002739 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002740 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002741 TouchOcclusionInfo info;
2742 info.hasBlockingOcclusion = false;
2743 info.obscuringOpacity = 0;
2744 info.obscuringUid = -1;
2745 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002746 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002747 if (windowHandle == otherHandle) {
2748 break; // All future windows are below us. Exit early.
2749 }
chaviw98318de2021-05-19 16:45:23 -05002750 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002751 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2752 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002753 if (DEBUG_TOUCH_OCCLUSION) {
2754 info.debugInfo.push_back(
2755 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2756 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002757 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2758 // we perform the checks below to see if the touch can be propagated or not based on the
2759 // window's touch occlusion mode
2760 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2761 info.hasBlockingOcclusion = true;
2762 info.obscuringUid = otherInfo->ownerUid;
2763 info.obscuringPackage = otherInfo->packageName;
2764 break;
2765 }
2766 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2767 uint32_t uid = otherInfo->ownerUid;
2768 float opacity =
2769 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2770 // Given windows A and B:
2771 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2772 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2773 opacityByUid[uid] = opacity;
2774 if (opacity > info.obscuringOpacity) {
2775 info.obscuringOpacity = opacity;
2776 info.obscuringUid = uid;
2777 info.obscuringPackage = otherInfo->packageName;
2778 }
2779 }
2780 }
2781 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002782 if (DEBUG_TOUCH_OCCLUSION) {
2783 info.debugInfo.push_back(
2784 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2785 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002786 return info;
2787}
2788
chaviw98318de2021-05-19 16:45:23 -05002789std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002790 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002791 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2792 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2793 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2794 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002795 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2796 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2797 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2798 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2799 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002800 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002801 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002802}
2803
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002804bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2805 if (occlusionInfo.hasBlockingOcclusion) {
2806 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2807 occlusionInfo.obscuringUid);
2808 return false;
2809 }
2810 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2811 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2812 "%.2f, maximum allowed = %.2f)",
2813 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2814 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2815 return false;
2816 }
2817 return true;
2818}
2819
chaviw98318de2021-05-19 16:45:23 -05002820bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002821 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002823 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2824 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002825 if (windowHandle == otherHandle) {
2826 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002827 }
chaviw98318de2021-05-19 16:45:23 -05002828 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002829 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002830 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002831 return true;
2832 }
2833 }
2834 return false;
2835}
2836
chaviw98318de2021-05-19 16:45:23 -05002837bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002838 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002839 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2840 const WindowInfo* windowInfo = windowHandle->getInfo();
2841 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002842 if (windowHandle == otherHandle) {
2843 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002844 }
chaviw98318de2021-05-19 16:45:23 -05002845 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002846 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002847 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002848 return true;
2849 }
2850 }
2851 return false;
2852}
2853
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002854std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002855 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002856 if (applicationHandle != nullptr) {
2857 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002858 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002859 } else {
2860 return applicationHandle->getName();
2861 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002862 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002863 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002865 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866 }
2867}
2868
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002869void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002870 if (!isUserActivityEvent(eventEntry)) {
2871 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002872 return;
2873 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002874 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002875 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002876 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002877 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002878 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002879 if (DEBUG_DISPATCH_CYCLE) {
2880 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882 return;
2883 }
2884 }
2885
2886 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002887 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002888 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002889 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2890 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002891 return;
2892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002894 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002895 eventType = USER_ACTIVITY_EVENT_TOUCH;
2896 }
2897 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002898 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002899 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002900 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2901 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002902 return;
2903 }
2904 eventType = USER_ACTIVITY_EVENT_BUTTON;
2905 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002906 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002907 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002908 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002909 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002910 break;
2911 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002912 }
2913
Prabir Pradhancef936d2021-07-21 16:17:52 +00002914 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2915 REQUIRES(mLock) {
2916 scoped_unlock unlock(mLock);
2917 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2918 };
2919 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920}
2921
2922void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002923 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002924 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002925 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002926 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002927 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002928 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002929 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002930 ATRACE_NAME(message.c_str());
2931 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002932 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002933 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002934 "globalScaleFactor=%f, pointerIds=0x%x %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002935 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002936 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2937 inputTarget.getPointerInfoString().c_str());
2938 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002939
2940 // Skip this event if the connection status is not normal.
2941 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002942 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002943 if (DEBUG_DISPATCH_CYCLE) {
2944 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002945 connection->getInputChannelName().c_str(),
2946 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002948 return;
2949 }
2950
2951 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002952 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002953 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002954 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002955 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002956
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002957 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002958 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002959 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
2960 "Splitting motion events requires a down time to be set for the "
2961 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002962 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002963 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
2964 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002965 if (!splitMotionEntry) {
2966 return; // split event was dropped
2967 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002968 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2969 std::string reason = std::string("reason=pointer cancel on split window");
2970 android_log_event_list(LOGTAG_INPUT_CANCEL)
2971 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2972 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002973 if (DEBUG_FOCUS) {
2974 ALOGD("channel '%s' ~ Split motion event.",
2975 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002976 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002977 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002978 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2979 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002980 return;
2981 }
2982 }
2983
2984 // Not splitting. Enqueue dispatch entries for the event as is.
2985 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2986}
2987
2988void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002989 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002990 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002991 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002992 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002993 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002994 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002995 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002996 ATRACE_NAME(message.c_str());
2997 }
2998
hongzuo liu95785e22022-09-06 02:51:35 +00002999 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003000
3001 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003002 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003003 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003004 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003005 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003006 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003007 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003008 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003009 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003010 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003011 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003012 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003013 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014
3015 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003016 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017 startDispatchCycleLocked(currentTime, connection);
3018 }
3019}
3020
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003021void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003022 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003023 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003024 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003025 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003026 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3027 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003028 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003029 ATRACE_NAME(message.c_str());
3030 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003031 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3032 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033 return;
3034 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003035
3036 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3037 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038
3039 // This is a new event.
3040 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003041 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003042 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003043
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003044 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3045 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003046 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003048 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003049 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003050 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003051 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003052 dispatchEntry->resolvedAction = keyEntry.action;
3053 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003055 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3056 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003057 if (DEBUG_DISPATCH_CYCLE) {
3058 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3059 "event",
3060 connection->getInputChannelName().c_str());
3061 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003062 return; // skip the inconsistent event
3063 }
3064 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003065 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003067 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003068 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003069 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3070 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3071 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3072 static_cast<int32_t>(IdGenerator::Source::OTHER);
3073 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003074 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003075 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003076 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003077 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003078 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003079 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003080 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003081 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003082 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003083 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3084 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003085 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003086 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003087 }
3088 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003089 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3090 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003091 if (DEBUG_DISPATCH_CYCLE) {
3092 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3093 "enter event",
3094 connection->getInputChannelName().c_str());
3095 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003096 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3097 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003098 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3099 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003101 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003102 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003103 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3104 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003105 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003106 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3107 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003108
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003109 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3110 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003111 if (DEBUG_DISPATCH_CYCLE) {
3112 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3113 "event",
3114 connection->getInputChannelName().c_str());
3115 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003116 return; // skip the inconsistent event
3117 }
3118
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003119 dispatchEntry->resolvedEventId =
3120 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3121 ? mIdGenerator.nextId()
3122 : motionEntry.id;
3123 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3124 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3125 ") to MotionEvent(id=0x%" PRIx32 ").",
3126 motionEntry.id, dispatchEntry->resolvedEventId);
3127 ATRACE_NAME(message.c_str());
3128 }
3129
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003130 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3131 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3132 // Skip reporting pointer down outside focus to the policy.
3133 break;
3134 }
3135
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003136 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003137 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003138
3139 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003140 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003141 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003142 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003143 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3144 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003145 break;
3146 }
Chris Yef59a2f42020-10-16 12:55:26 -07003147 case EventEntry::Type::SENSOR: {
3148 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3149 break;
3150 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003151 case EventEntry::Type::CONFIGURATION_CHANGED:
3152 case EventEntry::Type::DEVICE_RESET: {
3153 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003154 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003155 break;
3156 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 }
3158
3159 // Remember that we are waiting for this dispatch to complete.
3160 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003161 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162 }
3163
3164 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003165 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003166 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003167}
3168
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003169/**
3170 * This function is purely for debugging. It helps us understand where the user interaction
3171 * was taking place. For example, if user is touching launcher, we will see a log that user
3172 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3173 * We will see both launcher and wallpaper in that list.
3174 * Once the interaction with a particular set of connections starts, no new logs will be printed
3175 * until the set of interacted connections changes.
3176 *
3177 * The following items are skipped, to reduce the logspam:
3178 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3179 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3180 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3181 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3182 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003183 */
3184void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3185 const std::vector<InputTarget>& targets) {
3186 // Skip ACTION_UP events, and all events other than keys and motions
3187 if (entry.type == EventEntry::Type::KEY) {
3188 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3189 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3190 return;
3191 }
3192 } else if (entry.type == EventEntry::Type::MOTION) {
3193 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3194 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3195 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3196 return;
3197 }
3198 } else {
3199 return; // Not a key or a motion
3200 }
3201
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003202 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003203 std::vector<sp<Connection>> newConnections;
3204 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003205 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003206 continue; // Skip windows that receive ACTION_OUTSIDE
3207 }
3208
3209 sp<IBinder> token = target.inputChannel->getConnectionToken();
3210 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003211 if (connection == nullptr) {
3212 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003213 }
3214 newConnectionTokens.insert(std::move(token));
3215 newConnections.emplace_back(connection);
3216 }
3217 if (newConnectionTokens == mInteractionConnectionTokens) {
3218 return; // no change
3219 }
3220 mInteractionConnectionTokens = newConnectionTokens;
3221
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003222 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003223 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003224 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003225 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003226 std::string message = "Interaction with: " + targetList;
3227 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003228 message += "<none>";
3229 }
3230 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3231}
3232
chaviwfd6d3512019-03-25 13:23:49 -07003233void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003234 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003235 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003236 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3237 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003238 return;
3239 }
3240
Vishnu Nairc519ff72021-01-21 08:23:08 -08003241 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003242 if (focusedToken == token) {
3243 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003244 return;
3245 }
3246
Prabir Pradhancef936d2021-07-21 16:17:52 +00003247 auto command = [this, token]() REQUIRES(mLock) {
3248 scoped_unlock unlock(mLock);
3249 mPolicy->onPointerDownOutsideFocus(token);
3250 };
3251 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003252}
3253
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003254status_t InputDispatcher::publishMotionEvent(Connection& connection,
3255 DispatchEntry& dispatchEntry) const {
3256 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3257 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3258
3259 PointerCoords scaledCoords[MAX_POINTERS];
3260 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3261
3262 // Set the X and Y offset and X and Y scale depending on the input source.
3263 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003264 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003265 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3266 if (globalScaleFactor != 1.0f) {
3267 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3268 scaledCoords[i] = motionEntry.pointerCoords[i];
3269 // Don't apply window scale here since we don't want scale to affect raw
3270 // coordinates. The scale will be sent back to the client and applied
3271 // later when requesting relative coordinates.
3272 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3273 1 /* windowYScale */);
3274 }
3275 usingCoords = scaledCoords;
3276 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003277 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003278 // We don't want the dispatch target to know the coordinates
3279 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3280 scaledCoords[i].clear();
3281 }
3282 usingCoords = scaledCoords;
3283 }
3284
3285 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3286
3287 // Publish the motion event.
3288 return connection.inputPublisher
3289 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3290 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3291 std::move(hmac), dispatchEntry.resolvedAction,
3292 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3293 motionEntry.edgeFlags, motionEntry.metaState,
3294 motionEntry.buttonState, motionEntry.classification,
3295 dispatchEntry.transform, motionEntry.xPrecision,
3296 motionEntry.yPrecision, motionEntry.xCursorPosition,
3297 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3298 motionEntry.downTime, motionEntry.eventTime,
3299 motionEntry.pointerCount, motionEntry.pointerProperties,
3300 usingCoords);
3301}
3302
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003304 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003305 if (ATRACE_ENABLED()) {
3306 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003307 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003308 ATRACE_NAME(message.c_str());
3309 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003310 if (DEBUG_DISPATCH_CYCLE) {
3311 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3312 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003313
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003314 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003315 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003316 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003317 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003318 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319
3320 // Publish the event.
3321 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003322 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3323 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003324 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003325 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3326 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003328 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003329 status = connection->inputPublisher
3330 .publishKeyEvent(dispatchEntry->seq,
3331 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3332 keyEntry.source, keyEntry.displayId,
3333 std::move(hmac), dispatchEntry->resolvedAction,
3334 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3335 keyEntry.scanCode, keyEntry.metaState,
3336 keyEntry.repeatCount, keyEntry.downTime,
3337 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003338 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003339 }
3340
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003341 case EventEntry::Type::MOTION: {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003342 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003343 break;
3344 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003345
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003346 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003347 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003348 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003349 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003350 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003351 break;
3352 }
3353
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003354 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3355 const TouchModeEntry& touchModeEntry =
3356 static_cast<const TouchModeEntry&>(eventEntry);
3357 status = connection->inputPublisher
3358 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3359 touchModeEntry.inTouchMode);
3360
3361 break;
3362 }
3363
Prabir Pradhan99987712020-11-10 18:43:05 -08003364 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3365 const auto& captureEntry =
3366 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3367 status = connection->inputPublisher
3368 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003369 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003370 break;
3371 }
3372
arthurhungb89ccb02020-12-30 16:19:01 +08003373 case EventEntry::Type::DRAG: {
3374 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3375 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3376 dragEntry.id, dragEntry.x,
3377 dragEntry.y,
3378 dragEntry.isExiting);
3379 break;
3380 }
3381
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003382 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003383 case EventEntry::Type::DEVICE_RESET:
3384 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003385 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003386 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003387 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003389 }
3390
3391 // Check the result.
3392 if (status) {
3393 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003394 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003395 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003396 "This is unexpected because the wait queue is empty, so the pipe "
3397 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003398 "event to it, status=%s(%d)",
3399 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3400 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3402 } else {
3403 // Pipe is full and we are waiting for the app to finish process some events
3404 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003405 if (DEBUG_DISPATCH_CYCLE) {
3406 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3407 "waiting for the application to catch up",
3408 connection->getInputChannelName().c_str());
3409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 }
3411 } else {
3412 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003413 "status=%s(%d)",
3414 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3415 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3417 }
3418 return;
3419 }
3420
3421 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003422 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3423 connection->outboundQueue.end(),
3424 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003425 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003426 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003427 if (connection->responsive) {
3428 mAnrTracker.insert(dispatchEntry->timeoutTime,
3429 connection->inputChannel->getConnectionToken());
3430 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003431 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432 }
3433}
3434
chaviw09c8d2d2020-08-24 15:48:26 -07003435std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3436 size_t size;
3437 switch (event.type) {
3438 case VerifiedInputEvent::Type::KEY: {
3439 size = sizeof(VerifiedKeyEvent);
3440 break;
3441 }
3442 case VerifiedInputEvent::Type::MOTION: {
3443 size = sizeof(VerifiedMotionEvent);
3444 break;
3445 }
3446 }
3447 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3448 return mHmacKeyManager.sign(start, size);
3449}
3450
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003451const std::array<uint8_t, 32> InputDispatcher::getSignature(
3452 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003453 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3454 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003455 // Only sign events up and down events as the purely move events
3456 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003457 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003458 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003459
3460 VerifiedMotionEvent verifiedEvent =
3461 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3462 verifiedEvent.actionMasked = actionMasked;
3463 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3464 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003465}
3466
3467const std::array<uint8_t, 32> InputDispatcher::getSignature(
3468 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3469 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3470 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3471 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003472 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003473}
3474
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003476 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003477 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003478 if (DEBUG_DISPATCH_CYCLE) {
3479 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3480 connection->getInputChannelName().c_str(), seq, toString(handled));
3481 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003483 if (connection->status == Connection::Status::BROKEN ||
3484 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003485 return;
3486 }
3487
3488 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003489 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3490 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3491 };
3492 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003493}
3494
3495void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003496 const sp<Connection>& connection,
3497 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003498 if (DEBUG_DISPATCH_CYCLE) {
3499 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3500 connection->getInputChannelName().c_str(), toString(notify));
3501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502
3503 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003504 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003505 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003506 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003507 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508
3509 // The connection appears to be unrecoverably broken.
3510 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003511 if (connection->status == Connection::Status::NORMAL) {
3512 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513
3514 if (notify) {
3515 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003516 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3517 connection->getInputChannelName().c_str());
3518
3519 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003520 scoped_unlock unlock(mLock);
3521 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3522 };
3523 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003524 }
3525 }
3526}
3527
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003528void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3529 while (!queue.empty()) {
3530 DispatchEntry* dispatchEntry = queue.front();
3531 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003532 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533 }
3534}
3535
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003536void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003537 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003538 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003539 }
3540 delete dispatchEntry;
3541}
3542
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003543int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3544 std::scoped_lock _l(mLock);
3545 sp<Connection> connection = getConnectionLocked(connectionToken);
3546 if (connection == nullptr) {
3547 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3548 connectionToken.get(), events);
3549 return 0; // remove the callback
3550 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003552 bool notify;
3553 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3554 if (!(events & ALOOPER_EVENT_INPUT)) {
3555 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3556 "events=0x%x",
3557 connection->getInputChannelName().c_str(), events);
3558 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559 }
3560
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003561 nsecs_t currentTime = now();
3562 bool gotOne = false;
3563 status_t status = OK;
3564 for (;;) {
3565 Result<InputPublisher::ConsumerResponse> result =
3566 connection->inputPublisher.receiveConsumerResponse();
3567 if (!result.ok()) {
3568 status = result.error().code();
3569 break;
3570 }
3571
3572 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3573 const InputPublisher::Finished& finish =
3574 std::get<InputPublisher::Finished>(*result);
3575 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3576 finish.consumeTime);
3577 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003578 if (shouldReportMetricsForConnection(*connection)) {
3579 const InputPublisher::Timeline& timeline =
3580 std::get<InputPublisher::Timeline>(*result);
3581 mLatencyTracker
3582 .trackGraphicsLatency(timeline.inputEventId,
3583 connection->inputChannel->getConnectionToken(),
3584 std::move(timeline.graphicsTimeline));
3585 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003586 }
3587 gotOne = true;
3588 }
3589 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003590 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003591 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592 return 1;
3593 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594 }
3595
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003596 notify = status != DEAD_OBJECT || !connection->monitor;
3597 if (notify) {
3598 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3599 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3600 status);
3601 }
3602 } else {
3603 // Monitor channels are never explicitly unregistered.
3604 // We do it automatically when the remote endpoint is closed so don't warn about them.
3605 const bool stillHaveWindowHandle =
3606 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3607 notify = !connection->monitor && stillHaveWindowHandle;
3608 if (notify) {
3609 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3610 connection->getInputChannelName().c_str(), events);
3611 }
3612 }
3613
3614 // Remove the channel.
3615 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3616 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617}
3618
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003619void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003621 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003622 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623 }
3624}
3625
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003626void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003627 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003628 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003629 for (const Monitor& monitor : monitors) {
3630 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003631 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003632 }
3633}
3634
Michael Wrightd02c5b62014-02-10 15:10:22 -08003635void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003636 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003637 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003638 if (connection == nullptr) {
3639 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003640 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003641
3642 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643}
3644
3645void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3646 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003647 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648 return;
3649 }
3650
3651 nsecs_t currentTime = now();
3652
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003653 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003654 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003655
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003656 if (cancelationEvents.empty()) {
3657 return;
3658 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003659 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3660 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3661 "with reality: %s, mode=%d.",
3662 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3663 options.mode);
3664 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003665
Arthur Hungb3307ee2021-10-14 10:57:37 +00003666 std::string reason = std::string("reason=").append(options.reason);
3667 android_log_event_list(LOGTAG_INPUT_CANCEL)
3668 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3669
Svet Ganov5d3bc372020-01-26 23:11:07 -08003670 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003671 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003672 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3673 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003674 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003675 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003676 target.globalScaleFactor = windowInfo->globalScaleFactor;
3677 }
3678 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003679 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003680
hongzuo liu95785e22022-09-06 02:51:35 +00003681 const bool wasEmpty = connection->outboundQueue.empty();
3682
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003683 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003684 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003685 switch (cancelationEventEntry->type) {
3686 case EventEntry::Type::KEY: {
3687 logOutboundKeyDetails("cancel - ",
3688 static_cast<const KeyEntry&>(*cancelationEventEntry));
3689 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003691 case EventEntry::Type::MOTION: {
3692 logOutboundMotionDetails("cancel - ",
3693 static_cast<const MotionEntry&>(*cancelationEventEntry));
3694 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003695 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003696 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003697 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003698 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3699 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003700 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003701 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003702 break;
3703 }
3704 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003705 case EventEntry::Type::DEVICE_RESET:
3706 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003707 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003708 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003709 break;
3710 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711 }
3712
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003713 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003714 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003716
hongzuo liu95785e22022-09-06 02:51:35 +00003717 // If the outbound queue was previously empty, start the dispatch cycle going.
3718 if (wasEmpty && !connection->outboundQueue.empty()) {
3719 startDispatchCycleLocked(currentTime, connection);
3720 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003721}
3722
Svet Ganov5d3bc372020-01-26 23:11:07 -08003723void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003724 const nsecs_t downTime, const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003725 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003726 return;
3727 }
3728
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003729 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003730 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003731
3732 if (downEvents.empty()) {
3733 return;
3734 }
3735
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003736 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003737 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3738 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003739 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003740
3741 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003742 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003743 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3744 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003745 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003746 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003747 target.globalScaleFactor = windowInfo->globalScaleFactor;
3748 }
3749 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003750 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003751
hongzuo liu95785e22022-09-06 02:51:35 +00003752 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003753 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003754 switch (downEventEntry->type) {
3755 case EventEntry::Type::MOTION: {
3756 logOutboundMotionDetails("down - ",
3757 static_cast<const MotionEntry&>(*downEventEntry));
3758 break;
3759 }
3760
3761 case EventEntry::Type::KEY:
3762 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003763 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003764 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003765 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003766 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003767 case EventEntry::Type::SENSOR:
3768 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003769 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003770 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003771 break;
3772 }
3773 }
3774
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003775 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003776 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003777 }
3778
hongzuo liu95785e22022-09-06 02:51:35 +00003779 // If the outbound queue was previously empty, start the dispatch cycle going.
3780 if (wasEmpty && !connection->outboundQueue.empty()) {
3781 startDispatchCycleLocked(downTime, connection);
3782 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003783}
3784
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003785std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003786 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787 ALOG_ASSERT(pointerIds.value != 0);
3788
3789 uint32_t splitPointerIndexMap[MAX_POINTERS];
3790 PointerProperties splitPointerProperties[MAX_POINTERS];
3791 PointerCoords splitPointerCoords[MAX_POINTERS];
3792
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003793 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794 uint32_t splitPointerCount = 0;
3795
3796 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003797 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003798 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003799 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800 uint32_t pointerId = uint32_t(pointerProperties.id);
3801 if (pointerIds.hasBit(pointerId)) {
3802 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3803 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3804 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003805 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806 splitPointerCount += 1;
3807 }
3808 }
3809
3810 if (splitPointerCount != pointerIds.count()) {
3811 // This is bad. We are missing some of the pointers that we expected to deliver.
3812 // Most likely this indicates that we received an ACTION_MOVE events that has
3813 // different pointer ids than we expected based on the previous ACTION_DOWN
3814 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3815 // in this way.
3816 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003817 "we expected there to be %d pointers. This probably means we received "
3818 "a broken sequence of pointer ids from the input device.",
3819 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003820 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003821 }
3822
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003823 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003825 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3826 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003827 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3828 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003829 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003830 uint32_t pointerId = uint32_t(pointerProperties.id);
3831 if (pointerIds.hasBit(pointerId)) {
3832 if (pointerIds.count() == 1) {
3833 // The first/last pointer went down/up.
3834 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003835 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003836 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3837 ? AMOTION_EVENT_ACTION_CANCEL
3838 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839 } else {
3840 // A secondary pointer went down/up.
3841 uint32_t splitPointerIndex = 0;
3842 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3843 splitPointerIndex += 1;
3844 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003845 action = maskedAction |
3846 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003847 }
3848 } else {
3849 // An unrelated pointer changed.
3850 action = AMOTION_EVENT_ACTION_MOVE;
3851 }
3852 }
3853
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003854 if (action == AMOTION_EVENT_ACTION_DOWN) {
3855 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3856 "Split motion event has mismatching downTime and eventTime for "
3857 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3858 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3859 }
3860
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003861 int32_t newId = mIdGenerator.nextId();
3862 if (ATRACE_ENABLED()) {
3863 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3864 ") to MotionEvent(id=0x%" PRIx32 ").",
3865 originalMotionEntry.id, newId);
3866 ATRACE_NAME(message.c_str());
3867 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003868 std::unique_ptr<MotionEntry> splitMotionEntry =
3869 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3870 originalMotionEntry.deviceId, originalMotionEntry.source,
3871 originalMotionEntry.displayId,
3872 originalMotionEntry.policyFlags, action,
3873 originalMotionEntry.actionButton,
3874 originalMotionEntry.flags, originalMotionEntry.metaState,
3875 originalMotionEntry.buttonState,
3876 originalMotionEntry.classification,
3877 originalMotionEntry.edgeFlags,
3878 originalMotionEntry.xPrecision,
3879 originalMotionEntry.yPrecision,
3880 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003881 originalMotionEntry.yCursorPosition, splitDownTime,
3882 splitPointerCount, splitPointerProperties,
3883 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003885 if (originalMotionEntry.injectionState) {
3886 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887 splitMotionEntry->injectionState->refCount += 1;
3888 }
3889
3890 return splitMotionEntry;
3891}
3892
3893void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003894 if (DEBUG_INBOUND_EVENT_DETAILS) {
3895 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897
Antonio Kantekf16f2832021-09-28 04:39:20 +00003898 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003900 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003902 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3903 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3904 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905 } // release lock
3906
3907 if (needWake) {
3908 mLooper->wake();
3909 }
3910}
3911
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003912/**
3913 * If one of the meta shortcuts is detected, process them here:
3914 * Meta + Backspace -> generate BACK
3915 * Meta + Enter -> generate HOME
3916 * This will potentially overwrite keyCode and metaState.
3917 */
3918void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003919 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003920 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3921 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3922 if (keyCode == AKEYCODE_DEL) {
3923 newKeyCode = AKEYCODE_BACK;
3924 } else if (keyCode == AKEYCODE_ENTER) {
3925 newKeyCode = AKEYCODE_HOME;
3926 }
3927 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003928 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003929 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003930 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003931 keyCode = newKeyCode;
3932 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3933 }
3934 } else if (action == AKEY_EVENT_ACTION_UP) {
3935 // In order to maintain a consistent stream of up and down events, check to see if the key
3936 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3937 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003938 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003939 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003940 auto replacementIt = mReplacedKeys.find(replacement);
3941 if (replacementIt != mReplacedKeys.end()) {
3942 keyCode = replacementIt->second;
3943 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003944 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3945 }
3946 }
3947}
3948
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003950 if (DEBUG_INBOUND_EVENT_DETAILS) {
3951 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3952 "policyFlags=0x%x, action=0x%x, "
3953 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3954 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3955 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3956 args->downTime);
3957 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003958 if (!validateKeyEvent(args->action)) {
3959 return;
3960 }
3961
3962 uint32_t policyFlags = args->policyFlags;
3963 int32_t flags = args->flags;
3964 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003965 // InputDispatcher tracks and generates key repeats on behalf of
3966 // whatever notifies it, so repeatCount should always be set to 0
3967 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3969 policyFlags |= POLICY_FLAG_VIRTUAL;
3970 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3971 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972 if (policyFlags & POLICY_FLAG_FUNCTION) {
3973 metaState |= AMETA_FUNCTION_ON;
3974 }
3975
3976 policyFlags |= POLICY_FLAG_TRUSTED;
3977
Michael Wright78f24442014-08-06 15:55:28 -07003978 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003979 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003980
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003982 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003983 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3984 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985
Michael Wright2b3c3302018-03-02 17:19:13 +00003986 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003988 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3989 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003990 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003991 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992
Antonio Kantekf16f2832021-09-28 04:39:20 +00003993 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003994 { // acquire lock
3995 mLock.lock();
3996
3997 if (shouldSendKeyToInputFilterLocked(args)) {
3998 mLock.unlock();
3999
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004000 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004001 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4002 return; // event was consumed by the filter
4003 }
4004
4005 mLock.lock();
4006 }
4007
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004008 std::unique_ptr<KeyEntry> newEntry =
4009 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4010 args->displayId, policyFlags, args->action, flags,
4011 keyCode, args->scanCode, metaState, repeatCount,
4012 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004013
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004014 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004015 mLock.unlock();
4016 } // release lock
4017
4018 if (needWake) {
4019 mLooper->wake();
4020 }
4021}
4022
4023bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4024 return mInputFilterEnabled;
4025}
4026
4027void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004028 if (DEBUG_INBOUND_EVENT_DETAILS) {
4029 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4030 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004031 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004032 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4033 "yCursorPosition=%f, downTime=%" PRId64,
4034 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004035 args->policyFlags, MotionEvent::actionToString(args->action).c_str(),
4036 args->actionButton, args->flags, args->metaState, args->buttonState, args->edgeFlags,
4037 args->xPrecision, args->yPrecision, args->xCursorPosition, args->yCursorPosition,
4038 args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004039 for (uint32_t i = 0; i < args->pointerCount; i++) {
4040 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4041 "x=%f, y=%f, pressure=%f, size=%f, "
4042 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4043 "orientation=%f",
4044 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4045 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4046 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4047 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4048 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4049 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4050 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4051 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4052 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4053 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004056 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4057 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058 return;
4059 }
4060
4061 uint32_t policyFlags = args->policyFlags;
4062 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004063
4064 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004065 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004066 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4067 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004068 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004069 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070
Antonio Kantekf16f2832021-09-28 04:39:20 +00004071 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072 { // acquire lock
4073 mLock.lock();
4074
4075 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004076 ui::Transform displayTransform;
4077 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4078 displayTransform = it->second.transform;
4079 }
4080
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081 mLock.unlock();
4082
4083 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004084 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4085 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004086 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004087 displayTransform, args->xPrecision, args->yPrecision,
4088 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004089 args->downTime, args->eventTime, args->pointerCount,
4090 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091
4092 policyFlags |= POLICY_FLAG_FILTERED;
4093 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4094 return; // event was consumed by the filter
4095 }
4096
4097 mLock.lock();
4098 }
4099
4100 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004101 std::unique_ptr<MotionEntry> newEntry =
4102 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4103 args->source, args->displayId, policyFlags,
4104 args->action, args->actionButton, args->flags,
4105 args->metaState, args->buttonState,
4106 args->classification, args->edgeFlags,
4107 args->xPrecision, args->yPrecision,
4108 args->xCursorPosition, args->yCursorPosition,
4109 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004110 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004112 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4113 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4114 !mInputFilterEnabled) {
4115 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4116 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4117 }
4118
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004119 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120 mLock.unlock();
4121 } // release lock
4122
4123 if (needWake) {
4124 mLooper->wake();
4125 }
4126}
4127
Chris Yef59a2f42020-10-16 12:55:26 -07004128void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004129 if (DEBUG_INBOUND_EVENT_DETAILS) {
4130 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4131 " sensorType=%s",
4132 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004133 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004134 }
Chris Yef59a2f42020-10-16 12:55:26 -07004135
Antonio Kantekf16f2832021-09-28 04:39:20 +00004136 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004137 { // acquire lock
4138 mLock.lock();
4139
4140 // Just enqueue a new sensor event.
4141 std::unique_ptr<SensorEntry> newEntry =
4142 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4143 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4144 args->sensorType, args->accuracy,
4145 args->accuracyChanged, args->values);
4146
4147 needWake = enqueueInboundEventLocked(std::move(newEntry));
4148 mLock.unlock();
4149 } // release lock
4150
4151 if (needWake) {
4152 mLooper->wake();
4153 }
4154}
4155
Chris Yefb552902021-02-03 17:18:37 -08004156void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004157 if (DEBUG_INBOUND_EVENT_DETAILS) {
4158 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4159 args->deviceId, args->isOn);
4160 }
Chris Yefb552902021-02-03 17:18:37 -08004161 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4162}
4163
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004165 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166}
4167
4168void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004169 if (DEBUG_INBOUND_EVENT_DETAILS) {
4170 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4171 "switchMask=0x%08x",
4172 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174
4175 uint32_t policyFlags = args->policyFlags;
4176 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004177 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178}
4179
4180void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004181 if (DEBUG_INBOUND_EVENT_DETAILS) {
4182 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4183 args->deviceId);
4184 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185
Antonio Kantekf16f2832021-09-28 04:39:20 +00004186 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004188 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004190 std::unique_ptr<DeviceResetEntry> newEntry =
4191 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4192 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193 } // release lock
4194
4195 if (needWake) {
4196 mLooper->wake();
4197 }
4198}
4199
Prabir Pradhan7e186182020-11-10 13:56:45 -08004200void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004201 if (DEBUG_INBOUND_EVENT_DETAILS) {
4202 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004203 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004204 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004205
Antonio Kantekf16f2832021-09-28 04:39:20 +00004206 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004207 { // acquire lock
4208 std::scoped_lock _l(mLock);
4209 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004210 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004211 needWake = enqueueInboundEventLocked(std::move(entry));
4212 } // release lock
4213
4214 if (needWake) {
4215 mLooper->wake();
4216 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004217}
4218
Prabir Pradhan5735a322022-04-11 17:23:34 +00004219InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4220 std::optional<int32_t> targetUid,
4221 InputEventInjectionSync syncMode,
4222 std::chrono::milliseconds timeout,
4223 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004224 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004225 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4226 "policyFlags=0x%08x",
4227 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4228 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004229 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004230 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231
Prabir Pradhan5735a322022-04-11 17:23:34 +00004232 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004234 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004235 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4236 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4237 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4238 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4239 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004240 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004241 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004242 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004243 }
4244
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004245 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004246 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004247 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004248 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4249 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004250 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004251 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004254 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004255 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4256 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4257 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004258 int32_t keyCode = incomingKey.getKeyCode();
4259 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004260 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004261 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004262 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004263 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004264 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4265 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4266 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004268 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4269 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004270 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004271
4272 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4273 android::base::Timer t;
4274 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4275 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4276 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4277 std::to_string(t.duration().count()).c_str());
4278 }
4279 }
4280
4281 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004282 std::unique_ptr<KeyEntry> injectedEntry =
4283 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004284 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004285 incomingKey.getDisplayId(), policyFlags, action,
4286 flags, keyCode, incomingKey.getScanCode(), metaState,
4287 incomingKey.getRepeatCount(),
4288 incomingKey.getDownTime());
4289 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004290 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291 }
4292
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004293 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004294 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004295 const int32_t action = motionEvent.getAction();
4296 const bool isPointerEvent =
4297 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4298 // If a pointer event has no displayId specified, inject it to the default display.
4299 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4300 ? ADISPLAY_ID_DEFAULT
4301 : event->getDisplayId();
4302 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004303 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004304 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004305 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004306 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004307 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004308 }
4309
4310 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004311 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004312 android::base::Timer t;
4313 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4314 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4315 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4316 std::to_string(t.duration().count()).c_str());
4317 }
4318 }
4319
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004320 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4321 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4322 }
4323
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004324 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004325 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4326 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004327 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004328 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4329 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004330 displayId, policyFlags, action, actionButton,
4331 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004332 motionEvent.getButtonState(),
4333 motionEvent.getClassification(),
4334 motionEvent.getEdgeFlags(),
4335 motionEvent.getXPrecision(),
4336 motionEvent.getYPrecision(),
4337 motionEvent.getRawXCursorPosition(),
4338 motionEvent.getRawYCursorPosition(),
4339 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004340 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004341 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004342 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004343 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004344 sampleEventTimes += 1;
4345 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004346 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004347 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4348 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004349 displayId, policyFlags, action, actionButton,
4350 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004351 motionEvent.getButtonState(),
4352 motionEvent.getClassification(),
4353 motionEvent.getEdgeFlags(),
4354 motionEvent.getXPrecision(),
4355 motionEvent.getYPrecision(),
4356 motionEvent.getRawXCursorPosition(),
4357 motionEvent.getRawYCursorPosition(),
4358 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004359 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004360 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004361 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4362 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004363 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004364 }
4365 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004368 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004369 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004370 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371 }
4372
Prabir Pradhan5735a322022-04-11 17:23:34 +00004373 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004374 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375 injectionState->injectionIsAsync = true;
4376 }
4377
4378 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004379 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380
4381 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004382 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004383 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004384 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385 }
4386
4387 mLock.unlock();
4388
4389 if (needWake) {
4390 mLooper->wake();
4391 }
4392
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004393 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004394 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004395 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004397 if (syncMode == InputEventInjectionSync::NONE) {
4398 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399 } else {
4400 for (;;) {
4401 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004402 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403 break;
4404 }
4405
4406 nsecs_t remainingTimeout = endTime - now();
4407 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004408 if (DEBUG_INJECTION) {
4409 ALOGD("injectInputEvent - Timed out waiting for injection result "
4410 "to become available.");
4411 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004412 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004413 break;
4414 }
4415
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004416 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417 }
4418
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004419 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4420 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004422 if (DEBUG_INJECTION) {
4423 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4424 injectionState->pendingForegroundDispatches);
4425 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004426 nsecs_t remainingTimeout = endTime - now();
4427 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004428 if (DEBUG_INJECTION) {
4429 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4430 "dispatches to finish.");
4431 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004432 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433 break;
4434 }
4435
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004436 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437 }
4438 }
4439 }
4440
4441 injectionState->release();
4442 } // release lock
4443
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004444 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004445 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447
4448 return injectionResult;
4449}
4450
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004451std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004452 std::array<uint8_t, 32> calculatedHmac;
4453 std::unique_ptr<VerifiedInputEvent> result;
4454 switch (event.getType()) {
4455 case AINPUT_EVENT_TYPE_KEY: {
4456 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4457 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4458 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004459 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004460 break;
4461 }
4462 case AINPUT_EVENT_TYPE_MOTION: {
4463 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4464 VerifiedMotionEvent verifiedMotionEvent =
4465 verifiedMotionEventFromMotionEvent(motionEvent);
4466 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004467 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004468 break;
4469 }
4470 default: {
4471 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4472 return nullptr;
4473 }
4474 }
4475 if (calculatedHmac == INVALID_HMAC) {
4476 return nullptr;
4477 }
4478 if (calculatedHmac != event.getHmac()) {
4479 return nullptr;
4480 }
4481 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004482}
4483
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004484void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004485 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004486 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004487 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004488 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004489 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004490 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004491
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004492 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493 // Log the outcome since the injector did not wait for the injection result.
4494 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004495 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004496 ALOGV("Asynchronous input event injection succeeded.");
4497 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004498 case InputEventInjectionResult::TARGET_MISMATCH:
4499 ALOGV("Asynchronous input event injection target mismatch.");
4500 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004501 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004502 ALOGW("Asynchronous input event injection failed.");
4503 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004504 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004505 ALOGW("Asynchronous input event injection timed out.");
4506 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004507 case InputEventInjectionResult::PENDING:
4508 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4509 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510 }
4511 }
4512
4513 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004514 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004515 }
4516}
4517
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004518void InputDispatcher::transformMotionEntryForInjectionLocked(
4519 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004520 // Input injection works in the logical display coordinate space, but the input pipeline works
4521 // display space, so we need to transform the injected events accordingly.
4522 const auto it = mDisplayInfos.find(entry.displayId);
4523 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004524 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004525
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004526 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4527 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4528 const vec2 cursor =
4529 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4530 {entry.xCursorPosition, entry.yCursorPosition});
4531 entry.xCursorPosition = cursor.x;
4532 entry.yCursorPosition = cursor.y;
4533 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004534 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004535 entry.pointerCoords[i] =
4536 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4537 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004538 }
4539}
4540
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004541void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4542 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543 if (injectionState) {
4544 injectionState->pendingForegroundDispatches += 1;
4545 }
4546}
4547
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004548void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4549 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004550 if (injectionState) {
4551 injectionState->pendingForegroundDispatches -= 1;
4552
4553 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004554 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004555 }
4556 }
4557}
4558
chaviw98318de2021-05-19 16:45:23 -05004559const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004560 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004561 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004562 auto it = mWindowHandlesByDisplay.find(displayId);
4563 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004564}
4565
chaviw98318de2021-05-19 16:45:23 -05004566sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004567 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004568 if (windowHandleToken == nullptr) {
4569 return nullptr;
4570 }
4571
Arthur Hungb92218b2018-08-14 12:00:21 +08004572 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004573 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4574 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004575 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004576 return windowHandle;
4577 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004578 }
4579 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004580 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581}
4582
chaviw98318de2021-05-19 16:45:23 -05004583sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4584 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004585 if (windowHandleToken == nullptr) {
4586 return nullptr;
4587 }
4588
chaviw98318de2021-05-19 16:45:23 -05004589 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004590 if (windowHandle->getToken() == windowHandleToken) {
4591 return windowHandle;
4592 }
4593 }
4594 return nullptr;
4595}
4596
chaviw98318de2021-05-19 16:45:23 -05004597sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4598 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004599 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004600 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4601 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004602 if (handle->getId() == windowHandle->getId() &&
4603 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004604 if (windowHandle->getInfo()->displayId != it.first) {
4605 ALOGE("Found window %s in display %" PRId32
4606 ", but it should belong to display %" PRId32,
4607 windowHandle->getName().c_str(), it.first,
4608 windowHandle->getInfo()->displayId);
4609 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004610 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004611 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004612 }
4613 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004614 return nullptr;
4615}
4616
chaviw98318de2021-05-19 16:45:23 -05004617sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004618 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4619 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004620}
4621
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004622bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4623 const MotionEntry& motionEntry) const {
4624 const WindowInfo& info = *window->getInfo();
4625
4626 // Skip spy window targets that are not valid for targeted injection.
4627 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004628 return false;
4629 }
4630
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004631 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4632 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4633 return false;
4634 }
4635
4636 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4637 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4638 window->getName().c_str());
4639 return false;
4640 }
4641
4642 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004643 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004644 ALOGW("Not sending touch to %s because there's no corresponding connection",
4645 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004646 return false;
4647 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004648
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004649 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004650 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004651 return false;
4652 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004653
4654 // Drop events that can't be trusted due to occlusion
4655 const auto [x, y] = resolveTouchedPosition(motionEntry);
4656 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4657 if (!isTouchTrustedLocked(occlusionInfo)) {
4658 if (DEBUG_TOUCH_OCCLUSION) {
4659 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4660 for (const auto& log : occlusionInfo.debugInfo) {
4661 ALOGD("%s", log.c_str());
4662 }
4663 }
4664 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4665 occlusionInfo.obscuringUid);
4666 return false;
4667 }
4668
4669 // Drop touch events if requested by input feature
4670 if (shouldDropInput(motionEntry, window)) {
4671 return false;
4672 }
4673
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004674 return true;
4675}
4676
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004677std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4678 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004679 auto connectionIt = mConnectionsByToken.find(token);
4680 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004681 return nullptr;
4682 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004683 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004684}
4685
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004686void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004687 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4688 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004689 // Remove all handles on a display if there are no windows left.
4690 mWindowHandlesByDisplay.erase(displayId);
4691 return;
4692 }
4693
4694 // Since we compare the pointer of input window handles across window updates, we need
4695 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004696 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4697 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4698 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004699 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004700 }
4701
chaviw98318de2021-05-19 16:45:23 -05004702 std::vector<sp<WindowInfoHandle>> newHandles;
4703 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004704 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004705 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004706 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004707 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004708 const bool canReceiveInput =
4709 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4710 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004711 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004712 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004713 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004714 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004715 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004716 }
4717
4718 if (info->displayId != displayId) {
4719 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4720 handle->getName().c_str(), displayId, info->displayId);
4721 continue;
4722 }
4723
Robert Carredd13602020-04-13 17:24:34 -07004724 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4725 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004726 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004727 oldHandle->updateFrom(handle);
4728 newHandles.push_back(oldHandle);
4729 } else {
4730 newHandles.push_back(handle);
4731 }
4732 }
4733
4734 // Insert or replace
4735 mWindowHandlesByDisplay[displayId] = newHandles;
4736}
4737
Arthur Hung72d8dc32020-03-28 00:48:39 +00004738void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004739 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004740 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004741 { // acquire lock
4742 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004743 for (const auto& [displayId, handles] : handlesPerDisplay) {
4744 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004745 }
4746 }
4747 // Wake up poll loop since it may need to make new input dispatching choices.
4748 mLooper->wake();
4749}
4750
Arthur Hungb92218b2018-08-14 12:00:21 +08004751/**
4752 * Called from InputManagerService, update window handle list by displayId that can receive input.
4753 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4754 * If set an empty list, remove all handles from the specific display.
4755 * For focused handle, check if need to change and send a cancel event to previous one.
4756 * For removed handle, check if need to send a cancel event if already in touch.
4757 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004758void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004759 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004760 if (DEBUG_FOCUS) {
4761 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004762 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004763 windowList += iwh->getName() + " ";
4764 }
4765 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4766 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004767
Prabir Pradhand65552b2021-10-07 11:23:50 -07004768 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004769 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004770 const WindowInfo& info = *window->getInfo();
4771
4772 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004773 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004774 if (noInputWindow && window->getToken() != nullptr) {
4775 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4776 window->getName().c_str());
4777 window->releaseChannel();
4778 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004779
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004780 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004781 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4782 !info.inputConfig.test(
4783 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004784 "%s has feature SPY, but is not a trusted overlay.",
4785 window->getName().c_str());
4786
Prabir Pradhand65552b2021-10-07 11:23:50 -07004787 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004788 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4789 !info.inputConfig.test(
4790 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004791 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4792 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004793 }
4794
Arthur Hung72d8dc32020-03-28 00:48:39 +00004795 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004796 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004798 // Save the old windows' orientation by ID before it gets updated.
4799 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004800 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004801 oldWindowOrientations.emplace(handle->getId(),
4802 handle->getInfo()->transform.getOrientation());
4803 }
4804
chaviw98318de2021-05-19 16:45:23 -05004805 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004806
chaviw98318de2021-05-19 16:45:23 -05004807 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02004808 if (mLastHoverWindowHandle) {
4809 const WindowInfo* lastHoverWindowInfo = mLastHoverWindowHandle->getInfo();
4810 if (lastHoverWindowInfo->displayId == displayId &&
4811 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4812 windowHandles.end()) {
4813 mLastHoverWindowHandle = nullptr;
4814 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004815 }
4816
Vishnu Nairc519ff72021-01-21 08:23:08 -08004817 std::optional<FocusResolver::FocusChanges> changes =
4818 mFocusResolver.setInputWindows(displayId, windowHandles);
4819 if (changes) {
4820 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004821 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004822
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004823 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4824 mTouchStatesByDisplay.find(displayId);
4825 if (stateIt != mTouchStatesByDisplay.end()) {
4826 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004827 for (size_t i = 0; i < state.windows.size();) {
4828 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004829 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004830 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004831 ALOGD("Touched window was removed: %s in display %" PRId32,
4832 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004833 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004834 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004835 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4836 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004837 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00004838 "touched window was removed");
4839 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004840 // Since we are about to drop the touch, cancel the events for the wallpaper as
4841 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004842 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004843 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4844 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004845 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4846 if (wallpaper != nullptr) {
4847 sp<Connection> wallpaperConnection =
4848 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004849 if (wallpaperConnection != nullptr) {
4850 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4851 options);
4852 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004853 }
4854 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004856 state.windows.erase(state.windows.begin() + i);
4857 } else {
4858 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004859 }
4860 }
arthurhungb89ccb02020-12-30 16:19:01 +08004861
arthurhung6d4bed92021-03-17 11:59:33 +08004862 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004863 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004864 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004865 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004866 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004867 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4868 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004869 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004870 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004871 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004872
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004873 // Determine if the orientation of any of the input windows have changed, and cancel all
4874 // pointer events if necessary.
4875 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4876 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4877 if (newWindowHandle != nullptr &&
4878 newWindowHandle->getInfo()->transform.getOrientation() !=
4879 oldWindowOrientations[oldWindowHandle->getId()]) {
4880 std::shared_ptr<InputChannel> inputChannel =
4881 getInputChannelLocked(newWindowHandle->getToken());
4882 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004883 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004884 "touched window's orientation changed");
4885 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004886 }
4887 }
4888 }
4889
Arthur Hung72d8dc32020-03-28 00:48:39 +00004890 // Release information for windows that are no longer present.
4891 // This ensures that unused input channels are released promptly.
4892 // Otherwise, they might stick around until the window handle is destroyed
4893 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004894 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004895 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004896 if (DEBUG_FOCUS) {
4897 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004898 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004899 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004900 }
chaviw291d88a2019-02-14 10:33:58 -08004901 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004902}
4903
4904void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004905 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004906 if (DEBUG_FOCUS) {
4907 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4908 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4909 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004910 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004911 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004912 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004913 } // release lock
4914
4915 // Wake up poll loop since it may need to make new input dispatching choices.
4916 mLooper->wake();
4917}
4918
Vishnu Nair599f1412021-06-21 10:39:58 -07004919void InputDispatcher::setFocusedApplicationLocked(
4920 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4921 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4922 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4923
4924 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4925 return; // This application is already focused. No need to wake up or change anything.
4926 }
4927
4928 // Set the new application handle.
4929 if (inputApplicationHandle != nullptr) {
4930 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4931 } else {
4932 mFocusedApplicationHandlesByDisplay.erase(displayId);
4933 }
4934
4935 // No matter what the old focused application was, stop waiting on it because it is
4936 // no longer focused.
4937 resetNoFocusedWindowTimeoutLocked();
4938}
4939
Tiger Huang721e26f2018-07-24 22:26:19 +08004940/**
4941 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4942 * the display not specified.
4943 *
4944 * We track any unreleased events for each window. If a window loses the ability to receive the
4945 * released event, we will send a cancel event to it. So when the focused display is changed, we
4946 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4947 * display. The display-specified events won't be affected.
4948 */
4949void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004950 if (DEBUG_FOCUS) {
4951 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4952 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004953 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004954 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004955
4956 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004957 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004958 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004959 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004960 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004961 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004962 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004963 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00004964 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004965 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004966 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004967 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4968 }
4969 }
4970 mFocusedDisplayId = displayId;
4971
Chris Ye3c2d6f52020-08-09 10:39:48 -07004972 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004973 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004974 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004975
Vishnu Nairad321cd2020-08-20 16:40:21 -07004976 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004977 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004978 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004979 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004980 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004981 }
4982 }
4983 }
4984
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004985 if (DEBUG_FOCUS) {
4986 logDispatchStateLocked();
4987 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004988 } // release lock
4989
4990 // Wake up poll loop since it may need to make new input dispatching choices.
4991 mLooper->wake();
4992}
4993
Michael Wrightd02c5b62014-02-10 15:10:22 -08004994void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004995 if (DEBUG_FOCUS) {
4996 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4997 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004998
4999 bool changed;
5000 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005001 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005002
5003 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5004 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005005 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005006 }
5007
5008 if (mDispatchEnabled && !enabled) {
5009 resetAndDropEverythingLocked("dispatcher is being disabled");
5010 }
5011
5012 mDispatchEnabled = enabled;
5013 mDispatchFrozen = frozen;
5014 changed = true;
5015 } else {
5016 changed = false;
5017 }
5018
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005019 if (DEBUG_FOCUS) {
5020 logDispatchStateLocked();
5021 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005022 } // release lock
5023
5024 if (changed) {
5025 // Wake up poll loop since it may need to make new input dispatching choices.
5026 mLooper->wake();
5027 }
5028}
5029
5030void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005031 if (DEBUG_FOCUS) {
5032 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5033 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005034
5035 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005036 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005037
5038 if (mInputFilterEnabled == enabled) {
5039 return;
5040 }
5041
5042 mInputFilterEnabled = enabled;
5043 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5044 } // release lock
5045
5046 // Wake up poll loop since there might be work to do to drop everything.
5047 mLooper->wake();
5048}
5049
Antonio Kanteka042c022022-07-06 16:51:07 -07005050bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5051 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005052 bool needWake = false;
5053 {
5054 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005055 ALOGD_IF(DEBUG_TOUCH_MODE,
5056 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5057 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5058 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5059 mTouchModePerDisplay.count(displayId) == 0
5060 ? "not set"
5061 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5062
Antonio Kantek15beb512022-06-13 22:35:41 +00005063 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5064 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005065 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005066 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005067 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005068 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5069 !recentWindowsAreOwnedByLocked(pid, uid)) {
5070 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5071 "window nor none of the previously interacted window",
5072 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005073 return false;
5074 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005075 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005076 mTouchModePerDisplay[displayId] = inTouchMode;
5077 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5078 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005079 needWake = enqueueInboundEventLocked(std::move(entry));
5080 } // release lock
5081
5082 if (needWake) {
5083 mLooper->wake();
5084 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005085 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005086}
5087
Antonio Kantek48710e42022-03-24 14:19:30 -07005088bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5089 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5090 if (focusedToken == nullptr) {
5091 return false;
5092 }
5093 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5094 return isWindowOwnedBy(windowHandle, pid, uid);
5095}
5096
5097bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5098 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5099 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5100 const sp<WindowInfoHandle> windowHandle =
5101 getWindowHandleLocked(connectionToken);
5102 return isWindowOwnedBy(windowHandle, pid, uid);
5103 }) != mInteractionConnectionTokens.end();
5104}
5105
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005106void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5107 if (opacity < 0 || opacity > 1) {
5108 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5109 return;
5110 }
5111
5112 std::scoped_lock lock(mLock);
5113 mMaximumObscuringOpacityForTouch = opacity;
5114}
5115
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005116std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5117InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005118 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5119 for (TouchedWindow& w : state.windows) {
5120 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005121 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005122 }
5123 }
5124 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005125 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005126}
5127
arthurhungb89ccb02020-12-30 16:19:01 +08005128bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5129 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005130 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005131 if (DEBUG_FOCUS) {
5132 ALOGD("Trivial transfer to same window.");
5133 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005134 return true;
5135 }
5136
Michael Wrightd02c5b62014-02-10 15:10:22 -08005137 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005138 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005139
Arthur Hungabbb9d82021-09-01 14:52:30 +00005140 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005141 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005142 if (state == nullptr || touchedWindow == nullptr) {
5143 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005144 return false;
5145 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005146
Arthur Hungabbb9d82021-09-01 14:52:30 +00005147 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5148 if (toWindowHandle == nullptr) {
5149 ALOGW("Cannot transfer focus because to window not found.");
5150 return false;
5151 }
5152
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005153 if (DEBUG_FOCUS) {
5154 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005155 touchedWindow->windowHandle->getName().c_str(),
5156 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157 }
5158
Arthur Hungabbb9d82021-09-01 14:52:30 +00005159 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005160 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005161 BitSet32 pointerIds = touchedWindow->pointerIds;
5162 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005163
Arthur Hungabbb9d82021-09-01 14:52:30 +00005164 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005165 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005166 ftl::Flags<InputTarget::Flags> newTargetFlags =
5167 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005168 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005169 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005170 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005171 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172
Arthur Hungabbb9d82021-09-01 14:52:30 +00005173 // Store the dragging window.
5174 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005175 if (pointerIds.count() != 1) {
5176 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5177 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005178 return false;
5179 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005180 // Track the pointer id for drag window and generate the drag state.
5181 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005182 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005183 }
5184
Arthur Hungabbb9d82021-09-01 14:52:30 +00005185 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005186 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5187 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005188 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005189 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005190 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005191 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005192 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005193 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005194 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005195 }
5196
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005197 if (DEBUG_FOCUS) {
5198 logDispatchStateLocked();
5199 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005200 } // release lock
5201
5202 // Wake up poll loop since it may need to make new input dispatching choices.
5203 mLooper->wake();
5204 return true;
5205}
5206
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005207/**
5208 * Get the touched foreground window on the given display.
5209 * Return null if there are no windows touched on that display, or if more than one foreground
5210 * window is being touched.
5211 */
5212sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5213 auto stateIt = mTouchStatesByDisplay.find(displayId);
5214 if (stateIt == mTouchStatesByDisplay.end()) {
5215 ALOGI("No touch state on display %" PRId32, displayId);
5216 return nullptr;
5217 }
5218
5219 const TouchState& state = stateIt->second;
5220 sp<WindowInfoHandle> touchedForegroundWindow;
5221 // If multiple foreground windows are touched, return nullptr
5222 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005223 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005224 if (touchedForegroundWindow != nullptr) {
5225 ALOGI("Two or more foreground windows: %s and %s",
5226 touchedForegroundWindow->getName().c_str(),
5227 window.windowHandle->getName().c_str());
5228 return nullptr;
5229 }
5230 touchedForegroundWindow = window.windowHandle;
5231 }
5232 }
5233 return touchedForegroundWindow;
5234}
5235
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005236// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005237bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005238 sp<IBinder> fromToken;
5239 { // acquire lock
5240 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005241 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005242 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005243 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5244 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005245 return false;
5246 }
5247
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005248 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5249 if (from == nullptr) {
5250 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5251 return false;
5252 }
5253
5254 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005255 } // release lock
5256
5257 return transferTouchFocus(fromToken, destChannelToken);
5258}
5259
Michael Wrightd02c5b62014-02-10 15:10:22 -08005260void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005261 if (DEBUG_FOCUS) {
5262 ALOGD("Resetting and dropping all events (%s).", reason);
5263 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005264
Michael Wrightfb04fd52022-11-24 22:31:11 +00005265 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266 synthesizeCancelationEventsForAllConnectionsLocked(options);
5267
5268 resetKeyRepeatLocked();
5269 releasePendingEventLocked();
5270 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005271 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005273 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005274 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005275 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005276 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005277}
5278
5279void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005280 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005281 dumpDispatchStateLocked(dump);
5282
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005283 std::istringstream stream(dump);
5284 std::string line;
5285
5286 while (std::getline(stream, line, '\n')) {
5287 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005288 }
5289}
5290
Prabir Pradhan99987712020-11-10 18:43:05 -08005291std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5292 std::string dump;
5293
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005294 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5295 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005296
5297 std::string windowName = "None";
5298 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005299 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005300 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5301 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5302 : "token has capture without window";
5303 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005304 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005305
5306 return dump;
5307}
5308
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005309void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005310 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5311 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5312 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005313 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005314
Tiger Huang721e26f2018-07-24 22:26:19 +08005315 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5316 dump += StringPrintf(INDENT "FocusedApplications:\n");
5317 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5318 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005319 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005320 const std::chrono::duration timeout =
5321 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005322 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005323 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005324 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005325 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005326 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005327 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005328 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005329
Vishnu Nairc519ff72021-01-21 08:23:08 -08005330 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005331 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005332
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005333 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005334 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005335 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005336 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5337 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005338 }
5339 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005340 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005341 }
5342
arthurhung6d4bed92021-03-17 11:59:33 +08005343 if (mDragState) {
5344 dump += StringPrintf(INDENT "DragState:\n");
5345 mDragState->dump(dump, INDENT2);
5346 }
5347
Arthur Hungb92218b2018-08-14 12:00:21 +08005348 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005349 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5350 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5351 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5352 const auto& displayInfo = it->second;
5353 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5354 displayInfo.logicalHeight);
5355 displayInfo.transform.dump(dump, "transform", INDENT4);
5356 } else {
5357 dump += INDENT2 "No DisplayInfo found!\n";
5358 }
5359
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005360 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005361 dump += INDENT2 "Windows:\n";
5362 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005363 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5364 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005365
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005366 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005367 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005368 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005369 "applicationInfo.name=%s, "
5370 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005371 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005372 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005373 windowInfo->displayId,
5374 windowInfo->inputConfig.string().c_str(),
5375 windowInfo->alpha, windowInfo->frameLeft,
5376 windowInfo->frameTop, windowInfo->frameRight,
5377 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005378 windowInfo->applicationInfo.name.c_str(),
5379 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005380 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005381 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005382 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005383 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005384 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005385 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005386 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005387 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005388 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005389 }
5390 } else {
5391 dump += INDENT2 "Windows: <none>\n";
5392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005393 }
5394 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005395 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005396 }
5397
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005398 if (!mGlobalMonitorsByDisplay.empty()) {
5399 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5400 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005401 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005403 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005404 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005405 }
5406
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005407 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408
5409 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005410 if (!mRecentQueue.empty()) {
5411 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005412 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005413 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005414 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005415 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005416 }
5417 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005418 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005419 }
5420
5421 // Dump event currently being dispatched.
5422 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005423 dump += INDENT "PendingEvent:\n";
5424 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005425 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005426 dump += StringPrintf(", age=%" PRId64 "ms\n",
5427 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005428 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005429 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005430 }
5431
5432 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005433 if (!mInboundQueue.empty()) {
5434 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005435 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005436 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005437 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005438 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005439 }
5440 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005441 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005442 }
5443
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005444 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005445 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005446 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005447 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005448 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005449 }
5450 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005451 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005452 }
5453
Prabir Pradhancef936d2021-07-21 16:17:52 +00005454 if (!mCommandQueue.empty()) {
5455 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5456 } else {
5457 dump += INDENT "CommandQueue: <empty>\n";
5458 }
5459
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005460 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005461 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005462 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005463 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005464 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005465 connection->inputChannel->getFd().get(),
5466 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005467 connection->getWindowName().c_str(),
5468 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005469 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005470
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005471 if (!connection->outboundQueue.empty()) {
5472 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5473 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005474 dump += dumpQueue(connection->outboundQueue, currentTime);
5475
Michael Wrightd02c5b62014-02-10 15:10:22 -08005476 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005477 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005478 }
5479
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005480 if (!connection->waitQueue.empty()) {
5481 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5482 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005483 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005484 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005485 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005486 }
5487 }
5488 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005489 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490 }
5491
5492 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005493 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5494 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005495 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005496 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497 }
5498
Antonio Kantek15beb512022-06-13 22:35:41 +00005499 if (!mTouchModePerDisplay.empty()) {
5500 dump += INDENT "TouchModePerDisplay:\n";
5501 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5502 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5503 std::to_string(touchMode).c_str());
5504 }
5505 } else {
5506 dump += INDENT "TouchModePerDisplay: <none>\n";
5507 }
5508
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005509 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005510 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5511 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5512 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005513 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005514 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005515}
5516
Michael Wright3dd60e22019-03-27 22:06:44 +00005517void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5518 const size_t numMonitors = monitors.size();
5519 for (size_t i = 0; i < numMonitors; i++) {
5520 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005521 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005522 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5523 dump += "\n";
5524 }
5525}
5526
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005527class LooperEventCallback : public LooperCallback {
5528public:
5529 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5530 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5531
5532private:
5533 std::function<int(int events)> mCallback;
5534};
5535
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005536Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005537 if (DEBUG_CHANNEL_CREATION) {
5538 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5539 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005540
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005541 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005542 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005543 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005544
5545 if (result) {
5546 return base::Error(result) << "Failed to open input channel pair with name " << name;
5547 }
5548
Michael Wrightd02c5b62014-02-10 15:10:22 -08005549 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005550 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005551 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005552 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005553 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005554 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005555
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005556 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5557 ALOGE("Created a new connection, but the token %p is already known", token.get());
5558 }
5559 mConnectionsByToken.emplace(token, connection);
5560
5561 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5562 this, std::placeholders::_1, token);
5563
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005564 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5565 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005566 } // release lock
5567
5568 // Wake the looper because some connections have changed.
5569 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005570 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005571}
5572
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005573Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005574 const std::string& name,
5575 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005576 std::shared_ptr<InputChannel> serverChannel;
5577 std::unique_ptr<InputChannel> clientChannel;
5578 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5579 if (result) {
5580 return base::Error(result) << "Failed to open input channel pair with name " << name;
5581 }
5582
Michael Wright3dd60e22019-03-27 22:06:44 +00005583 { // acquire lock
5584 std::scoped_lock _l(mLock);
5585
5586 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005587 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5588 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005589 }
5590
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005591 sp<Connection> connection =
5592 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005593 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005594 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005595
5596 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5597 ALOGE("Created a new connection, but the token %p is already known", token.get());
5598 }
5599 mConnectionsByToken.emplace(token, connection);
5600 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5601 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005602
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005603 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005604
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005605 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5606 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005607 }
Garfield Tan15601662020-09-22 15:32:38 -07005608
Michael Wright3dd60e22019-03-27 22:06:44 +00005609 // Wake the looper because some connections have changed.
5610 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005611 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005612}
5613
Garfield Tan15601662020-09-22 15:32:38 -07005614status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005615 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005616 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005617
Garfield Tan15601662020-09-22 15:32:38 -07005618 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005619 if (status) {
5620 return status;
5621 }
5622 } // release lock
5623
5624 // Wake the poll loop because removing the connection may have changed the current
5625 // synchronization state.
5626 mLooper->wake();
5627 return OK;
5628}
5629
Garfield Tan15601662020-09-22 15:32:38 -07005630status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5631 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005632 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005633 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005634 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005635 return BAD_VALUE;
5636 }
5637
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005638 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005639
Michael Wrightd02c5b62014-02-10 15:10:22 -08005640 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005641 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005642 }
5643
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005644 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005645
5646 nsecs_t currentTime = now();
5647 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5648
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005649 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005650 return OK;
5651}
5652
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005653void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005654 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5655 auto& [displayId, monitors] = *it;
5656 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5657 return monitor.inputChannel->getConnectionToken() == connectionToken;
5658 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005659
Michael Wright3dd60e22019-03-27 22:06:44 +00005660 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005661 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005662 } else {
5663 ++it;
5664 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005665 }
5666}
5667
Michael Wright3dd60e22019-03-27 22:06:44 +00005668status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005669 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005670 return pilferPointersLocked(token);
5671}
Michael Wright3dd60e22019-03-27 22:06:44 +00005672
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005673status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005674 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5675 if (!requestingChannel) {
5676 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5677 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005678 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005679
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005680 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07005681 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.isEmpty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005682 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5683 " Ignoring.");
5684 return BAD_VALUE;
5685 }
5686
5687 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005688 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005689 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005690 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005691 "input channel stole pointer stream");
5692 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005693 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005694 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005695 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005696 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005697 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005698 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005699 if (channel != nullptr && channel->getConnectionToken() != token) {
5700 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5701 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5702 canceledWindows += channel->getName();
5703 }
5704 }
5705 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5706 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5707 canceledWindows.c_str());
5708
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005709 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005710 // This only blocks relevant pointers to be sent to other windows
5711 window.isPilferingPointers = true;
5712
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005713 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005714 return OK;
5715}
5716
Prabir Pradhan99987712020-11-10 18:43:05 -08005717void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5718 { // acquire lock
5719 std::scoped_lock _l(mLock);
5720 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005721 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005722 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5723 windowHandle != nullptr ? windowHandle->getName().c_str()
5724 : "token without window");
5725 }
5726
Vishnu Nairc519ff72021-01-21 08:23:08 -08005727 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005728 if (focusedToken != windowToken) {
5729 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5730 enabled ? "enable" : "disable");
5731 return;
5732 }
5733
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005734 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005735 ALOGW("Ignoring request to %s Pointer Capture: "
5736 "window has %s requested pointer capture.",
5737 enabled ? "enable" : "disable", enabled ? "already" : "not");
5738 return;
5739 }
5740
Christine Franksb768bb42021-11-29 12:11:31 -08005741 if (enabled) {
5742 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5743 mIneligibleDisplaysForPointerCapture.end(),
5744 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5745 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5746 return;
5747 }
5748 }
5749
Prabir Pradhan99987712020-11-10 18:43:05 -08005750 setPointerCaptureLocked(enabled);
5751 } // release lock
5752
5753 // Wake the thread to process command entries.
5754 mLooper->wake();
5755}
5756
Christine Franksb768bb42021-11-29 12:11:31 -08005757void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5758 { // acquire lock
5759 std::scoped_lock _l(mLock);
5760 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5761 if (!isEligible) {
5762 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5763 }
5764 } // release lock
5765}
5766
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005767std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5768 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005769 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005770 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005771 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005772 }
5773 }
5774 }
5775 return std::nullopt;
5776}
5777
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005778sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005779 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005780 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005781 }
5782
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005783 for (const auto& [token, connection] : mConnectionsByToken) {
5784 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005785 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005786 }
5787 }
Robert Carr4e670e52018-08-15 13:26:12 -07005788
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005789 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005790}
5791
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005792std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5793 sp<Connection> connection = getConnectionLocked(connectionToken);
5794 if (connection == nullptr) {
5795 return "<nullptr>";
5796 }
5797 return connection->getInputChannelName();
5798}
5799
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005800void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005801 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005802 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005803}
5804
Prabir Pradhancef936d2021-07-21 16:17:52 +00005805void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5806 const sp<Connection>& connection, uint32_t seq,
5807 bool handled, nsecs_t consumeTime) {
5808 // Handle post-event policy actions.
5809 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5810 if (dispatchEntryIt == connection->waitQueue.end()) {
5811 return;
5812 }
5813 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5814 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5815 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5816 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5817 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5818 }
5819 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5820 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5821 connection->inputChannel->getConnectionToken(),
5822 dispatchEntry->deliveryTime, consumeTime, finishTime);
5823 }
5824
5825 bool restartEvent;
5826 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5827 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5828 restartEvent =
5829 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5830 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5831 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5832 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5833 handled);
5834 } else {
5835 restartEvent = false;
5836 }
5837
5838 // Dequeue the event and start the next cycle.
5839 // Because the lock might have been released, it is possible that the
5840 // contents of the wait queue to have been drained, so we need to double-check
5841 // a few things.
5842 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5843 if (dispatchEntryIt != connection->waitQueue.end()) {
5844 dispatchEntry = *dispatchEntryIt;
5845 connection->waitQueue.erase(dispatchEntryIt);
5846 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5847 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5848 if (!connection->responsive) {
5849 connection->responsive = isConnectionResponsive(*connection);
5850 if (connection->responsive) {
5851 // The connection was unresponsive, and now it's responsive.
5852 processConnectionResponsiveLocked(*connection);
5853 }
5854 }
5855 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005856 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005857 connection->outboundQueue.push_front(dispatchEntry);
5858 traceOutboundQueueLength(*connection);
5859 } else {
5860 releaseDispatchEntry(dispatchEntry);
5861 }
5862 }
5863
5864 // Start the next dispatch cycle for this connection.
5865 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005866}
5867
Prabir Pradhancef936d2021-07-21 16:17:52 +00005868void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5869 const sp<IBinder>& newToken) {
5870 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5871 scoped_unlock unlock(mLock);
5872 mPolicy->notifyFocusChanged(oldToken, newToken);
5873 };
5874 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005875}
5876
Prabir Pradhancef936d2021-07-21 16:17:52 +00005877void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5878 auto command = [this, token, x, y]() REQUIRES(mLock) {
5879 scoped_unlock unlock(mLock);
5880 mPolicy->notifyDropWindow(token, x, y);
5881 };
5882 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005883}
5884
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005885void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5886 if (connection == nullptr) {
5887 LOG_ALWAYS_FATAL("Caller must check for nullness");
5888 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005889 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5890 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005891 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005892 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005893 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005894 return;
5895 }
5896 /**
5897 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5898 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5899 * has changed. This could cause newer entries to time out before the already dispatched
5900 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5901 * processes the events linearly. So providing information about the oldest entry seems to be
5902 * most useful.
5903 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005904 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005905 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5906 std::string reason =
5907 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005908 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005909 ns2ms(currentWait),
5910 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005911 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005912 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005913
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005914 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5915
5916 // Stop waking up for events on this connection, it is already unresponsive
5917 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005918}
5919
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005920void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5921 std::string reason =
5922 StringPrintf("%s does not have a focused window", application->getName().c_str());
5923 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005924
Prabir Pradhancef936d2021-07-21 16:17:52 +00005925 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5926 scoped_unlock unlock(mLock);
5927 mPolicy->notifyNoFocusedWindowAnr(application);
5928 };
5929 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005930}
5931
chaviw98318de2021-05-19 16:45:23 -05005932void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005933 const std::string& reason) {
5934 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5935 updateLastAnrStateLocked(windowLabel, reason);
5936}
5937
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005938void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5939 const std::string& reason) {
5940 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005941 updateLastAnrStateLocked(windowLabel, reason);
5942}
5943
5944void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5945 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005946 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005947 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005948 struct tm tm;
5949 localtime_r(&t, &tm);
5950 char timestr[64];
5951 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005952 mLastAnrState.clear();
5953 mLastAnrState += INDENT "ANR:\n";
5954 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005955 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5956 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005957 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005958}
5959
Prabir Pradhancef936d2021-07-21 16:17:52 +00005960void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5961 KeyEntry& entry) {
5962 const KeyEvent event = createKeyEvent(entry);
5963 nsecs_t delay = 0;
5964 { // release lock
5965 scoped_unlock unlock(mLock);
5966 android::base::Timer t;
5967 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5968 entry.policyFlags);
5969 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5970 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5971 std::to_string(t.duration().count()).c_str());
5972 }
5973 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005974
5975 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00005976 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005977 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00005978 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005979 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00005980 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005981 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005983}
5984
Prabir Pradhancef936d2021-07-21 16:17:52 +00005985void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005986 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005987 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005988 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005989 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005990 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005991 };
5992 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005993}
5994
Prabir Pradhanedd96402022-02-15 01:46:16 -08005995void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5996 std::optional<int32_t> pid) {
5997 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005998 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005999 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006000 };
6001 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006002}
6003
6004/**
6005 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6006 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6007 * command entry to the command queue.
6008 */
6009void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6010 std::string reason) {
6011 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006012 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006013 if (connection.monitor) {
6014 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6015 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006016 pid = findMonitorPidByTokenLocked(connectionToken);
6017 } else {
6018 // The connection is a window
6019 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6020 reason.c_str());
6021 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6022 if (handle != nullptr) {
6023 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006024 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006025 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006026 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006027}
6028
6029/**
6030 * Tell the policy that a connection has become responsive so that it can stop ANR.
6031 */
6032void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6033 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006034 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006035 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006036 pid = findMonitorPidByTokenLocked(connectionToken);
6037 } else {
6038 // The connection is a window
6039 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6040 if (handle != nullptr) {
6041 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006042 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006043 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006044 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006045}
6046
Prabir Pradhancef936d2021-07-21 16:17:52 +00006047bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006048 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006049 KeyEntry& keyEntry, bool handled) {
6050 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006051 if (!handled) {
6052 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006053 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006054 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006055 return false;
6056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006057
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006058 // Get the fallback key state.
6059 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006060 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006061 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006062 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006063 connection->inputState.removeFallbackKey(originalKeyCode);
6064 }
6065
6066 if (handled || !dispatchEntry->hasForegroundTarget()) {
6067 // If the application handles the original key for which we previously
6068 // generated a fallback or if the window is not a foreground window,
6069 // then cancel the associated fallback key, if any.
6070 if (fallbackKeyCode != -1) {
6071 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006072 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6073 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6074 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6075 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6076 keyEntry.policyFlags);
6077 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006078 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006079 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006080
6081 mLock.unlock();
6082
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006083 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006084 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006085
6086 mLock.lock();
6087
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006088 // Cancel the fallback key.
6089 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006090 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006091 "application handled the original non-fallback key "
6092 "or is no longer a foreground target, "
6093 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006094 options.keyCode = fallbackKeyCode;
6095 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006096 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006097 connection->inputState.removeFallbackKey(originalKeyCode);
6098 }
6099 } else {
6100 // If the application did not handle a non-fallback key, first check
6101 // that we are in a good state to perform unhandled key event processing
6102 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006103 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006104 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006105 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6106 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6107 "since this is not an initial down. "
6108 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6109 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6110 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006111 return false;
6112 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006113
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006114 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006115 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6116 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6117 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6118 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6119 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006120 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006121
6122 mLock.unlock();
6123
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006124 bool fallback =
6125 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006126 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006127
6128 mLock.lock();
6129
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006130 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006131 connection->inputState.removeFallbackKey(originalKeyCode);
6132 return false;
6133 }
6134
6135 // Latch the fallback keycode for this key on an initial down.
6136 // The fallback keycode cannot change at any other point in the lifecycle.
6137 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006138 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006139 fallbackKeyCode = event.getKeyCode();
6140 } else {
6141 fallbackKeyCode = AKEYCODE_UNKNOWN;
6142 }
6143 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6144 }
6145
6146 ALOG_ASSERT(fallbackKeyCode != -1);
6147
6148 // Cancel the fallback key if the policy decides not to send it anymore.
6149 // We will continue to dispatch the key to the policy but we will no
6150 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006151 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6152 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006153 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6154 if (fallback) {
6155 ALOGD("Unhandled key event: Policy requested to send key %d"
6156 "as a fallback for %d, but on the DOWN it had requested "
6157 "to send %d instead. Fallback canceled.",
6158 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6159 } else {
6160 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6161 "but on the DOWN it had requested to send %d. "
6162 "Fallback canceled.",
6163 originalKeyCode, fallbackKeyCode);
6164 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006165 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006166
Michael Wrightfb04fd52022-11-24 22:31:11 +00006167 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006168 "canceling fallback, policy no longer desires it");
6169 options.keyCode = fallbackKeyCode;
6170 synthesizeCancelationEventsForConnectionLocked(connection, options);
6171
6172 fallback = false;
6173 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006174 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006175 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006176 }
6177 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006178
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006179 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6180 {
6181 std::string msg;
6182 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6183 connection->inputState.getFallbackKeys();
6184 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6185 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6186 }
6187 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6188 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006189 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006190 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006191
6192 if (fallback) {
6193 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006194 keyEntry.eventTime = event.getEventTime();
6195 keyEntry.deviceId = event.getDeviceId();
6196 keyEntry.source = event.getSource();
6197 keyEntry.displayId = event.getDisplayId();
6198 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6199 keyEntry.keyCode = fallbackKeyCode;
6200 keyEntry.scanCode = event.getScanCode();
6201 keyEntry.metaState = event.getMetaState();
6202 keyEntry.repeatCount = event.getRepeatCount();
6203 keyEntry.downTime = event.getDownTime();
6204 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006205
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006206 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6207 ALOGD("Unhandled key event: Dispatching fallback key. "
6208 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6209 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6210 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006211 return true; // restart the event
6212 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006213 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6214 ALOGD("Unhandled key event: No fallback key.");
6215 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006216
6217 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006218 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006219 }
6220 }
6221 return false;
6222}
6223
Prabir Pradhancef936d2021-07-21 16:17:52 +00006224bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006225 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006226 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006227 return false;
6228}
6229
Michael Wrightd02c5b62014-02-10 15:10:22 -08006230void InputDispatcher::traceInboundQueueLengthLocked() {
6231 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006232 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006233 }
6234}
6235
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006236void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006237 if (ATRACE_ENABLED()) {
6238 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006239 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6240 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006241 }
6242}
6243
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006244void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006245 if (ATRACE_ENABLED()) {
6246 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006247 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6248 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006249 }
6250}
6251
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006252void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006253 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006254
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006255 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006256 dumpDispatchStateLocked(dump);
6257
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006258 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006259 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006260 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006261 }
6262}
6263
6264void InputDispatcher::monitor() {
6265 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006266 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006267 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006268 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006269}
6270
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006271/**
6272 * Wake up the dispatcher and wait until it processes all events and commands.
6273 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6274 * this method can be safely called from any thread, as long as you've ensured that
6275 * the work you are interested in completing has already been queued.
6276 */
6277bool InputDispatcher::waitForIdle() {
6278 /**
6279 * Timeout should represent the longest possible time that a device might spend processing
6280 * events and commands.
6281 */
6282 constexpr std::chrono::duration TIMEOUT = 100ms;
6283 std::unique_lock lock(mLock);
6284 mLooper->wake();
6285 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6286 return result == std::cv_status::no_timeout;
6287}
6288
Vishnu Naire798b472020-07-23 13:52:21 -07006289/**
6290 * Sets focus to the window identified by the token. This must be called
6291 * after updating any input window handles.
6292 *
6293 * Params:
6294 * request.token - input channel token used to identify the window that should gain focus.
6295 * request.focusedToken - the token that the caller expects currently to be focused. If the
6296 * specified token does not match the currently focused window, this request will be dropped.
6297 * If the specified focused token matches the currently focused window, the call will succeed.
6298 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6299 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6300 * when requesting the focus change. This determines which request gets
6301 * precedence if there is a focus change request from another source such as pointer down.
6302 */
Vishnu Nair958da932020-08-21 17:12:37 -07006303void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6304 { // acquire lock
6305 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006306 std::optional<FocusResolver::FocusChanges> changes =
6307 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6308 if (changes) {
6309 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006310 }
6311 } // release lock
6312 // Wake up poll loop since it may need to make new input dispatching choices.
6313 mLooper->wake();
6314}
6315
Vishnu Nairc519ff72021-01-21 08:23:08 -08006316void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6317 if (changes.oldFocus) {
6318 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006319 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006320 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006321 "focus left window");
6322 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006323 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006324 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006325 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006326 if (changes.newFocus) {
6327 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006328 }
6329
Prabir Pradhan99987712020-11-10 18:43:05 -08006330 // If a window has pointer capture, then it must have focus. We need to ensure that this
6331 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6332 // If the window loses focus before it loses pointer capture, then the window can be in a state
6333 // where it has pointer capture but not focus, violating the contract. Therefore we must
6334 // dispatch the pointer capture event before the focus event. Since focus events are added to
6335 // the front of the queue (above), we add the pointer capture event to the front of the queue
6336 // after the focus events are added. This ensures the pointer capture event ends up at the
6337 // front.
6338 disablePointerCaptureForcedLocked();
6339
Vishnu Nairc519ff72021-01-21 08:23:08 -08006340 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006341 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006342 }
6343}
Vishnu Nair958da932020-08-21 17:12:37 -07006344
Prabir Pradhan99987712020-11-10 18:43:05 -08006345void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006346 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006347 return;
6348 }
6349
6350 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6351
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006352 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006353 setPointerCaptureLocked(false);
6354 }
6355
6356 if (!mWindowTokenWithPointerCapture) {
6357 // No need to send capture changes because no window has capture.
6358 return;
6359 }
6360
6361 if (mPendingEvent != nullptr) {
6362 // Move the pending event to the front of the queue. This will give the chance
6363 // for the pending event to be dropped if it is a captured event.
6364 mInboundQueue.push_front(mPendingEvent);
6365 mPendingEvent = nullptr;
6366 }
6367
6368 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006369 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006370 mInboundQueue.push_front(std::move(entry));
6371}
6372
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006373void InputDispatcher::setPointerCaptureLocked(bool enable) {
6374 mCurrentPointerCaptureRequest.enable = enable;
6375 mCurrentPointerCaptureRequest.seq++;
6376 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006377 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006378 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006379 };
6380 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006381}
6382
Vishnu Nair599f1412021-06-21 10:39:58 -07006383void InputDispatcher::displayRemoved(int32_t displayId) {
6384 { // acquire lock
6385 std::scoped_lock _l(mLock);
6386 // Set an empty list to remove all handles from the specific display.
6387 setInputWindowsLocked(/* window handles */ {}, displayId);
6388 setFocusedApplicationLocked(displayId, nullptr);
6389 // Call focus resolver to clean up stale requests. This must be called after input windows
6390 // have been removed for the removed display.
6391 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006392 // Reset pointer capture eligibility, regardless of previous state.
6393 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006394 // Remove the associated touch mode state.
6395 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006396 } // release lock
6397
6398 // Wake up poll loop since it may need to make new input dispatching choices.
6399 mLooper->wake();
6400}
6401
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006402void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6403 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006404 // The listener sends the windows as a flattened array. Separate the windows by display for
6405 // more convenient parsing.
6406 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006407 for (const auto& info : windowInfos) {
6408 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006409 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006410 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006411
6412 { // acquire lock
6413 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006414
6415 // Ensure that we have an entry created for all existing displays so that if a displayId has
6416 // no windows, we can tell that the windows were removed from the display.
6417 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6418 handlesPerDisplay[displayId];
6419 }
6420
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006421 mDisplayInfos.clear();
6422 for (const auto& displayInfo : displayInfos) {
6423 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6424 }
6425
6426 for (const auto& [displayId, handles] : handlesPerDisplay) {
6427 setInputWindowsLocked(handles, displayId);
6428 }
6429 }
6430 // Wake up poll loop since it may need to make new input dispatching choices.
6431 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006432}
6433
Vishnu Nair062a8672021-09-03 16:07:44 -07006434bool InputDispatcher::shouldDropInput(
6435 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006436 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6437 (windowHandle->getInfo()->inputConfig.test(
6438 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006439 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006440 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6441 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006442 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006443 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006444 windowHandle->getInfo()->displayId);
6445 return true;
6446 }
6447 return false;
6448}
6449
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006450void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6451 const std::vector<gui::WindowInfo>& windowInfos,
6452 const std::vector<DisplayInfo>& displayInfos) {
6453 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6454}
6455
Arthur Hungdfd528e2021-12-08 13:23:04 +00006456void InputDispatcher::cancelCurrentTouch() {
6457 {
6458 std::scoped_lock _l(mLock);
6459 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006460 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006461 "cancel current touch");
6462 synthesizeCancelationEventsForAllConnectionsLocked(options);
6463
6464 mTouchStatesByDisplay.clear();
6465 mLastHoverWindowHandle.clear();
6466 }
6467 // Wake up poll loop since there might be work to do.
6468 mLooper->wake();
6469}
6470
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006471void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6472 std::scoped_lock _l(mLock);
6473 mMonitorDispatchingTimeout = timeout;
6474}
6475
Garfield Tane84e6f92019-08-29 17:28:41 -07006476} // namespace android::inputdispatcher