blob: d36b6ff41dc4eaf37aa8495111e2345b0d37d3bd [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 }
2309 }
2310
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002311 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002313 // Let the previous window know that the hover sequence is over, unless we already did
2314 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002315 if (mLastHoverWindowHandle != nullptr &&
2316 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2317 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002318 if (DEBUG_HOVER) {
2319 ALOGD("Sending hover exit event to window %s.",
2320 mLastHoverWindowHandle->getName().c_str());
2321 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002322 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002323 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT,
2324 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325 }
2326
Garfield Tandf26e862020-07-01 20:18:19 -07002327 // Let the new window know that the hover sequence is starting, unless we already did it
2328 // when dispatching it as is to newTouchedWindowHandle.
2329 if (newHoverWindowHandle != nullptr &&
2330 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2331 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002332 if (DEBUG_HOVER) {
2333 ALOGD("Sending hover enter event to window %s.",
2334 newHoverWindowHandle->getName().c_str());
2335 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002336 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002337 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002338 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339 }
2340 }
2341
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002342 // Ensure that we have at least one foreground window or at least one window that cannot be a
2343 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2344 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2345 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002346 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2347 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002348 return !canReceiveForegroundTouches(
2349 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002350 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002351 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002352 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2353 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002354 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002355 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 }
2357
Prabir Pradhan5735a322022-04-11 17:23:34 +00002358 // Ensure that all touched windows are valid for injection.
2359 if (entry.injectionState != nullptr) {
2360 std::string errs;
2361 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002362 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002363 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2364 // dispatched to any uid, since the coords will be zeroed out later.
2365 continue;
2366 }
2367 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2368 if (err) errs += "\n - " + *err;
2369 }
2370 if (!errs.empty()) {
2371 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2372 "%d:%s",
2373 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002374 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002375 goto Failed;
2376 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002377 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002378
Michael Wrightd02c5b62014-02-10 15:10:22 -08002379 // Check whether windows listening for outside touches are owned by the same UID. If it is
2380 // set the policy flag that we will not reveal coordinate information to this window.
2381 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002382 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002383 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002384 if (foregroundWindowHandle) {
2385 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002386 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002387 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
chaviw98318de2021-05-19 16:45:23 -05002388 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2389 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2390 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002391 InputTarget::Flags::ZERO_COORDS,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002392 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002393 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 }
2395 }
2396 }
2397 }
2398
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 // If this is the first pointer going down and the touched window has a wallpaper
2400 // then also add the touched wallpaper windows so they are locked in for the duration
2401 // of the touch gesture.
2402 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2403 // engine only supports touch events. We would need to add a mechanism similar
2404 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2405 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002406 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002407 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002408 if (foregroundWindowHandle &&
2409 foregroundWindowHandle->getInfo()->inputConfig.test(
2410 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002411 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002412 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002413 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2414 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002415 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002416 windowHandle->getInfo()->inputConfig.test(
2417 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002418 tempTouchState.addOrUpdateWindow(windowHandle,
2419 InputTarget::Flags::WINDOW_IS_OBSCURED |
2420 InputTarget::Flags::
2421 WINDOW_IS_PARTIALLY_OBSCURED |
2422 InputTarget::Flags::DISPATCH_AS_IS,
2423 BitSet32(0), entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424 }
2425 }
2426 }
2427 }
2428
2429 // Success! Output targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002430 touchedWindows = tempTouchState.windows;
2431 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002432
2433 // Drop the outside or hover touch windows since we will not care about them
2434 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002435 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436
2437Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002438 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002439 if (switchedDevice) {
2440 if (DEBUG_FOCUS) {
2441 ALOGD("Conflicting pointer actions: Switched to a different device.");
2442 }
2443 *outConflictingPointerActions = true;
2444 }
2445
2446 if (isHoverAction) {
2447 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002448 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002449 ALOGD_IF(DEBUG_FOCUS,
2450 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002451 *outConflictingPointerActions = true;
2452 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002453 tempTouchState.reset();
2454 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2455 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2456 tempTouchState.deviceId = entry.deviceId;
2457 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002458 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002459 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2460 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2461 // All pointers up or canceled.
2462 tempTouchState.reset();
2463 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2464 // First pointer went down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002465 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002466 ALOGD("Conflicting pointer actions: Down received while already down.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002467 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002468 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002469 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2470 // One pointer went up.
2471 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2472 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002473
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002474 for (size_t i = 0; i < tempTouchState.windows.size();) {
2475 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2476 touchedWindow.pointerIds.clearBit(pointerId);
2477 if (touchedWindow.pointerIds.isEmpty()) {
2478 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2479 continue;
2480 }
2481 i += 1;
2482 }
2483 } else if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2484 // If no split, we suppose all touched windows should receive pointer down.
2485 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2486 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2487 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2488 // Ignore drag window for it should just track one pointer.
2489 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2490 continue;
2491 }
2492 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2493 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494 }
2495
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002496 // Save changes unless the action was scroll in which case the temporary touch
2497 // state was only valid for this one action.
2498 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002499 if (displayId >= 0) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002500 mTouchStatesByDisplay[displayId] = tempTouchState;
2501 } else {
2502 mTouchStatesByDisplay.erase(displayId);
2503 }
2504 }
2505
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002506 if (tempTouchState.windows.empty()) {
2507 mTouchStatesByDisplay.erase(displayId);
2508 }
2509
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002510 // Update hover state.
2511 mLastHoverWindowHandle = newHoverWindowHandle;
2512
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002513 return touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002514}
2515
arthurhung6d4bed92021-03-17 11:59:33 +08002516void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002517 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2518 // have an explicit reason to support it.
2519 constexpr bool isStylus = false;
2520
chaviw98318de2021-05-19 16:45:23 -05002521 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002522 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002523 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002524 if (dropWindow) {
2525 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002526 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002527 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002528 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002529 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002530 }
2531 mDragState.reset();
2532}
2533
2534void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002535 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002536 return;
2537 }
2538
arthurhung6d4bed92021-03-17 11:59:33 +08002539 if (!mDragState->isStartDrag) {
2540 mDragState->isStartDrag = true;
2541 mDragState->isStylusButtonDownAtStart =
2542 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2543 }
2544
Arthur Hung54745652022-04-20 07:17:41 +00002545 // Find the pointer index by id.
2546 int32_t pointerIndex = 0;
2547 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2548 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2549 if (pointerProperties.id == mDragState->pointerId) {
2550 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002551 }
Arthur Hung54745652022-04-20 07:17:41 +00002552 }
arthurhung6d4bed92021-03-17 11:59:33 +08002553
Arthur Hung54745652022-04-20 07:17:41 +00002554 if (uint32_t(pointerIndex) == entry.pointerCount) {
2555 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002556 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002557 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002558 return;
2559 }
2560
2561 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2562 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2563 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2564
2565 switch (maskedAction) {
2566 case AMOTION_EVENT_ACTION_MOVE: {
2567 // Handle the special case : stylus button no longer pressed.
2568 bool isStylusButtonDown =
2569 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2570 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2571 finishDragAndDrop(entry.displayId, x, y);
2572 return;
2573 }
2574
2575 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2576 // until we have an explicit reason to support it.
2577 constexpr bool isStylus = false;
2578
2579 const sp<WindowInfoHandle> hoverWindowHandle =
2580 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2581 isStylus, false /*addOutsideTargets*/,
2582 true /*ignoreDragWindow*/);
2583 // enqueue drag exit if needed.
2584 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2585 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2586 if (mDragState->dragHoverWindowHandle != nullptr) {
2587 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2588 y);
2589 }
2590 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2591 }
2592 // enqueue drag location if needed.
2593 if (hoverWindowHandle != nullptr) {
2594 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2595 }
2596 break;
2597 }
2598
2599 case AMOTION_EVENT_ACTION_POINTER_UP:
2600 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2601 break;
2602 }
2603 // The drag pointer is up.
2604 [[fallthrough]];
2605 case AMOTION_EVENT_ACTION_UP:
2606 finishDragAndDrop(entry.displayId, x, y);
2607 break;
2608 case AMOTION_EVENT_ACTION_CANCEL: {
2609 ALOGD("Receiving cancel when drag and drop.");
2610 sendDropWindowCommandLocked(nullptr, 0, 0);
2611 mDragState.reset();
2612 break;
2613 }
arthurhungb89ccb02020-12-30 16:19:01 +08002614 }
2615}
2616
chaviw98318de2021-05-19 16:45:23 -05002617void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002618 ftl::Flags<InputTarget::Flags> targetFlags,
2619 BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002620 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002621 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002622 std::vector<InputTarget>::iterator it =
2623 std::find_if(inputTargets.begin(), inputTargets.end(),
2624 [&windowHandle](const InputTarget& inputTarget) {
2625 return inputTarget.inputChannel->getConnectionToken() ==
2626 windowHandle->getToken();
2627 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002628
chaviw98318de2021-05-19 16:45:23 -05002629 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002630
2631 if (it == inputTargets.end()) {
2632 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002633 std::shared_ptr<InputChannel> inputChannel =
2634 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002635 if (inputChannel == nullptr) {
2636 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2637 return;
2638 }
2639 inputTarget.inputChannel = inputChannel;
2640 inputTarget.flags = targetFlags;
2641 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002642 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002643 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2644 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002645 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002646 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002647 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002648 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002649 inputTargets.push_back(inputTarget);
2650 it = inputTargets.end() - 1;
2651 }
2652
2653 ALOG_ASSERT(it->flags == targetFlags);
2654 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2655
chaviw1ff3d1e2020-07-01 15:53:47 -07002656 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002657}
2658
Michael Wright3dd60e22019-03-27 22:06:44 +00002659void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002660 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002661 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2662 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002663
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002664 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2665 InputTarget target;
2666 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002667 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002668 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2669 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002670 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2671 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002672 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002673 target.setDefaultPointerTransform(target.displayTransform);
2674 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002675 }
2676}
2677
Robert Carrc9bf1d32020-04-13 17:21:08 -07002678/**
2679 * Indicate whether one window handle should be considered as obscuring
2680 * another window handle. We only check a few preconditions. Actually
2681 * checking the bounds is left to the caller.
2682 */
chaviw98318de2021-05-19 16:45:23 -05002683static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2684 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002685 // Compare by token so cloned layers aren't counted
2686 if (haveSameToken(windowHandle, otherHandle)) {
2687 return false;
2688 }
2689 auto info = windowHandle->getInfo();
2690 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002691 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002692 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002693 } else if (otherInfo->alpha == 0 &&
2694 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002695 // Those act as if they were invisible, so we don't need to flag them.
2696 // We do want to potentially flag touchable windows even if they have 0
2697 // opacity, since they can consume touches and alter the effects of the
2698 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002699 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002700 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2701 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002702 } else if (info->ownerUid == otherInfo->ownerUid) {
2703 // If ownerUid is the same we don't generate occlusion events as there
2704 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002705 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002706 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002707 return false;
2708 } else if (otherInfo->displayId != info->displayId) {
2709 return false;
2710 }
2711 return true;
2712}
2713
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002714/**
2715 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2716 * untrusted, one should check:
2717 *
2718 * 1. If result.hasBlockingOcclusion is true.
2719 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2720 * BLOCK_UNTRUSTED.
2721 *
2722 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2723 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2724 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2725 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2726 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2727 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2728 *
2729 * If neither of those is true, then it means the touch can be allowed.
2730 */
2731InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002732 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2733 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002734 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002735 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002736 TouchOcclusionInfo info;
2737 info.hasBlockingOcclusion = false;
2738 info.obscuringOpacity = 0;
2739 info.obscuringUid = -1;
2740 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002741 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002742 if (windowHandle == otherHandle) {
2743 break; // All future windows are below us. Exit early.
2744 }
chaviw98318de2021-05-19 16:45:23 -05002745 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002746 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2747 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002748 if (DEBUG_TOUCH_OCCLUSION) {
2749 info.debugInfo.push_back(
2750 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2751 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002752 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2753 // we perform the checks below to see if the touch can be propagated or not based on the
2754 // window's touch occlusion mode
2755 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2756 info.hasBlockingOcclusion = true;
2757 info.obscuringUid = otherInfo->ownerUid;
2758 info.obscuringPackage = otherInfo->packageName;
2759 break;
2760 }
2761 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2762 uint32_t uid = otherInfo->ownerUid;
2763 float opacity =
2764 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2765 // Given windows A and B:
2766 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2767 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2768 opacityByUid[uid] = opacity;
2769 if (opacity > info.obscuringOpacity) {
2770 info.obscuringOpacity = opacity;
2771 info.obscuringUid = uid;
2772 info.obscuringPackage = otherInfo->packageName;
2773 }
2774 }
2775 }
2776 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002777 if (DEBUG_TOUCH_OCCLUSION) {
2778 info.debugInfo.push_back(
2779 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2780 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002781 return info;
2782}
2783
chaviw98318de2021-05-19 16:45:23 -05002784std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002785 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002786 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2787 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2788 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2789 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002790 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2791 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2792 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2793 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2794 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002795 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002796 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002797}
2798
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002799bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2800 if (occlusionInfo.hasBlockingOcclusion) {
2801 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2802 occlusionInfo.obscuringUid);
2803 return false;
2804 }
2805 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2806 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2807 "%.2f, maximum allowed = %.2f)",
2808 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2809 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2810 return false;
2811 }
2812 return true;
2813}
2814
chaviw98318de2021-05-19 16:45:23 -05002815bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002816 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002817 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002818 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2819 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002820 if (windowHandle == otherHandle) {
2821 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 }
chaviw98318de2021-05-19 16:45:23 -05002823 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002824 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002825 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002826 return true;
2827 }
2828 }
2829 return false;
2830}
2831
chaviw98318de2021-05-19 16:45:23 -05002832bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002833 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002834 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2835 const WindowInfo* windowInfo = windowHandle->getInfo();
2836 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002837 if (windowHandle == otherHandle) {
2838 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002839 }
chaviw98318de2021-05-19 16:45:23 -05002840 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002841 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002842 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002843 return true;
2844 }
2845 }
2846 return false;
2847}
2848
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002849std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002850 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002851 if (applicationHandle != nullptr) {
2852 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002853 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002854 } else {
2855 return applicationHandle->getName();
2856 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002857 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002858 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002859 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002860 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002861 }
2862}
2863
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002864void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002865 if (!isUserActivityEvent(eventEntry)) {
2866 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002867 return;
2868 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002869 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002870 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002871 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002872 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002873 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002874 if (DEBUG_DISPATCH_CYCLE) {
2875 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2876 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002877 return;
2878 }
2879 }
2880
2881 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002882 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002883 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002884 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2885 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002886 return;
2887 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002889 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002890 eventType = USER_ACTIVITY_EVENT_TOUCH;
2891 }
2892 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002894 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002895 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2896 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002897 return;
2898 }
2899 eventType = USER_ACTIVITY_EVENT_BUTTON;
2900 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002902 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002903 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002904 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002905 break;
2906 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002907 }
2908
Prabir Pradhancef936d2021-07-21 16:17:52 +00002909 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2910 REQUIRES(mLock) {
2911 scoped_unlock unlock(mLock);
2912 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2913 };
2914 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002915}
2916
2917void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002918 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002919 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002920 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002921 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002922 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002923 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002924 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002925 ATRACE_NAME(message.c_str());
2926 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002927 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002928 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002929 "globalScaleFactor=%f, pointerIds=0x%x %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002930 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002931 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2932 inputTarget.getPointerInfoString().c_str());
2933 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002934
2935 // Skip this event if the connection status is not normal.
2936 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002937 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002938 if (DEBUG_DISPATCH_CYCLE) {
2939 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002940 connection->getInputChannelName().c_str(),
2941 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002942 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002943 return;
2944 }
2945
2946 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002947 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002948 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002949 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002950 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002951
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002952 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002953 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002954 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
2955 "Splitting motion events requires a down time to be set for the "
2956 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002957 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002958 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
2959 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002960 if (!splitMotionEntry) {
2961 return; // split event was dropped
2962 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002963 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2964 std::string reason = std::string("reason=pointer cancel on split window");
2965 android_log_event_list(LOGTAG_INPUT_CANCEL)
2966 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2967 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002968 if (DEBUG_FOCUS) {
2969 ALOGD("channel '%s' ~ Split motion event.",
2970 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002971 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002972 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002973 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2974 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002975 return;
2976 }
2977 }
2978
2979 // Not splitting. Enqueue dispatch entries for the event as is.
2980 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2981}
2982
2983void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002984 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002985 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002986 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002987 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002988 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002989 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002990 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002991 ATRACE_NAME(message.c_str());
2992 }
2993
hongzuo liu95785e22022-09-06 02:51:35 +00002994 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002995
2996 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002997 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002998 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002999 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003000 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003001 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003002 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003003 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003004 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003005 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003006 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003007 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003008 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003009
3010 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003011 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003012 startDispatchCycleLocked(currentTime, connection);
3013 }
3014}
3015
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003016void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003017 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003018 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003019 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003020 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003021 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3022 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003023 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003024 ATRACE_NAME(message.c_str());
3025 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003026 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3027 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003028 return;
3029 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003030
3031 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3032 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033
3034 // This is a new event.
3035 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003036 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003037 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003039 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3040 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003041 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003043 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003044 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003045 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003046 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003047 dispatchEntry->resolvedAction = keyEntry.action;
3048 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003049
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003050 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3051 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003052 if (DEBUG_DISPATCH_CYCLE) {
3053 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3054 "event",
3055 connection->getInputChannelName().c_str());
3056 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003057 return; // skip the inconsistent event
3058 }
3059 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003060 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003061
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003062 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003063 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003064 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3065 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3066 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3067 static_cast<int32_t>(IdGenerator::Source::OTHER);
3068 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003069 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003070 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003071 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003072 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003073 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003074 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003075 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003076 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003077 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003078 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3079 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003080 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003081 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003082 }
3083 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003084 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3085 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003086 if (DEBUG_DISPATCH_CYCLE) {
3087 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3088 "enter event",
3089 connection->getInputChannelName().c_str());
3090 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003091 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3092 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003093 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3094 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003095
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003096 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003097 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003098 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3099 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003100 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003101 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3102 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003104 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3105 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003106 if (DEBUG_DISPATCH_CYCLE) {
3107 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3108 "event",
3109 connection->getInputChannelName().c_str());
3110 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003111 return; // skip the inconsistent event
3112 }
3113
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003114 dispatchEntry->resolvedEventId =
3115 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3116 ? mIdGenerator.nextId()
3117 : motionEntry.id;
3118 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3119 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3120 ") to MotionEvent(id=0x%" PRIx32 ").",
3121 motionEntry.id, dispatchEntry->resolvedEventId);
3122 ATRACE_NAME(message.c_str());
3123 }
3124
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003125 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3126 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3127 // Skip reporting pointer down outside focus to the policy.
3128 break;
3129 }
3130
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003131 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003132 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003133
3134 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003135 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003136 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003137 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003138 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3139 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003140 break;
3141 }
Chris Yef59a2f42020-10-16 12:55:26 -07003142 case EventEntry::Type::SENSOR: {
3143 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3144 break;
3145 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003146 case EventEntry::Type::CONFIGURATION_CHANGED:
3147 case EventEntry::Type::DEVICE_RESET: {
3148 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003149 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003150 break;
3151 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152 }
3153
3154 // Remember that we are waiting for this dispatch to complete.
3155 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003156 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 }
3158
3159 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003160 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003161 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003162}
3163
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003164/**
3165 * This function is purely for debugging. It helps us understand where the user interaction
3166 * was taking place. For example, if user is touching launcher, we will see a log that user
3167 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3168 * We will see both launcher and wallpaper in that list.
3169 * Once the interaction with a particular set of connections starts, no new logs will be printed
3170 * until the set of interacted connections changes.
3171 *
3172 * The following items are skipped, to reduce the logspam:
3173 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3174 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3175 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3176 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3177 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003178 */
3179void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3180 const std::vector<InputTarget>& targets) {
3181 // Skip ACTION_UP events, and all events other than keys and motions
3182 if (entry.type == EventEntry::Type::KEY) {
3183 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3184 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3185 return;
3186 }
3187 } else if (entry.type == EventEntry::Type::MOTION) {
3188 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3189 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3190 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3191 return;
3192 }
3193 } else {
3194 return; // Not a key or a motion
3195 }
3196
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003197 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003198 std::vector<sp<Connection>> newConnections;
3199 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003200 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003201 continue; // Skip windows that receive ACTION_OUTSIDE
3202 }
3203
3204 sp<IBinder> token = target.inputChannel->getConnectionToken();
3205 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003206 if (connection == nullptr) {
3207 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003208 }
3209 newConnectionTokens.insert(std::move(token));
3210 newConnections.emplace_back(connection);
3211 }
3212 if (newConnectionTokens == mInteractionConnectionTokens) {
3213 return; // no change
3214 }
3215 mInteractionConnectionTokens = newConnectionTokens;
3216
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003217 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003218 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003219 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003220 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003221 std::string message = "Interaction with: " + targetList;
3222 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003223 message += "<none>";
3224 }
3225 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3226}
3227
chaviwfd6d3512019-03-25 13:23:49 -07003228void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003229 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003230 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003231 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3232 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003233 return;
3234 }
3235
Vishnu Nairc519ff72021-01-21 08:23:08 -08003236 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003237 if (focusedToken == token) {
3238 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003239 return;
3240 }
3241
Prabir Pradhancef936d2021-07-21 16:17:52 +00003242 auto command = [this, token]() REQUIRES(mLock) {
3243 scoped_unlock unlock(mLock);
3244 mPolicy->onPointerDownOutsideFocus(token);
3245 };
3246 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247}
3248
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003249status_t InputDispatcher::publishMotionEvent(Connection& connection,
3250 DispatchEntry& dispatchEntry) const {
3251 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3252 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3253
3254 PointerCoords scaledCoords[MAX_POINTERS];
3255 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3256
3257 // Set the X and Y offset and X and Y scale depending on the input source.
3258 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003259 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003260 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3261 if (globalScaleFactor != 1.0f) {
3262 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3263 scaledCoords[i] = motionEntry.pointerCoords[i];
3264 // Don't apply window scale here since we don't want scale to affect raw
3265 // coordinates. The scale will be sent back to the client and applied
3266 // later when requesting relative coordinates.
3267 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3268 1 /* windowYScale */);
3269 }
3270 usingCoords = scaledCoords;
3271 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003272 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003273 // We don't want the dispatch target to know the coordinates
3274 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3275 scaledCoords[i].clear();
3276 }
3277 usingCoords = scaledCoords;
3278 }
3279
3280 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3281
3282 // Publish the motion event.
3283 return connection.inputPublisher
3284 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3285 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3286 std::move(hmac), dispatchEntry.resolvedAction,
3287 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3288 motionEntry.edgeFlags, motionEntry.metaState,
3289 motionEntry.buttonState, motionEntry.classification,
3290 dispatchEntry.transform, motionEntry.xPrecision,
3291 motionEntry.yPrecision, motionEntry.xCursorPosition,
3292 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3293 motionEntry.downTime, motionEntry.eventTime,
3294 motionEntry.pointerCount, motionEntry.pointerProperties,
3295 usingCoords);
3296}
3297
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003299 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003300 if (ATRACE_ENABLED()) {
3301 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003302 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003303 ATRACE_NAME(message.c_str());
3304 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003305 if (DEBUG_DISPATCH_CYCLE) {
3306 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3307 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003308
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003309 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003310 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003312 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003313 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003314
3315 // Publish the event.
3316 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003317 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3318 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003319 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003320 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3321 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003322
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003323 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003324 status = connection->inputPublisher
3325 .publishKeyEvent(dispatchEntry->seq,
3326 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3327 keyEntry.source, keyEntry.displayId,
3328 std::move(hmac), dispatchEntry->resolvedAction,
3329 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3330 keyEntry.scanCode, keyEntry.metaState,
3331 keyEntry.repeatCount, keyEntry.downTime,
3332 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003333 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003334 }
3335
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003336 case EventEntry::Type::MOTION: {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003337 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003338 break;
3339 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003340
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003341 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003342 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003343 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003344 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003345 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003346 break;
3347 }
3348
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003349 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3350 const TouchModeEntry& touchModeEntry =
3351 static_cast<const TouchModeEntry&>(eventEntry);
3352 status = connection->inputPublisher
3353 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3354 touchModeEntry.inTouchMode);
3355
3356 break;
3357 }
3358
Prabir Pradhan99987712020-11-10 18:43:05 -08003359 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3360 const auto& captureEntry =
3361 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3362 status = connection->inputPublisher
3363 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003364 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003365 break;
3366 }
3367
arthurhungb89ccb02020-12-30 16:19:01 +08003368 case EventEntry::Type::DRAG: {
3369 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3370 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3371 dragEntry.id, dragEntry.x,
3372 dragEntry.y,
3373 dragEntry.isExiting);
3374 break;
3375 }
3376
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003377 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003378 case EventEntry::Type::DEVICE_RESET:
3379 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003380 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003381 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003382 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003383 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384 }
3385
3386 // Check the result.
3387 if (status) {
3388 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003389 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003391 "This is unexpected because the wait queue is empty, so the pipe "
3392 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003393 "event to it, status=%s(%d)",
3394 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3395 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3397 } else {
3398 // Pipe is full and we are waiting for the app to finish process some events
3399 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003400 if (DEBUG_DISPATCH_CYCLE) {
3401 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3402 "waiting for the application to catch up",
3403 connection->getInputChannelName().c_str());
3404 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405 }
3406 } else {
3407 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003408 "status=%s(%d)",
3409 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3410 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3412 }
3413 return;
3414 }
3415
3416 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003417 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3418 connection->outboundQueue.end(),
3419 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003420 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003421 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003422 if (connection->responsive) {
3423 mAnrTracker.insert(dispatchEntry->timeoutTime,
3424 connection->inputChannel->getConnectionToken());
3425 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003426 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003427 }
3428}
3429
chaviw09c8d2d2020-08-24 15:48:26 -07003430std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3431 size_t size;
3432 switch (event.type) {
3433 case VerifiedInputEvent::Type::KEY: {
3434 size = sizeof(VerifiedKeyEvent);
3435 break;
3436 }
3437 case VerifiedInputEvent::Type::MOTION: {
3438 size = sizeof(VerifiedMotionEvent);
3439 break;
3440 }
3441 }
3442 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3443 return mHmacKeyManager.sign(start, size);
3444}
3445
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003446const std::array<uint8_t, 32> InputDispatcher::getSignature(
3447 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003448 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3449 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003450 // Only sign events up and down events as the purely move events
3451 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003452 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003453 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003454
3455 VerifiedMotionEvent verifiedEvent =
3456 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3457 verifiedEvent.actionMasked = actionMasked;
3458 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3459 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003460}
3461
3462const std::array<uint8_t, 32> InputDispatcher::getSignature(
3463 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3464 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3465 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3466 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003467 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003468}
3469
Michael Wrightd02c5b62014-02-10 15:10:22 -08003470void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003471 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003472 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003473 if (DEBUG_DISPATCH_CYCLE) {
3474 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3475 connection->getInputChannelName().c_str(), seq, toString(handled));
3476 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003478 if (connection->status == Connection::Status::BROKEN ||
3479 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003480 return;
3481 }
3482
3483 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003484 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3485 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3486 };
3487 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003488}
3489
3490void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003491 const sp<Connection>& connection,
3492 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003493 if (DEBUG_DISPATCH_CYCLE) {
3494 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3495 connection->getInputChannelName().c_str(), toString(notify));
3496 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003497
3498 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003499 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003500 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003501 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003502 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003503
3504 // The connection appears to be unrecoverably broken.
3505 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003506 if (connection->status == Connection::Status::NORMAL) {
3507 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508
3509 if (notify) {
3510 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003511 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3512 connection->getInputChannelName().c_str());
3513
3514 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003515 scoped_unlock unlock(mLock);
3516 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3517 };
3518 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003519 }
3520 }
3521}
3522
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003523void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3524 while (!queue.empty()) {
3525 DispatchEntry* dispatchEntry = queue.front();
3526 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003527 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528 }
3529}
3530
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003531void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003533 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534 }
3535 delete dispatchEntry;
3536}
3537
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003538int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3539 std::scoped_lock _l(mLock);
3540 sp<Connection> connection = getConnectionLocked(connectionToken);
3541 if (connection == nullptr) {
3542 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3543 connectionToken.get(), events);
3544 return 0; // remove the callback
3545 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003546
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003547 bool notify;
3548 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3549 if (!(events & ALOOPER_EVENT_INPUT)) {
3550 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3551 "events=0x%x",
3552 connection->getInputChannelName().c_str(), events);
3553 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003554 }
3555
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003556 nsecs_t currentTime = now();
3557 bool gotOne = false;
3558 status_t status = OK;
3559 for (;;) {
3560 Result<InputPublisher::ConsumerResponse> result =
3561 connection->inputPublisher.receiveConsumerResponse();
3562 if (!result.ok()) {
3563 status = result.error().code();
3564 break;
3565 }
3566
3567 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3568 const InputPublisher::Finished& finish =
3569 std::get<InputPublisher::Finished>(*result);
3570 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3571 finish.consumeTime);
3572 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003573 if (shouldReportMetricsForConnection(*connection)) {
3574 const InputPublisher::Timeline& timeline =
3575 std::get<InputPublisher::Timeline>(*result);
3576 mLatencyTracker
3577 .trackGraphicsLatency(timeline.inputEventId,
3578 connection->inputChannel->getConnectionToken(),
3579 std::move(timeline.graphicsTimeline));
3580 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003581 }
3582 gotOne = true;
3583 }
3584 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003585 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003586 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003587 return 1;
3588 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 }
3590
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003591 notify = status != DEAD_OBJECT || !connection->monitor;
3592 if (notify) {
3593 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3594 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3595 status);
3596 }
3597 } else {
3598 // Monitor channels are never explicitly unregistered.
3599 // We do it automatically when the remote endpoint is closed so don't warn about them.
3600 const bool stillHaveWindowHandle =
3601 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3602 notify = !connection->monitor && stillHaveWindowHandle;
3603 if (notify) {
3604 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3605 connection->getInputChannelName().c_str(), events);
3606 }
3607 }
3608
3609 // Remove the channel.
3610 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3611 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612}
3613
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003614void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003616 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003617 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618 }
3619}
3620
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003621void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003622 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003623 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003624 for (const Monitor& monitor : monitors) {
3625 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003626 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003627 }
3628}
3629
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003631 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003632 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003633 if (connection == nullptr) {
3634 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003635 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003636
3637 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638}
3639
3640void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3641 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003642 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643 return;
3644 }
3645
3646 nsecs_t currentTime = now();
3647
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003648 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003649 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003650
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003651 if (cancelationEvents.empty()) {
3652 return;
3653 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003654 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3655 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3656 "with reality: %s, mode=%d.",
3657 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3658 options.mode);
3659 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003660
Arthur Hungb3307ee2021-10-14 10:57:37 +00003661 std::string reason = std::string("reason=").append(options.reason);
3662 android_log_event_list(LOGTAG_INPUT_CANCEL)
3663 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3664
Svet Ganov5d3bc372020-01-26 23:11:07 -08003665 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003666 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003667 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3668 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003669 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003670 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003671 target.globalScaleFactor = windowInfo->globalScaleFactor;
3672 }
3673 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003674 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003675
hongzuo liu95785e22022-09-06 02:51:35 +00003676 const bool wasEmpty = connection->outboundQueue.empty();
3677
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003678 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003679 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003680 switch (cancelationEventEntry->type) {
3681 case EventEntry::Type::KEY: {
3682 logOutboundKeyDetails("cancel - ",
3683 static_cast<const KeyEntry&>(*cancelationEventEntry));
3684 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003685 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003686 case EventEntry::Type::MOTION: {
3687 logOutboundMotionDetails("cancel - ",
3688 static_cast<const MotionEntry&>(*cancelationEventEntry));
3689 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003691 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003692 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003693 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3694 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003695 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003696 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003697 break;
3698 }
3699 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003700 case EventEntry::Type::DEVICE_RESET:
3701 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003702 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003703 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003704 break;
3705 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706 }
3707
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003708 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003709 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003711
hongzuo liu95785e22022-09-06 02:51:35 +00003712 // If the outbound queue was previously empty, start the dispatch cycle going.
3713 if (wasEmpty && !connection->outboundQueue.empty()) {
3714 startDispatchCycleLocked(currentTime, connection);
3715 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716}
3717
Svet Ganov5d3bc372020-01-26 23:11:07 -08003718void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003719 const nsecs_t downTime, const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003720 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003721 return;
3722 }
3723
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003724 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003725 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003726
3727 if (downEvents.empty()) {
3728 return;
3729 }
3730
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003731 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003732 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3733 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003734 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003735
3736 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003737 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003738 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3739 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003740 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003741 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003742 target.globalScaleFactor = windowInfo->globalScaleFactor;
3743 }
3744 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003745 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003746
hongzuo liu95785e22022-09-06 02:51:35 +00003747 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003748 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003749 switch (downEventEntry->type) {
3750 case EventEntry::Type::MOTION: {
3751 logOutboundMotionDetails("down - ",
3752 static_cast<const MotionEntry&>(*downEventEntry));
3753 break;
3754 }
3755
3756 case EventEntry::Type::KEY:
3757 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003758 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003759 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003760 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003761 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003762 case EventEntry::Type::SENSOR:
3763 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003764 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003765 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003766 break;
3767 }
3768 }
3769
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003770 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003771 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003772 }
3773
hongzuo liu95785e22022-09-06 02:51:35 +00003774 // If the outbound queue was previously empty, start the dispatch cycle going.
3775 if (wasEmpty && !connection->outboundQueue.empty()) {
3776 startDispatchCycleLocked(downTime, connection);
3777 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003778}
3779
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003780std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003781 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 ALOG_ASSERT(pointerIds.value != 0);
3783
3784 uint32_t splitPointerIndexMap[MAX_POINTERS];
3785 PointerProperties splitPointerProperties[MAX_POINTERS];
3786 PointerCoords splitPointerCoords[MAX_POINTERS];
3787
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003788 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789 uint32_t splitPointerCount = 0;
3790
3791 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003792 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003794 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795 uint32_t pointerId = uint32_t(pointerProperties.id);
3796 if (pointerIds.hasBit(pointerId)) {
3797 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3798 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3799 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003800 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003801 splitPointerCount += 1;
3802 }
3803 }
3804
3805 if (splitPointerCount != pointerIds.count()) {
3806 // This is bad. We are missing some of the pointers that we expected to deliver.
3807 // Most likely this indicates that we received an ACTION_MOVE events that has
3808 // different pointer ids than we expected based on the previous ACTION_DOWN
3809 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3810 // in this way.
3811 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003812 "we expected there to be %d pointers. This probably means we received "
3813 "a broken sequence of pointer ids from the input device.",
3814 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003815 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003816 }
3817
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003818 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003820 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3821 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3823 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003824 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003825 uint32_t pointerId = uint32_t(pointerProperties.id);
3826 if (pointerIds.hasBit(pointerId)) {
3827 if (pointerIds.count() == 1) {
3828 // The first/last pointer went down/up.
3829 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003830 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003831 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3832 ? AMOTION_EVENT_ACTION_CANCEL
3833 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834 } else {
3835 // A secondary pointer went down/up.
3836 uint32_t splitPointerIndex = 0;
3837 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3838 splitPointerIndex += 1;
3839 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003840 action = maskedAction |
3841 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003842 }
3843 } else {
3844 // An unrelated pointer changed.
3845 action = AMOTION_EVENT_ACTION_MOVE;
3846 }
3847 }
3848
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003849 if (action == AMOTION_EVENT_ACTION_DOWN) {
3850 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3851 "Split motion event has mismatching downTime and eventTime for "
3852 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3853 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3854 }
3855
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003856 int32_t newId = mIdGenerator.nextId();
3857 if (ATRACE_ENABLED()) {
3858 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3859 ") to MotionEvent(id=0x%" PRIx32 ").",
3860 originalMotionEntry.id, newId);
3861 ATRACE_NAME(message.c_str());
3862 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003863 std::unique_ptr<MotionEntry> splitMotionEntry =
3864 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3865 originalMotionEntry.deviceId, originalMotionEntry.source,
3866 originalMotionEntry.displayId,
3867 originalMotionEntry.policyFlags, action,
3868 originalMotionEntry.actionButton,
3869 originalMotionEntry.flags, originalMotionEntry.metaState,
3870 originalMotionEntry.buttonState,
3871 originalMotionEntry.classification,
3872 originalMotionEntry.edgeFlags,
3873 originalMotionEntry.xPrecision,
3874 originalMotionEntry.yPrecision,
3875 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003876 originalMotionEntry.yCursorPosition, splitDownTime,
3877 splitPointerCount, splitPointerProperties,
3878 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003880 if (originalMotionEntry.injectionState) {
3881 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003882 splitMotionEntry->injectionState->refCount += 1;
3883 }
3884
3885 return splitMotionEntry;
3886}
3887
3888void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003889 if (DEBUG_INBOUND_EVENT_DETAILS) {
3890 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3891 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003892
Antonio Kantekf16f2832021-09-28 04:39:20 +00003893 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003895 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003897 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3898 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3899 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900 } // release lock
3901
3902 if (needWake) {
3903 mLooper->wake();
3904 }
3905}
3906
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003907/**
3908 * If one of the meta shortcuts is detected, process them here:
3909 * Meta + Backspace -> generate BACK
3910 * Meta + Enter -> generate HOME
3911 * This will potentially overwrite keyCode and metaState.
3912 */
3913void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003914 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003915 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3916 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3917 if (keyCode == AKEYCODE_DEL) {
3918 newKeyCode = AKEYCODE_BACK;
3919 } else if (keyCode == AKEYCODE_ENTER) {
3920 newKeyCode = AKEYCODE_HOME;
3921 }
3922 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003923 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003924 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003925 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003926 keyCode = newKeyCode;
3927 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3928 }
3929 } else if (action == AKEY_EVENT_ACTION_UP) {
3930 // In order to maintain a consistent stream of up and down events, check to see if the key
3931 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3932 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003933 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003934 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003935 auto replacementIt = mReplacedKeys.find(replacement);
3936 if (replacementIt != mReplacedKeys.end()) {
3937 keyCode = replacementIt->second;
3938 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003939 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3940 }
3941 }
3942}
3943
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003945 if (DEBUG_INBOUND_EVENT_DETAILS) {
3946 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3947 "policyFlags=0x%x, action=0x%x, "
3948 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3949 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3950 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3951 args->downTime);
3952 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953 if (!validateKeyEvent(args->action)) {
3954 return;
3955 }
3956
3957 uint32_t policyFlags = args->policyFlags;
3958 int32_t flags = args->flags;
3959 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003960 // InputDispatcher tracks and generates key repeats on behalf of
3961 // whatever notifies it, so repeatCount should always be set to 0
3962 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3964 policyFlags |= POLICY_FLAG_VIRTUAL;
3965 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3966 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967 if (policyFlags & POLICY_FLAG_FUNCTION) {
3968 metaState |= AMETA_FUNCTION_ON;
3969 }
3970
3971 policyFlags |= POLICY_FLAG_TRUSTED;
3972
Michael Wright78f24442014-08-06 15:55:28 -07003973 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003974 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003975
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003977 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003978 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3979 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980
Michael Wright2b3c3302018-03-02 17:19:13 +00003981 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003982 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003983 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3984 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003985 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003986 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987
Antonio Kantekf16f2832021-09-28 04:39:20 +00003988 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003989 { // acquire lock
3990 mLock.lock();
3991
3992 if (shouldSendKeyToInputFilterLocked(args)) {
3993 mLock.unlock();
3994
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003995 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3997 return; // event was consumed by the filter
3998 }
3999
4000 mLock.lock();
4001 }
4002
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004003 std::unique_ptr<KeyEntry> newEntry =
4004 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4005 args->displayId, policyFlags, args->action, flags,
4006 keyCode, args->scanCode, metaState, repeatCount,
4007 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004009 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004010 mLock.unlock();
4011 } // release lock
4012
4013 if (needWake) {
4014 mLooper->wake();
4015 }
4016}
4017
4018bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4019 return mInputFilterEnabled;
4020}
4021
4022void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004023 if (DEBUG_INBOUND_EVENT_DETAILS) {
4024 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4025 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004026 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004027 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4028 "yCursorPosition=%f, downTime=%" PRId64,
4029 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004030 args->policyFlags, MotionEvent::actionToString(args->action).c_str(),
4031 args->actionButton, args->flags, args->metaState, args->buttonState, args->edgeFlags,
4032 args->xPrecision, args->yPrecision, args->xCursorPosition, args->yCursorPosition,
4033 args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004034 for (uint32_t i = 0; i < args->pointerCount; i++) {
4035 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4036 "x=%f, y=%f, pressure=%f, size=%f, "
4037 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4038 "orientation=%f",
4039 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4040 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4041 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4042 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4043 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4044 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4045 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4046 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4047 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4048 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4049 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004050 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004051 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4052 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004053 return;
4054 }
4055
4056 uint32_t policyFlags = args->policyFlags;
4057 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004058
4059 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004060 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004061 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4062 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004063 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004064 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065
Antonio Kantekf16f2832021-09-28 04:39:20 +00004066 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067 { // acquire lock
4068 mLock.lock();
4069
4070 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004071 ui::Transform displayTransform;
4072 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4073 displayTransform = it->second.transform;
4074 }
4075
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076 mLock.unlock();
4077
4078 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004079 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4080 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004081 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004082 displayTransform, args->xPrecision, args->yPrecision,
4083 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004084 args->downTime, args->eventTime, args->pointerCount,
4085 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086
4087 policyFlags |= POLICY_FLAG_FILTERED;
4088 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4089 return; // event was consumed by the filter
4090 }
4091
4092 mLock.lock();
4093 }
4094
4095 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004096 std::unique_ptr<MotionEntry> newEntry =
4097 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4098 args->source, args->displayId, policyFlags,
4099 args->action, args->actionButton, args->flags,
4100 args->metaState, args->buttonState,
4101 args->classification, args->edgeFlags,
4102 args->xPrecision, args->yPrecision,
4103 args->xCursorPosition, args->yCursorPosition,
4104 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004105 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004106
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004107 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4108 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4109 !mInputFilterEnabled) {
4110 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4111 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4112 }
4113
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004114 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004115 mLock.unlock();
4116 } // release lock
4117
4118 if (needWake) {
4119 mLooper->wake();
4120 }
4121}
4122
Chris Yef59a2f42020-10-16 12:55:26 -07004123void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004124 if (DEBUG_INBOUND_EVENT_DETAILS) {
4125 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4126 " sensorType=%s",
4127 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004128 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004129 }
Chris Yef59a2f42020-10-16 12:55:26 -07004130
Antonio Kantekf16f2832021-09-28 04:39:20 +00004131 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004132 { // acquire lock
4133 mLock.lock();
4134
4135 // Just enqueue a new sensor event.
4136 std::unique_ptr<SensorEntry> newEntry =
4137 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4138 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4139 args->sensorType, args->accuracy,
4140 args->accuracyChanged, args->values);
4141
4142 needWake = enqueueInboundEventLocked(std::move(newEntry));
4143 mLock.unlock();
4144 } // release lock
4145
4146 if (needWake) {
4147 mLooper->wake();
4148 }
4149}
4150
Chris Yefb552902021-02-03 17:18:37 -08004151void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004152 if (DEBUG_INBOUND_EVENT_DETAILS) {
4153 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4154 args->deviceId, args->isOn);
4155 }
Chris Yefb552902021-02-03 17:18:37 -08004156 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4157}
4158
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004160 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161}
4162
4163void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004164 if (DEBUG_INBOUND_EVENT_DETAILS) {
4165 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4166 "switchMask=0x%08x",
4167 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4168 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169
4170 uint32_t policyFlags = args->policyFlags;
4171 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004172 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173}
4174
4175void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004176 if (DEBUG_INBOUND_EVENT_DETAILS) {
4177 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4178 args->deviceId);
4179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180
Antonio Kantekf16f2832021-09-28 04:39:20 +00004181 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004183 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004185 std::unique_ptr<DeviceResetEntry> newEntry =
4186 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4187 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188 } // release lock
4189
4190 if (needWake) {
4191 mLooper->wake();
4192 }
4193}
4194
Prabir Pradhan7e186182020-11-10 13:56:45 -08004195void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004196 if (DEBUG_INBOUND_EVENT_DETAILS) {
4197 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004198 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004199 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004200
Antonio Kantekf16f2832021-09-28 04:39:20 +00004201 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004202 { // acquire lock
4203 std::scoped_lock _l(mLock);
4204 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004205 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004206 needWake = enqueueInboundEventLocked(std::move(entry));
4207 } // release lock
4208
4209 if (needWake) {
4210 mLooper->wake();
4211 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004212}
4213
Prabir Pradhan5735a322022-04-11 17:23:34 +00004214InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4215 std::optional<int32_t> targetUid,
4216 InputEventInjectionSync syncMode,
4217 std::chrono::milliseconds timeout,
4218 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004219 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004220 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4221 "policyFlags=0x%08x",
4222 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4223 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004224 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004225 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226
Prabir Pradhan5735a322022-04-11 17:23:34 +00004227 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004229 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004230 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4231 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4232 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4233 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4234 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004235 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004236 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004237 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004238 }
4239
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004240 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004242 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004243 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4244 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004245 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004246 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004247 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004249 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004250 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4251 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4252 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004253 int32_t keyCode = incomingKey.getKeyCode();
4254 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004255 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004256 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004257 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004258 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004259 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4260 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4261 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004263 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4264 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004265 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004266
4267 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4268 android::base::Timer t;
4269 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4270 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4271 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4272 std::to_string(t.duration().count()).c_str());
4273 }
4274 }
4275
4276 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004277 std::unique_ptr<KeyEntry> injectedEntry =
4278 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004279 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004280 incomingKey.getDisplayId(), policyFlags, action,
4281 flags, keyCode, incomingKey.getScanCode(), metaState,
4282 incomingKey.getRepeatCount(),
4283 incomingKey.getDownTime());
4284 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004285 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286 }
4287
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004288 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004289 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004290 const int32_t action = motionEvent.getAction();
4291 const bool isPointerEvent =
4292 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4293 // If a pointer event has no displayId specified, inject it to the default display.
4294 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4295 ? ADISPLAY_ID_DEFAULT
4296 : event->getDisplayId();
4297 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004298 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004299 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004300 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004301 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004302 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004303 }
4304
4305 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004306 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004307 android::base::Timer t;
4308 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4309 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4310 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4311 std::to_string(t.duration().count()).c_str());
4312 }
4313 }
4314
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004315 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4316 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4317 }
4318
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004319 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004320 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4321 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004322 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004323 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4324 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004325 displayId, policyFlags, action, actionButton,
4326 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004327 motionEvent.getButtonState(),
4328 motionEvent.getClassification(),
4329 motionEvent.getEdgeFlags(),
4330 motionEvent.getXPrecision(),
4331 motionEvent.getYPrecision(),
4332 motionEvent.getRawXCursorPosition(),
4333 motionEvent.getRawYCursorPosition(),
4334 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004335 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004336 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004337 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004338 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004339 sampleEventTimes += 1;
4340 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004341 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004342 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4343 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004344 displayId, policyFlags, action, actionButton,
4345 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004346 motionEvent.getButtonState(),
4347 motionEvent.getClassification(),
4348 motionEvent.getEdgeFlags(),
4349 motionEvent.getXPrecision(),
4350 motionEvent.getYPrecision(),
4351 motionEvent.getRawXCursorPosition(),
4352 motionEvent.getRawYCursorPosition(),
4353 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004354 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004355 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004356 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4357 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004358 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004359 }
4360 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004362
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004363 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004364 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004365 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 }
4367
Prabir Pradhan5735a322022-04-11 17:23:34 +00004368 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004369 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004370 injectionState->injectionIsAsync = true;
4371 }
4372
4373 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004374 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375
4376 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004377 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004378 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004379 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380 }
4381
4382 mLock.unlock();
4383
4384 if (needWake) {
4385 mLooper->wake();
4386 }
4387
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004388 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004390 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004392 if (syncMode == InputEventInjectionSync::NONE) {
4393 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004394 } else {
4395 for (;;) {
4396 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004397 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004398 break;
4399 }
4400
4401 nsecs_t remainingTimeout = endTime - now();
4402 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004403 if (DEBUG_INJECTION) {
4404 ALOGD("injectInputEvent - Timed out waiting for injection result "
4405 "to become available.");
4406 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004407 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004408 break;
4409 }
4410
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004411 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004412 }
4413
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004414 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4415 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004416 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004417 if (DEBUG_INJECTION) {
4418 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4419 injectionState->pendingForegroundDispatches);
4420 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421 nsecs_t remainingTimeout = endTime - now();
4422 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004423 if (DEBUG_INJECTION) {
4424 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4425 "dispatches to finish.");
4426 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004427 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004428 break;
4429 }
4430
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004431 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004432 }
4433 }
4434 }
4435
4436 injectionState->release();
4437 } // release lock
4438
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004439 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004440 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004441 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004442
4443 return injectionResult;
4444}
4445
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004446std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004447 std::array<uint8_t, 32> calculatedHmac;
4448 std::unique_ptr<VerifiedInputEvent> result;
4449 switch (event.getType()) {
4450 case AINPUT_EVENT_TYPE_KEY: {
4451 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4452 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4453 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004454 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004455 break;
4456 }
4457 case AINPUT_EVENT_TYPE_MOTION: {
4458 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4459 VerifiedMotionEvent verifiedMotionEvent =
4460 verifiedMotionEventFromMotionEvent(motionEvent);
4461 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004462 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004463 break;
4464 }
4465 default: {
4466 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4467 return nullptr;
4468 }
4469 }
4470 if (calculatedHmac == INVALID_HMAC) {
4471 return nullptr;
4472 }
4473 if (calculatedHmac != event.getHmac()) {
4474 return nullptr;
4475 }
4476 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004477}
4478
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004479void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004480 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004481 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004482 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004483 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004484 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004485 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004486
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004487 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004488 // Log the outcome since the injector did not wait for the injection result.
4489 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004490 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004491 ALOGV("Asynchronous input event injection succeeded.");
4492 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004493 case InputEventInjectionResult::TARGET_MISMATCH:
4494 ALOGV("Asynchronous input event injection target mismatch.");
4495 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004496 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004497 ALOGW("Asynchronous input event injection failed.");
4498 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004499 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004500 ALOGW("Asynchronous input event injection timed out.");
4501 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004502 case InputEventInjectionResult::PENDING:
4503 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4504 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505 }
4506 }
4507
4508 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004509 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510 }
4511}
4512
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004513void InputDispatcher::transformMotionEntryForInjectionLocked(
4514 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004515 // Input injection works in the logical display coordinate space, but the input pipeline works
4516 // display space, so we need to transform the injected events accordingly.
4517 const auto it = mDisplayInfos.find(entry.displayId);
4518 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004519 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004520
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004521 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4522 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4523 const vec2 cursor =
4524 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4525 {entry.xCursorPosition, entry.yCursorPosition});
4526 entry.xCursorPosition = cursor.x;
4527 entry.yCursorPosition = cursor.y;
4528 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004529 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004530 entry.pointerCoords[i] =
4531 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4532 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004533 }
4534}
4535
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004536void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4537 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004538 if (injectionState) {
4539 injectionState->pendingForegroundDispatches += 1;
4540 }
4541}
4542
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004543void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4544 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004545 if (injectionState) {
4546 injectionState->pendingForegroundDispatches -= 1;
4547
4548 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004549 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004550 }
4551 }
4552}
4553
chaviw98318de2021-05-19 16:45:23 -05004554const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004555 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004556 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004557 auto it = mWindowHandlesByDisplay.find(displayId);
4558 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004559}
4560
chaviw98318de2021-05-19 16:45:23 -05004561sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004562 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004563 if (windowHandleToken == nullptr) {
4564 return nullptr;
4565 }
4566
Arthur Hungb92218b2018-08-14 12:00:21 +08004567 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004568 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4569 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004570 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004571 return windowHandle;
4572 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004573 }
4574 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004575 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004576}
4577
chaviw98318de2021-05-19 16:45:23 -05004578sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4579 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004580 if (windowHandleToken == nullptr) {
4581 return nullptr;
4582 }
4583
chaviw98318de2021-05-19 16:45:23 -05004584 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004585 if (windowHandle->getToken() == windowHandleToken) {
4586 return windowHandle;
4587 }
4588 }
4589 return nullptr;
4590}
4591
chaviw98318de2021-05-19 16:45:23 -05004592sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4593 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004594 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004595 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4596 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004597 if (handle->getId() == windowHandle->getId() &&
4598 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004599 if (windowHandle->getInfo()->displayId != it.first) {
4600 ALOGE("Found window %s in display %" PRId32
4601 ", but it should belong to display %" PRId32,
4602 windowHandle->getName().c_str(), it.first,
4603 windowHandle->getInfo()->displayId);
4604 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004605 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004606 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004607 }
4608 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004609 return nullptr;
4610}
4611
chaviw98318de2021-05-19 16:45:23 -05004612sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004613 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4614 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004615}
4616
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004617bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4618 const MotionEntry& motionEntry) const {
4619 const WindowInfo& info = *window->getInfo();
4620
4621 // Skip spy window targets that are not valid for targeted injection.
4622 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004623 return false;
4624 }
4625
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004626 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4627 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4628 return false;
4629 }
4630
4631 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4632 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4633 window->getName().c_str());
4634 return false;
4635 }
4636
4637 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004638 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004639 ALOGW("Not sending touch to %s because there's no corresponding connection",
4640 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004641 return false;
4642 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004643
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004644 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004645 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004646 return false;
4647 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004648
4649 // Drop events that can't be trusted due to occlusion
4650 const auto [x, y] = resolveTouchedPosition(motionEntry);
4651 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4652 if (!isTouchTrustedLocked(occlusionInfo)) {
4653 if (DEBUG_TOUCH_OCCLUSION) {
4654 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4655 for (const auto& log : occlusionInfo.debugInfo) {
4656 ALOGD("%s", log.c_str());
4657 }
4658 }
4659 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4660 occlusionInfo.obscuringUid);
4661 return false;
4662 }
4663
4664 // Drop touch events if requested by input feature
4665 if (shouldDropInput(motionEntry, window)) {
4666 return false;
4667 }
4668
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004669 return true;
4670}
4671
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004672std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4673 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004674 auto connectionIt = mConnectionsByToken.find(token);
4675 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004676 return nullptr;
4677 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004678 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004679}
4680
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004681void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004682 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4683 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004684 // Remove all handles on a display if there are no windows left.
4685 mWindowHandlesByDisplay.erase(displayId);
4686 return;
4687 }
4688
4689 // Since we compare the pointer of input window handles across window updates, we need
4690 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004691 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4692 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4693 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004694 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004695 }
4696
chaviw98318de2021-05-19 16:45:23 -05004697 std::vector<sp<WindowInfoHandle>> newHandles;
4698 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004699 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004700 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004701 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004702 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004703 const bool canReceiveInput =
4704 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4705 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004706 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004707 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004708 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004709 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004710 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004711 }
4712
4713 if (info->displayId != displayId) {
4714 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4715 handle->getName().c_str(), displayId, info->displayId);
4716 continue;
4717 }
4718
Robert Carredd13602020-04-13 17:24:34 -07004719 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4720 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004721 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004722 oldHandle->updateFrom(handle);
4723 newHandles.push_back(oldHandle);
4724 } else {
4725 newHandles.push_back(handle);
4726 }
4727 }
4728
4729 // Insert or replace
4730 mWindowHandlesByDisplay[displayId] = newHandles;
4731}
4732
Arthur Hung72d8dc32020-03-28 00:48:39 +00004733void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004734 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004735 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004736 { // acquire lock
4737 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004738 for (const auto& [displayId, handles] : handlesPerDisplay) {
4739 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004740 }
4741 }
4742 // Wake up poll loop since it may need to make new input dispatching choices.
4743 mLooper->wake();
4744}
4745
Arthur Hungb92218b2018-08-14 12:00:21 +08004746/**
4747 * Called from InputManagerService, update window handle list by displayId that can receive input.
4748 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4749 * If set an empty list, remove all handles from the specific display.
4750 * For focused handle, check if need to change and send a cancel event to previous one.
4751 * For removed handle, check if need to send a cancel event if already in touch.
4752 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004753void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004754 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004755 if (DEBUG_FOCUS) {
4756 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004757 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004758 windowList += iwh->getName() + " ";
4759 }
4760 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4761 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004762
Prabir Pradhand65552b2021-10-07 11:23:50 -07004763 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004764 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004765 const WindowInfo& info = *window->getInfo();
4766
4767 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004768 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004769 if (noInputWindow && window->getToken() != nullptr) {
4770 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4771 window->getName().c_str());
4772 window->releaseChannel();
4773 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004774
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004775 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004776 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4777 !info.inputConfig.test(
4778 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004779 "%s has feature SPY, but is not a trusted overlay.",
4780 window->getName().c_str());
4781
Prabir Pradhand65552b2021-10-07 11:23:50 -07004782 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004783 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4784 !info.inputConfig.test(
4785 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004786 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4787 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004788 }
4789
Arthur Hung72d8dc32020-03-28 00:48:39 +00004790 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004791 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004792
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004793 // Save the old windows' orientation by ID before it gets updated.
4794 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004795 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004796 oldWindowOrientations.emplace(handle->getId(),
4797 handle->getInfo()->transform.getOrientation());
4798 }
4799
chaviw98318de2021-05-19 16:45:23 -05004800 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004801
chaviw98318de2021-05-19 16:45:23 -05004802 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004803 if (mLastHoverWindowHandle &&
4804 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4805 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004806 mLastHoverWindowHandle = nullptr;
4807 }
4808
Vishnu Nairc519ff72021-01-21 08:23:08 -08004809 std::optional<FocusResolver::FocusChanges> changes =
4810 mFocusResolver.setInputWindows(displayId, windowHandles);
4811 if (changes) {
4812 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004815 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4816 mTouchStatesByDisplay.find(displayId);
4817 if (stateIt != mTouchStatesByDisplay.end()) {
4818 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004819 for (size_t i = 0; i < state.windows.size();) {
4820 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004821 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004822 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004823 ALOGD("Touched window was removed: %s in display %" PRId32,
4824 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004825 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004826 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004827 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4828 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004829 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00004830 "touched window was removed");
4831 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004832 // Since we are about to drop the touch, cancel the events for the wallpaper as
4833 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004834 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004835 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4836 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004837 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4838 if (wallpaper != nullptr) {
4839 sp<Connection> wallpaperConnection =
4840 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004841 if (wallpaperConnection != nullptr) {
4842 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4843 options);
4844 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004845 }
4846 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004848 state.windows.erase(state.windows.begin() + i);
4849 } else {
4850 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851 }
4852 }
arthurhungb89ccb02020-12-30 16:19:01 +08004853
arthurhung6d4bed92021-03-17 11:59:33 +08004854 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004855 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004856 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004857 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004858 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004859 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4860 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004861 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004862 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004863 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004864
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004865 // Determine if the orientation of any of the input windows have changed, and cancel all
4866 // pointer events if necessary.
4867 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4868 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4869 if (newWindowHandle != nullptr &&
4870 newWindowHandle->getInfo()->transform.getOrientation() !=
4871 oldWindowOrientations[oldWindowHandle->getId()]) {
4872 std::shared_ptr<InputChannel> inputChannel =
4873 getInputChannelLocked(newWindowHandle->getToken());
4874 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004875 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004876 "touched window's orientation changed");
4877 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004878 }
4879 }
4880 }
4881
Arthur Hung72d8dc32020-03-28 00:48:39 +00004882 // Release information for windows that are no longer present.
4883 // This ensures that unused input channels are released promptly.
4884 // Otherwise, they might stick around until the window handle is destroyed
4885 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004886 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004887 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004888 if (DEBUG_FOCUS) {
4889 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004890 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004891 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004892 }
chaviw291d88a2019-02-14 10:33:58 -08004893 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894}
4895
4896void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004897 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004898 if (DEBUG_FOCUS) {
4899 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4900 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4901 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004902 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004903 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004904 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004905 } // release lock
4906
4907 // Wake up poll loop since it may need to make new input dispatching choices.
4908 mLooper->wake();
4909}
4910
Vishnu Nair599f1412021-06-21 10:39:58 -07004911void InputDispatcher::setFocusedApplicationLocked(
4912 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4913 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4914 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4915
4916 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4917 return; // This application is already focused. No need to wake up or change anything.
4918 }
4919
4920 // Set the new application handle.
4921 if (inputApplicationHandle != nullptr) {
4922 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4923 } else {
4924 mFocusedApplicationHandlesByDisplay.erase(displayId);
4925 }
4926
4927 // No matter what the old focused application was, stop waiting on it because it is
4928 // no longer focused.
4929 resetNoFocusedWindowTimeoutLocked();
4930}
4931
Tiger Huang721e26f2018-07-24 22:26:19 +08004932/**
4933 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4934 * the display not specified.
4935 *
4936 * We track any unreleased events for each window. If a window loses the ability to receive the
4937 * released event, we will send a cancel event to it. So when the focused display is changed, we
4938 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4939 * display. The display-specified events won't be affected.
4940 */
4941void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004942 if (DEBUG_FOCUS) {
4943 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4944 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004945 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004946 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004947
4948 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004949 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004950 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004951 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004952 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004953 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004954 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004955 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00004956 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004957 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004958 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004959 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4960 }
4961 }
4962 mFocusedDisplayId = displayId;
4963
Chris Ye3c2d6f52020-08-09 10:39:48 -07004964 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004965 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004966 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004967
Vishnu Nairad321cd2020-08-20 16:40:21 -07004968 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004969 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004970 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004971 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004972 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004973 }
4974 }
4975 }
4976
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004977 if (DEBUG_FOCUS) {
4978 logDispatchStateLocked();
4979 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004980 } // release lock
4981
4982 // Wake up poll loop since it may need to make new input dispatching choices.
4983 mLooper->wake();
4984}
4985
Michael Wrightd02c5b62014-02-10 15:10:22 -08004986void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004987 if (DEBUG_FOCUS) {
4988 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4989 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990
4991 bool changed;
4992 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004993 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004994
4995 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4996 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004997 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004998 }
4999
5000 if (mDispatchEnabled && !enabled) {
5001 resetAndDropEverythingLocked("dispatcher is being disabled");
5002 }
5003
5004 mDispatchEnabled = enabled;
5005 mDispatchFrozen = frozen;
5006 changed = true;
5007 } else {
5008 changed = false;
5009 }
5010
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005011 if (DEBUG_FOCUS) {
5012 logDispatchStateLocked();
5013 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005014 } // release lock
5015
5016 if (changed) {
5017 // Wake up poll loop since it may need to make new input dispatching choices.
5018 mLooper->wake();
5019 }
5020}
5021
5022void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005023 if (DEBUG_FOCUS) {
5024 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005026
5027 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005028 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005029
5030 if (mInputFilterEnabled == enabled) {
5031 return;
5032 }
5033
5034 mInputFilterEnabled = enabled;
5035 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5036 } // release lock
5037
5038 // Wake up poll loop since there might be work to do to drop everything.
5039 mLooper->wake();
5040}
5041
Antonio Kanteka042c022022-07-06 16:51:07 -07005042bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5043 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005044 bool needWake = false;
5045 {
5046 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005047 ALOGD_IF(DEBUG_TOUCH_MODE,
5048 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5049 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5050 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5051 mTouchModePerDisplay.count(displayId) == 0
5052 ? "not set"
5053 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5054
Antonio Kantek15beb512022-06-13 22:35:41 +00005055 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5056 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005057 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005058 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005059 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005060 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5061 !recentWindowsAreOwnedByLocked(pid, uid)) {
5062 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5063 "window nor none of the previously interacted window",
5064 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005065 return false;
5066 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005067 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005068 mTouchModePerDisplay[displayId] = inTouchMode;
5069 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5070 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005071 needWake = enqueueInboundEventLocked(std::move(entry));
5072 } // release lock
5073
5074 if (needWake) {
5075 mLooper->wake();
5076 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005077 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005078}
5079
Antonio Kantek48710e42022-03-24 14:19:30 -07005080bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5081 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5082 if (focusedToken == nullptr) {
5083 return false;
5084 }
5085 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5086 return isWindowOwnedBy(windowHandle, pid, uid);
5087}
5088
5089bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5090 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5091 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5092 const sp<WindowInfoHandle> windowHandle =
5093 getWindowHandleLocked(connectionToken);
5094 return isWindowOwnedBy(windowHandle, pid, uid);
5095 }) != mInteractionConnectionTokens.end();
5096}
5097
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005098void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5099 if (opacity < 0 || opacity > 1) {
5100 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5101 return;
5102 }
5103
5104 std::scoped_lock lock(mLock);
5105 mMaximumObscuringOpacityForTouch = opacity;
5106}
5107
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005108std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5109InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005110 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5111 for (TouchedWindow& w : state.windows) {
5112 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005113 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005114 }
5115 }
5116 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005117 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005118}
5119
arthurhungb89ccb02020-12-30 16:19:01 +08005120bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5121 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005122 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005123 if (DEBUG_FOCUS) {
5124 ALOGD("Trivial transfer to same window.");
5125 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005126 return true;
5127 }
5128
Michael Wrightd02c5b62014-02-10 15:10:22 -08005129 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005130 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005131
Arthur Hungabbb9d82021-09-01 14:52:30 +00005132 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005133 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005134 if (state == nullptr || touchedWindow == nullptr) {
5135 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005136 return false;
5137 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005138
Arthur Hungabbb9d82021-09-01 14:52:30 +00005139 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5140 if (toWindowHandle == nullptr) {
5141 ALOGW("Cannot transfer focus because to window not found.");
5142 return false;
5143 }
5144
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005145 if (DEBUG_FOCUS) {
5146 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005147 touchedWindow->windowHandle->getName().c_str(),
5148 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005149 }
5150
Arthur Hungabbb9d82021-09-01 14:52:30 +00005151 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005152 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005153 BitSet32 pointerIds = touchedWindow->pointerIds;
5154 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005155
Arthur Hungabbb9d82021-09-01 14:52:30 +00005156 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005157 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005158 ftl::Flags<InputTarget::Flags> newTargetFlags =
5159 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005160 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005161 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005162 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005163 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005164
Arthur Hungabbb9d82021-09-01 14:52:30 +00005165 // Store the dragging window.
5166 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005167 if (pointerIds.count() != 1) {
5168 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5169 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005170 return false;
5171 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005172 // Track the pointer id for drag window and generate the drag state.
5173 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005174 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005175 }
5176
Arthur Hungabbb9d82021-09-01 14:52:30 +00005177 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005178 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5179 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005180 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005181 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005182 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005183 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005184 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005185 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005186 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005187 }
5188
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005189 if (DEBUG_FOCUS) {
5190 logDispatchStateLocked();
5191 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005192 } // release lock
5193
5194 // Wake up poll loop since it may need to make new input dispatching choices.
5195 mLooper->wake();
5196 return true;
5197}
5198
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005199/**
5200 * Get the touched foreground window on the given display.
5201 * Return null if there are no windows touched on that display, or if more than one foreground
5202 * window is being touched.
5203 */
5204sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5205 auto stateIt = mTouchStatesByDisplay.find(displayId);
5206 if (stateIt == mTouchStatesByDisplay.end()) {
5207 ALOGI("No touch state on display %" PRId32, displayId);
5208 return nullptr;
5209 }
5210
5211 const TouchState& state = stateIt->second;
5212 sp<WindowInfoHandle> touchedForegroundWindow;
5213 // If multiple foreground windows are touched, return nullptr
5214 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005215 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005216 if (touchedForegroundWindow != nullptr) {
5217 ALOGI("Two or more foreground windows: %s and %s",
5218 touchedForegroundWindow->getName().c_str(),
5219 window.windowHandle->getName().c_str());
5220 return nullptr;
5221 }
5222 touchedForegroundWindow = window.windowHandle;
5223 }
5224 }
5225 return touchedForegroundWindow;
5226}
5227
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005228// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005229bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005230 sp<IBinder> fromToken;
5231 { // acquire lock
5232 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005233 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005234 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005235 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5236 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005237 return false;
5238 }
5239
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005240 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5241 if (from == nullptr) {
5242 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5243 return false;
5244 }
5245
5246 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005247 } // release lock
5248
5249 return transferTouchFocus(fromToken, destChannelToken);
5250}
5251
Michael Wrightd02c5b62014-02-10 15:10:22 -08005252void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005253 if (DEBUG_FOCUS) {
5254 ALOGD("Resetting and dropping all events (%s).", reason);
5255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005256
Michael Wrightfb04fd52022-11-24 22:31:11 +00005257 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005258 synthesizeCancelationEventsForAllConnectionsLocked(options);
5259
5260 resetKeyRepeatLocked();
5261 releasePendingEventLocked();
5262 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005263 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005264
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005265 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005266 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005267 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005268 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005269}
5270
5271void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005272 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005273 dumpDispatchStateLocked(dump);
5274
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005275 std::istringstream stream(dump);
5276 std::string line;
5277
5278 while (std::getline(stream, line, '\n')) {
5279 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005280 }
5281}
5282
Prabir Pradhan99987712020-11-10 18:43:05 -08005283std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5284 std::string dump;
5285
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005286 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5287 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005288
5289 std::string windowName = "None";
5290 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005291 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005292 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5293 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5294 : "token has capture without window";
5295 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005296 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005297
5298 return dump;
5299}
5300
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005301void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005302 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5303 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5304 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005305 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005306
Tiger Huang721e26f2018-07-24 22:26:19 +08005307 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5308 dump += StringPrintf(INDENT "FocusedApplications:\n");
5309 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5310 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005311 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005312 const std::chrono::duration timeout =
5313 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005314 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005315 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005316 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005318 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005319 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005320 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005321
Vishnu Nairc519ff72021-01-21 08:23:08 -08005322 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005323 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005324
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005325 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005326 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005327 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005328 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5329 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005330 }
5331 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005332 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005333 }
5334
arthurhung6d4bed92021-03-17 11:59:33 +08005335 if (mDragState) {
5336 dump += StringPrintf(INDENT "DragState:\n");
5337 mDragState->dump(dump, INDENT2);
5338 }
5339
Arthur Hungb92218b2018-08-14 12:00:21 +08005340 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005341 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5342 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5343 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5344 const auto& displayInfo = it->second;
5345 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5346 displayInfo.logicalHeight);
5347 displayInfo.transform.dump(dump, "transform", INDENT4);
5348 } else {
5349 dump += INDENT2 "No DisplayInfo found!\n";
5350 }
5351
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005352 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005353 dump += INDENT2 "Windows:\n";
5354 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005355 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5356 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005357
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005358 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005359 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005360 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005361 "applicationInfo.name=%s, "
5362 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005363 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005364 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005365 windowInfo->displayId,
5366 windowInfo->inputConfig.string().c_str(),
5367 windowInfo->alpha, windowInfo->frameLeft,
5368 windowInfo->frameTop, windowInfo->frameRight,
5369 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005370 windowInfo->applicationInfo.name.c_str(),
5371 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005372 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005373 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005374 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005375 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005376 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005377 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005378 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005379 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005380 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005381 }
5382 } else {
5383 dump += INDENT2 "Windows: <none>\n";
5384 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005385 }
5386 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005387 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005388 }
5389
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005390 if (!mGlobalMonitorsByDisplay.empty()) {
5391 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5392 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005393 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005394 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005395 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005396 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005397 }
5398
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005399 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005400
5401 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005402 if (!mRecentQueue.empty()) {
5403 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005404 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005405 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005406 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005407 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408 }
5409 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005410 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005411 }
5412
5413 // Dump event currently being dispatched.
5414 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005415 dump += INDENT "PendingEvent:\n";
5416 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005417 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005418 dump += StringPrintf(", age=%" PRId64 "ms\n",
5419 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005420 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005421 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005422 }
5423
5424 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005425 if (!mInboundQueue.empty()) {
5426 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005427 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005428 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005429 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005430 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005431 }
5432 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005433 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005434 }
5435
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005436 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005437 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005438 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005439 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005440 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005441 }
5442 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005443 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005444 }
5445
Prabir Pradhancef936d2021-07-21 16:17:52 +00005446 if (!mCommandQueue.empty()) {
5447 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5448 } else {
5449 dump += INDENT "CommandQueue: <empty>\n";
5450 }
5451
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005452 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005453 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005454 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005455 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005456 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005457 connection->inputChannel->getFd().get(),
5458 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005459 connection->getWindowName().c_str(),
5460 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005461 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005462
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005463 if (!connection->outboundQueue.empty()) {
5464 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5465 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005466 dump += dumpQueue(connection->outboundQueue, currentTime);
5467
Michael Wrightd02c5b62014-02-10 15:10:22 -08005468 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005469 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005470 }
5471
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005472 if (!connection->waitQueue.empty()) {
5473 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5474 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005475 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005476 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005477 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005478 }
5479 }
5480 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005481 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482 }
5483
5484 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005485 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5486 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005487 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005488 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005489 }
5490
Antonio Kantek15beb512022-06-13 22:35:41 +00005491 if (!mTouchModePerDisplay.empty()) {
5492 dump += INDENT "TouchModePerDisplay:\n";
5493 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5494 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5495 std::to_string(touchMode).c_str());
5496 }
5497 } else {
5498 dump += INDENT "TouchModePerDisplay: <none>\n";
5499 }
5500
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005501 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005502 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5503 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5504 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005505 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005506 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005507}
5508
Michael Wright3dd60e22019-03-27 22:06:44 +00005509void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5510 const size_t numMonitors = monitors.size();
5511 for (size_t i = 0; i < numMonitors; i++) {
5512 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005513 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005514 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5515 dump += "\n";
5516 }
5517}
5518
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005519class LooperEventCallback : public LooperCallback {
5520public:
5521 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5522 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5523
5524private:
5525 std::function<int(int events)> mCallback;
5526};
5527
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005528Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005529 if (DEBUG_CHANNEL_CREATION) {
5530 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005532
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005533 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005534 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005535 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005536
5537 if (result) {
5538 return base::Error(result) << "Failed to open input channel pair with name " << name;
5539 }
5540
Michael Wrightd02c5b62014-02-10 15:10:22 -08005541 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005542 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005543 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005544 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005545 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005546 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005547
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005548 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5549 ALOGE("Created a new connection, but the token %p is already known", token.get());
5550 }
5551 mConnectionsByToken.emplace(token, connection);
5552
5553 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5554 this, std::placeholders::_1, token);
5555
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005556 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5557 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005558 } // release lock
5559
5560 // Wake the looper because some connections have changed.
5561 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005562 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005563}
5564
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005565Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005566 const std::string& name,
5567 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005568 std::shared_ptr<InputChannel> serverChannel;
5569 std::unique_ptr<InputChannel> clientChannel;
5570 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5571 if (result) {
5572 return base::Error(result) << "Failed to open input channel pair with name " << name;
5573 }
5574
Michael Wright3dd60e22019-03-27 22:06:44 +00005575 { // acquire lock
5576 std::scoped_lock _l(mLock);
5577
5578 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005579 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5580 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005581 }
5582
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005583 sp<Connection> connection =
5584 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005585 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005586 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005587
5588 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5589 ALOGE("Created a new connection, but the token %p is already known", token.get());
5590 }
5591 mConnectionsByToken.emplace(token, connection);
5592 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5593 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005594
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005595 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005596
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005597 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5598 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005599 }
Garfield Tan15601662020-09-22 15:32:38 -07005600
Michael Wright3dd60e22019-03-27 22:06:44 +00005601 // Wake the looper because some connections have changed.
5602 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005603 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005604}
5605
Garfield Tan15601662020-09-22 15:32:38 -07005606status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005608 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005609
Garfield Tan15601662020-09-22 15:32:38 -07005610 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005611 if (status) {
5612 return status;
5613 }
5614 } // release lock
5615
5616 // Wake the poll loop because removing the connection may have changed the current
5617 // synchronization state.
5618 mLooper->wake();
5619 return OK;
5620}
5621
Garfield Tan15601662020-09-22 15:32:38 -07005622status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5623 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005624 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005625 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005626 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005627 return BAD_VALUE;
5628 }
5629
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005630 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005631
Michael Wrightd02c5b62014-02-10 15:10:22 -08005632 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005633 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005634 }
5635
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005636 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005637
5638 nsecs_t currentTime = now();
5639 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5640
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005641 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005642 return OK;
5643}
5644
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005645void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005646 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5647 auto& [displayId, monitors] = *it;
5648 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5649 return monitor.inputChannel->getConnectionToken() == connectionToken;
5650 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005651
Michael Wright3dd60e22019-03-27 22:06:44 +00005652 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005653 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005654 } else {
5655 ++it;
5656 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005657 }
5658}
5659
Michael Wright3dd60e22019-03-27 22:06:44 +00005660status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005661 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005662 return pilferPointersLocked(token);
5663}
Michael Wright3dd60e22019-03-27 22:06:44 +00005664
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005665status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005666 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5667 if (!requestingChannel) {
5668 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5669 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005670 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005671
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005672 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07005673 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.isEmpty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005674 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5675 " Ignoring.");
5676 return BAD_VALUE;
5677 }
5678
5679 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005680 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005681 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005682 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005683 "input channel stole pointer stream");
5684 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005685 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005686 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005687 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005688 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005689 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005690 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005691 if (channel != nullptr && channel->getConnectionToken() != token) {
5692 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5693 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5694 canceledWindows += channel->getName();
5695 }
5696 }
5697 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5698 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5699 canceledWindows.c_str());
5700
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005701 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005702 // This only blocks relevant pointers to be sent to other windows
5703 window.isPilferingPointers = true;
5704
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005705 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005706 return OK;
5707}
5708
Prabir Pradhan99987712020-11-10 18:43:05 -08005709void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5710 { // acquire lock
5711 std::scoped_lock _l(mLock);
5712 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005713 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005714 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5715 windowHandle != nullptr ? windowHandle->getName().c_str()
5716 : "token without window");
5717 }
5718
Vishnu Nairc519ff72021-01-21 08:23:08 -08005719 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005720 if (focusedToken != windowToken) {
5721 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5722 enabled ? "enable" : "disable");
5723 return;
5724 }
5725
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005726 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005727 ALOGW("Ignoring request to %s Pointer Capture: "
5728 "window has %s requested pointer capture.",
5729 enabled ? "enable" : "disable", enabled ? "already" : "not");
5730 return;
5731 }
5732
Christine Franksb768bb42021-11-29 12:11:31 -08005733 if (enabled) {
5734 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5735 mIneligibleDisplaysForPointerCapture.end(),
5736 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5737 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5738 return;
5739 }
5740 }
5741
Prabir Pradhan99987712020-11-10 18:43:05 -08005742 setPointerCaptureLocked(enabled);
5743 } // release lock
5744
5745 // Wake the thread to process command entries.
5746 mLooper->wake();
5747}
5748
Christine Franksb768bb42021-11-29 12:11:31 -08005749void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5750 { // acquire lock
5751 std::scoped_lock _l(mLock);
5752 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5753 if (!isEligible) {
5754 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5755 }
5756 } // release lock
5757}
5758
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005759std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5760 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005761 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005762 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005763 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005764 }
5765 }
5766 }
5767 return std::nullopt;
5768}
5769
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005770sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005771 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005772 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005773 }
5774
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005775 for (const auto& [token, connection] : mConnectionsByToken) {
5776 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005777 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005778 }
5779 }
Robert Carr4e670e52018-08-15 13:26:12 -07005780
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005781 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005782}
5783
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005784std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5785 sp<Connection> connection = getConnectionLocked(connectionToken);
5786 if (connection == nullptr) {
5787 return "<nullptr>";
5788 }
5789 return connection->getInputChannelName();
5790}
5791
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005792void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005793 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005794 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005795}
5796
Prabir Pradhancef936d2021-07-21 16:17:52 +00005797void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5798 const sp<Connection>& connection, uint32_t seq,
5799 bool handled, nsecs_t consumeTime) {
5800 // Handle post-event policy actions.
5801 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5802 if (dispatchEntryIt == connection->waitQueue.end()) {
5803 return;
5804 }
5805 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5806 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5807 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5808 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5809 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5810 }
5811 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5812 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5813 connection->inputChannel->getConnectionToken(),
5814 dispatchEntry->deliveryTime, consumeTime, finishTime);
5815 }
5816
5817 bool restartEvent;
5818 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5819 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5820 restartEvent =
5821 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5822 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5823 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5824 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5825 handled);
5826 } else {
5827 restartEvent = false;
5828 }
5829
5830 // Dequeue the event and start the next cycle.
5831 // Because the lock might have been released, it is possible that the
5832 // contents of the wait queue to have been drained, so we need to double-check
5833 // a few things.
5834 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5835 if (dispatchEntryIt != connection->waitQueue.end()) {
5836 dispatchEntry = *dispatchEntryIt;
5837 connection->waitQueue.erase(dispatchEntryIt);
5838 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5839 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5840 if (!connection->responsive) {
5841 connection->responsive = isConnectionResponsive(*connection);
5842 if (connection->responsive) {
5843 // The connection was unresponsive, and now it's responsive.
5844 processConnectionResponsiveLocked(*connection);
5845 }
5846 }
5847 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005848 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005849 connection->outboundQueue.push_front(dispatchEntry);
5850 traceOutboundQueueLength(*connection);
5851 } else {
5852 releaseDispatchEntry(dispatchEntry);
5853 }
5854 }
5855
5856 // Start the next dispatch cycle for this connection.
5857 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005858}
5859
Prabir Pradhancef936d2021-07-21 16:17:52 +00005860void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5861 const sp<IBinder>& newToken) {
5862 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5863 scoped_unlock unlock(mLock);
5864 mPolicy->notifyFocusChanged(oldToken, newToken);
5865 };
5866 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005867}
5868
Prabir Pradhancef936d2021-07-21 16:17:52 +00005869void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5870 auto command = [this, token, x, y]() REQUIRES(mLock) {
5871 scoped_unlock unlock(mLock);
5872 mPolicy->notifyDropWindow(token, x, y);
5873 };
5874 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005875}
5876
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005877void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5878 if (connection == nullptr) {
5879 LOG_ALWAYS_FATAL("Caller must check for nullness");
5880 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005881 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5882 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005883 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005884 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005885 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005886 return;
5887 }
5888 /**
5889 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5890 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5891 * has changed. This could cause newer entries to time out before the already dispatched
5892 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5893 * processes the events linearly. So providing information about the oldest entry seems to be
5894 * most useful.
5895 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005896 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005897 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5898 std::string reason =
5899 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005900 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005901 ns2ms(currentWait),
5902 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005903 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005904 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005905
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005906 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5907
5908 // Stop waking up for events on this connection, it is already unresponsive
5909 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005910}
5911
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005912void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5913 std::string reason =
5914 StringPrintf("%s does not have a focused window", application->getName().c_str());
5915 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005916
Prabir Pradhancef936d2021-07-21 16:17:52 +00005917 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5918 scoped_unlock unlock(mLock);
5919 mPolicy->notifyNoFocusedWindowAnr(application);
5920 };
5921 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005922}
5923
chaviw98318de2021-05-19 16:45:23 -05005924void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005925 const std::string& reason) {
5926 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5927 updateLastAnrStateLocked(windowLabel, reason);
5928}
5929
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005930void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5931 const std::string& reason) {
5932 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005933 updateLastAnrStateLocked(windowLabel, reason);
5934}
5935
5936void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5937 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005938 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005939 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005940 struct tm tm;
5941 localtime_r(&t, &tm);
5942 char timestr[64];
5943 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005944 mLastAnrState.clear();
5945 mLastAnrState += INDENT "ANR:\n";
5946 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005947 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5948 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005949 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005950}
5951
Prabir Pradhancef936d2021-07-21 16:17:52 +00005952void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5953 KeyEntry& entry) {
5954 const KeyEvent event = createKeyEvent(entry);
5955 nsecs_t delay = 0;
5956 { // release lock
5957 scoped_unlock unlock(mLock);
5958 android::base::Timer t;
5959 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5960 entry.policyFlags);
5961 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5962 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5963 std::to_string(t.duration().count()).c_str());
5964 }
5965 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005966
5967 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00005968 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005969 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00005970 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005971 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00005972 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005973 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005975}
5976
Prabir Pradhancef936d2021-07-21 16:17:52 +00005977void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005978 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005979 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005980 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005981 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005982 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005983 };
5984 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005985}
5986
Prabir Pradhanedd96402022-02-15 01:46:16 -08005987void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5988 std::optional<int32_t> pid) {
5989 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005990 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005991 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005992 };
5993 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005994}
5995
5996/**
5997 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5998 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5999 * command entry to the command queue.
6000 */
6001void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6002 std::string reason) {
6003 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006004 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006005 if (connection.monitor) {
6006 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6007 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006008 pid = findMonitorPidByTokenLocked(connectionToken);
6009 } else {
6010 // The connection is a window
6011 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6012 reason.c_str());
6013 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6014 if (handle != nullptr) {
6015 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006016 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006017 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006018 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006019}
6020
6021/**
6022 * Tell the policy that a connection has become responsive so that it can stop ANR.
6023 */
6024void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6025 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006026 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006027 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006028 pid = findMonitorPidByTokenLocked(connectionToken);
6029 } else {
6030 // The connection is a window
6031 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6032 if (handle != nullptr) {
6033 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006034 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006035 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006036 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006037}
6038
Prabir Pradhancef936d2021-07-21 16:17:52 +00006039bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006040 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006041 KeyEntry& keyEntry, bool handled) {
6042 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006043 if (!handled) {
6044 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006045 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006046 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006047 return false;
6048 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006049
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006050 // Get the fallback key state.
6051 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006052 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006053 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006054 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006055 connection->inputState.removeFallbackKey(originalKeyCode);
6056 }
6057
6058 if (handled || !dispatchEntry->hasForegroundTarget()) {
6059 // If the application handles the original key for which we previously
6060 // generated a fallback or if the window is not a foreground window,
6061 // then cancel the associated fallback key, if any.
6062 if (fallbackKeyCode != -1) {
6063 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006064 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6065 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6066 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6067 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6068 keyEntry.policyFlags);
6069 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006070 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006071 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006072
6073 mLock.unlock();
6074
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006075 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006076 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006077
6078 mLock.lock();
6079
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006080 // Cancel the fallback key.
6081 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006082 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006083 "application handled the original non-fallback key "
6084 "or is no longer a foreground target, "
6085 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006086 options.keyCode = fallbackKeyCode;
6087 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006088 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006089 connection->inputState.removeFallbackKey(originalKeyCode);
6090 }
6091 } else {
6092 // If the application did not handle a non-fallback key, first check
6093 // that we are in a good state to perform unhandled key event processing
6094 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006095 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006096 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006097 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6098 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6099 "since this is not an initial down. "
6100 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6101 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6102 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006103 return false;
6104 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006105
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006106 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006107 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6108 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6109 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6110 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6111 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006112 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006113
6114 mLock.unlock();
6115
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006116 bool fallback =
6117 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006118 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006119
6120 mLock.lock();
6121
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006122 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006123 connection->inputState.removeFallbackKey(originalKeyCode);
6124 return false;
6125 }
6126
6127 // Latch the fallback keycode for this key on an initial down.
6128 // The fallback keycode cannot change at any other point in the lifecycle.
6129 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006130 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006131 fallbackKeyCode = event.getKeyCode();
6132 } else {
6133 fallbackKeyCode = AKEYCODE_UNKNOWN;
6134 }
6135 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6136 }
6137
6138 ALOG_ASSERT(fallbackKeyCode != -1);
6139
6140 // Cancel the fallback key if the policy decides not to send it anymore.
6141 // We will continue to dispatch the key to the policy but we will no
6142 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006143 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6144 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006145 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6146 if (fallback) {
6147 ALOGD("Unhandled key event: Policy requested to send key %d"
6148 "as a fallback for %d, but on the DOWN it had requested "
6149 "to send %d instead. Fallback canceled.",
6150 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6151 } else {
6152 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6153 "but on the DOWN it had requested to send %d. "
6154 "Fallback canceled.",
6155 originalKeyCode, fallbackKeyCode);
6156 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006157 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006158
Michael Wrightfb04fd52022-11-24 22:31:11 +00006159 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006160 "canceling fallback, policy no longer desires it");
6161 options.keyCode = fallbackKeyCode;
6162 synthesizeCancelationEventsForConnectionLocked(connection, options);
6163
6164 fallback = false;
6165 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006166 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006167 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006168 }
6169 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006170
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006171 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6172 {
6173 std::string msg;
6174 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6175 connection->inputState.getFallbackKeys();
6176 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6177 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6178 }
6179 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6180 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006181 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006182 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006183
6184 if (fallback) {
6185 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006186 keyEntry.eventTime = event.getEventTime();
6187 keyEntry.deviceId = event.getDeviceId();
6188 keyEntry.source = event.getSource();
6189 keyEntry.displayId = event.getDisplayId();
6190 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6191 keyEntry.keyCode = fallbackKeyCode;
6192 keyEntry.scanCode = event.getScanCode();
6193 keyEntry.metaState = event.getMetaState();
6194 keyEntry.repeatCount = event.getRepeatCount();
6195 keyEntry.downTime = event.getDownTime();
6196 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006197
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006198 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6199 ALOGD("Unhandled key event: Dispatching fallback key. "
6200 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6201 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6202 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006203 return true; // restart the event
6204 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006205 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6206 ALOGD("Unhandled key event: No fallback key.");
6207 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006208
6209 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006210 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006211 }
6212 }
6213 return false;
6214}
6215
Prabir Pradhancef936d2021-07-21 16:17:52 +00006216bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006217 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006218 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006219 return false;
6220}
6221
Michael Wrightd02c5b62014-02-10 15:10:22 -08006222void InputDispatcher::traceInboundQueueLengthLocked() {
6223 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006224 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006225 }
6226}
6227
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006228void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006229 if (ATRACE_ENABLED()) {
6230 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006231 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6232 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006233 }
6234}
6235
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006236void InputDispatcher::traceWaitQueueLength(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), "wq:%s", connection.getWindowName().c_str());
6240 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006241 }
6242}
6243
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006244void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006245 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006246
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006247 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006248 dumpDispatchStateLocked(dump);
6249
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006250 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006251 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006252 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006253 }
6254}
6255
6256void InputDispatcher::monitor() {
6257 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006258 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006259 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006260 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006261}
6262
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006263/**
6264 * Wake up the dispatcher and wait until it processes all events and commands.
6265 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6266 * this method can be safely called from any thread, as long as you've ensured that
6267 * the work you are interested in completing has already been queued.
6268 */
6269bool InputDispatcher::waitForIdle() {
6270 /**
6271 * Timeout should represent the longest possible time that a device might spend processing
6272 * events and commands.
6273 */
6274 constexpr std::chrono::duration TIMEOUT = 100ms;
6275 std::unique_lock lock(mLock);
6276 mLooper->wake();
6277 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6278 return result == std::cv_status::no_timeout;
6279}
6280
Vishnu Naire798b472020-07-23 13:52:21 -07006281/**
6282 * Sets focus to the window identified by the token. This must be called
6283 * after updating any input window handles.
6284 *
6285 * Params:
6286 * request.token - input channel token used to identify the window that should gain focus.
6287 * request.focusedToken - the token that the caller expects currently to be focused. If the
6288 * specified token does not match the currently focused window, this request will be dropped.
6289 * If the specified focused token matches the currently focused window, the call will succeed.
6290 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6291 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6292 * when requesting the focus change. This determines which request gets
6293 * precedence if there is a focus change request from another source such as pointer down.
6294 */
Vishnu Nair958da932020-08-21 17:12:37 -07006295void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6296 { // acquire lock
6297 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006298 std::optional<FocusResolver::FocusChanges> changes =
6299 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6300 if (changes) {
6301 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006302 }
6303 } // release lock
6304 // Wake up poll loop since it may need to make new input dispatching choices.
6305 mLooper->wake();
6306}
6307
Vishnu Nairc519ff72021-01-21 08:23:08 -08006308void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6309 if (changes.oldFocus) {
6310 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006311 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006312 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006313 "focus left window");
6314 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006315 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006316 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006317 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006318 if (changes.newFocus) {
6319 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006320 }
6321
Prabir Pradhan99987712020-11-10 18:43:05 -08006322 // If a window has pointer capture, then it must have focus. We need to ensure that this
6323 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6324 // If the window loses focus before it loses pointer capture, then the window can be in a state
6325 // where it has pointer capture but not focus, violating the contract. Therefore we must
6326 // dispatch the pointer capture event before the focus event. Since focus events are added to
6327 // the front of the queue (above), we add the pointer capture event to the front of the queue
6328 // after the focus events are added. This ensures the pointer capture event ends up at the
6329 // front.
6330 disablePointerCaptureForcedLocked();
6331
Vishnu Nairc519ff72021-01-21 08:23:08 -08006332 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006333 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006334 }
6335}
Vishnu Nair958da932020-08-21 17:12:37 -07006336
Prabir Pradhan99987712020-11-10 18:43:05 -08006337void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006338 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006339 return;
6340 }
6341
6342 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6343
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006344 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006345 setPointerCaptureLocked(false);
6346 }
6347
6348 if (!mWindowTokenWithPointerCapture) {
6349 // No need to send capture changes because no window has capture.
6350 return;
6351 }
6352
6353 if (mPendingEvent != nullptr) {
6354 // Move the pending event to the front of the queue. This will give the chance
6355 // for the pending event to be dropped if it is a captured event.
6356 mInboundQueue.push_front(mPendingEvent);
6357 mPendingEvent = nullptr;
6358 }
6359
6360 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006361 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006362 mInboundQueue.push_front(std::move(entry));
6363}
6364
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006365void InputDispatcher::setPointerCaptureLocked(bool enable) {
6366 mCurrentPointerCaptureRequest.enable = enable;
6367 mCurrentPointerCaptureRequest.seq++;
6368 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006369 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006370 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006371 };
6372 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006373}
6374
Vishnu Nair599f1412021-06-21 10:39:58 -07006375void InputDispatcher::displayRemoved(int32_t displayId) {
6376 { // acquire lock
6377 std::scoped_lock _l(mLock);
6378 // Set an empty list to remove all handles from the specific display.
6379 setInputWindowsLocked(/* window handles */ {}, displayId);
6380 setFocusedApplicationLocked(displayId, nullptr);
6381 // Call focus resolver to clean up stale requests. This must be called after input windows
6382 // have been removed for the removed display.
6383 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006384 // Reset pointer capture eligibility, regardless of previous state.
6385 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006386 // Remove the associated touch mode state.
6387 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006388 } // release lock
6389
6390 // Wake up poll loop since it may need to make new input dispatching choices.
6391 mLooper->wake();
6392}
6393
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006394void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6395 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006396 // The listener sends the windows as a flattened array. Separate the windows by display for
6397 // more convenient parsing.
6398 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006399 for (const auto& info : windowInfos) {
6400 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006401 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006402 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006403
6404 { // acquire lock
6405 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006406
6407 // Ensure that we have an entry created for all existing displays so that if a displayId has
6408 // no windows, we can tell that the windows were removed from the display.
6409 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6410 handlesPerDisplay[displayId];
6411 }
6412
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006413 mDisplayInfos.clear();
6414 for (const auto& displayInfo : displayInfos) {
6415 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6416 }
6417
6418 for (const auto& [displayId, handles] : handlesPerDisplay) {
6419 setInputWindowsLocked(handles, displayId);
6420 }
6421 }
6422 // Wake up poll loop since it may need to make new input dispatching choices.
6423 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006424}
6425
Vishnu Nair062a8672021-09-03 16:07:44 -07006426bool InputDispatcher::shouldDropInput(
6427 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006428 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6429 (windowHandle->getInfo()->inputConfig.test(
6430 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006431 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006432 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6433 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006434 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006435 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006436 windowHandle->getInfo()->displayId);
6437 return true;
6438 }
6439 return false;
6440}
6441
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006442void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6443 const std::vector<gui::WindowInfo>& windowInfos,
6444 const std::vector<DisplayInfo>& displayInfos) {
6445 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6446}
6447
Arthur Hungdfd528e2021-12-08 13:23:04 +00006448void InputDispatcher::cancelCurrentTouch() {
6449 {
6450 std::scoped_lock _l(mLock);
6451 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006452 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006453 "cancel current touch");
6454 synthesizeCancelationEventsForAllConnectionsLocked(options);
6455
6456 mTouchStatesByDisplay.clear();
6457 mLastHoverWindowHandle.clear();
6458 }
6459 // Wake up poll loop since there might be work to do.
6460 mLooper->wake();
6461}
6462
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006463void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6464 std::scoped_lock _l(mLock);
6465 mMonitorDispatchingTimeout = timeout;
6466}
6467
Garfield Tane84e6f92019-08-29 17:28:41 -07006468} // namespace android::inputdispatcher