blob: 0e95ee4bb4430de8ebe96cf53f32a7a37cfc3995 [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) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002099 (oldState->deviceId != entry.deviceId || oldState->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);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002107
Michael Wrightd02c5b62014-02-10 15:10:22 -08002108 if (newGesture) {
2109 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002110 if (switchedDevice && tempTouchState.isDown() && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002111 ALOGI("Dropping event because a pointer for a different device is already down "
2112 "in display %" PRId32,
2113 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002114 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002115 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakouf0ab2c82022-10-25 18:15:28 -07002116 return touchedWindows; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002117 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002118 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002119 tempTouchState.deviceId = entry.deviceId;
2120 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002121 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002122 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002123 ALOGI("Dropping move event because a pointer for a different device is already active "
2124 "in display %" PRId32,
2125 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002126 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002127 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakouf0ab2c82022-10-25 18:15:28 -07002128 return touchedWindows; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129 }
2130
2131 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2132 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002133 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002134 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002135 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002136 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002137 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002138 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002139
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002141 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002142 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2143 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002144 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002145 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002146 }
2147
Prabir Pradhan5735a322022-04-11 17:23:34 +00002148 // Verify targeted injection.
2149 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2150 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002151 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002152 newTouchedWindowHandle = nullptr;
2153 goto Failed;
2154 }
2155
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002156 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002157 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002158 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2159 // New window supports splitting, but we should never split mouse events.
2160 isSplit = !isFromMouse;
2161 } else if (isSplit) {
2162 // New window does not support splitting but we have already split events.
2163 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002164 newTouchedWindowHandle = nullptr;
2165 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002166 } else {
2167 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002168 // be delivered to a new window which supports split touch. Pointers from a mouse device
2169 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002170 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002171 }
2172
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002173 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002174 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002175 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2176 newHoverWindowHandle = nullptr;
2177 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002178 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002179 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002180 }
2181
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002182 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002183 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002184 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002185 // Process the foreground window first so that it is the first to receive the event.
2186 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002187 }
2188
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002189 if (newTouchedWindows.empty()) {
2190 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2191 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002192 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002193 goto Failed;
2194 }
2195
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002196 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002197 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002198 continue;
2199 }
2200
2201 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002202 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002203
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002204 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2205 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002206 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002207 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002208
2209 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002210 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002211 }
2212 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002213 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002214 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002215 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002216 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002217
2218 // Update the temporary touch state.
2219 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002220 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002221
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002222 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
2223 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002224 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002225
2226 // If any existing window is pilfering pointers from newly added window, remove it
2227 BitSet32 canceledPointers = BitSet32(0);
2228 for (const TouchedWindow& window : tempTouchState.windows) {
2229 if (window.isPilferingPointers) {
2230 canceledPointers |= window.pointerIds;
2231 }
2232 }
2233 tempTouchState.cancelPointersForNonPilferingWindows(canceledPointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234 } else {
2235 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2236
2237 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002238 if (!tempTouchState.isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002239 ALOGD_IF(DEBUG_FOCUS,
2240 "Dropping event because the pointer is not down or we previously "
2241 "dropped the pointer down event in display %" PRId32 ": %s",
2242 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002243 outInjectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002244 goto Failed;
2245 }
2246
arthurhung6d4bed92021-03-17 11:59:33 +08002247 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002248
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002250 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002251 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002252 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07002253 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002254 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002255 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002256 newTouchedWindowHandle =
2257 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002258
Prabir Pradhan5735a322022-04-11 17:23:34 +00002259 // Verify targeted injection.
2260 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2261 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002262 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002263 newTouchedWindowHandle = nullptr;
2264 goto Failed;
2265 }
2266
Vishnu Nair062a8672021-09-03 16:07:44 -07002267 // Drop touch events if requested by input feature
2268 if (newTouchedWindowHandle != nullptr &&
2269 shouldDropInput(entry, newTouchedWindowHandle)) {
2270 newTouchedWindowHandle = nullptr;
2271 }
2272
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002273 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2274 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002275 if (DEBUG_FOCUS) {
2276 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2277 oldTouchedWindowHandle->getName().c_str(),
2278 newTouchedWindowHandle->getName().c_str(), displayId);
2279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002281 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002282 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002283 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284
2285 // Make a slippery entrance into the new window.
2286 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002287 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 }
2289
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002290 ftl::Flags<InputTarget::Flags> targetFlags =
2291 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002292 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002293 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002294 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002296 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297 }
2298 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002299 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002300 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002301 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002302 }
2303
2304 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002305 pointerIds.markBit(entry.pointerProperties[0].id);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002306 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2307 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 }
2309 }
Arthur Hung96483742022-11-15 03:30:48 +00002310
2311 // Update the pointerIds for non-splittable when it received pointer down.
2312 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2313 // If no split, we suppose all touched windows should receive pointer down.
2314 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2315 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2316 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2317 // Ignore drag window for it should just track one pointer.
2318 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2319 continue;
2320 }
2321 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2322 }
2323 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324 }
2325
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002326 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002328 // Let the previous window know that the hover sequence is over, unless we already did
2329 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002330 if (mLastHoverWindowHandle != nullptr &&
2331 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2332 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002333 if (DEBUG_HOVER) {
2334 ALOGD("Sending hover exit event to window %s.",
2335 mLastHoverWindowHandle->getName().c_str());
2336 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002337 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002338 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT,
2339 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340 }
2341
Garfield Tandf26e862020-07-01 20:18:19 -07002342 // Let the new window know that the hover sequence is starting, unless we already did it
2343 // when dispatching it as is to newTouchedWindowHandle.
2344 if (newHoverWindowHandle != nullptr &&
2345 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2346 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002347 if (DEBUG_HOVER) {
2348 ALOGD("Sending hover enter event to window %s.",
2349 newHoverWindowHandle->getName().c_str());
2350 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002351 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002352 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002353 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354 }
2355 }
2356
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002357 // Ensure that we have at least one foreground window or at least one window that cannot be a
2358 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2359 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2360 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002361 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2362 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002363 return !canReceiveForegroundTouches(
2364 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002365 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002366 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002367 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2368 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002369 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002370 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371 }
2372
Prabir Pradhan5735a322022-04-11 17:23:34 +00002373 // Ensure that all touched windows are valid for injection.
2374 if (entry.injectionState != nullptr) {
2375 std::string errs;
2376 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002377 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002378 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2379 // dispatched to any uid, since the coords will be zeroed out later.
2380 continue;
2381 }
2382 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2383 if (err) errs += "\n - " + *err;
2384 }
2385 if (!errs.empty()) {
2386 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2387 "%d:%s",
2388 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002389 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002390 goto Failed;
2391 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002392 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002393
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 // Check whether windows listening for outside touches are owned by the same UID. If it is
2395 // set the policy flag that we will not reveal coordinate information to this window.
2396 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002397 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002398 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002399 if (foregroundWindowHandle) {
2400 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002401 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002402 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
chaviw98318de2021-05-19 16:45:23 -05002403 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2404 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2405 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002406 InputTarget::Flags::ZERO_COORDS,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002407 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002408 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002409 }
2410 }
2411 }
2412 }
2413
Michael Wrightd02c5b62014-02-10 15:10:22 -08002414 // If this is the first pointer going down and the touched window has a wallpaper
2415 // then also add the touched wallpaper windows so they are locked in for the duration
2416 // of the touch gesture.
2417 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2418 // engine only supports touch events. We would need to add a mechanism similar
2419 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2420 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002421 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002422 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002423 if (foregroundWindowHandle &&
2424 foregroundWindowHandle->getInfo()->inputConfig.test(
2425 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002426 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002427 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002428 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2429 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002430 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002431 windowHandle->getInfo()->inputConfig.test(
2432 WindowInfo::InputConfig::IS_WALLPAPER)) {
Arthur Hung74c248d2022-11-23 07:09:59 +00002433 BitSet32 pointerIds;
2434 pointerIds.markBit(entry.pointerProperties[0].id);
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002435 tempTouchState.addOrUpdateWindow(windowHandle,
2436 InputTarget::Flags::WINDOW_IS_OBSCURED |
2437 InputTarget::Flags::
2438 WINDOW_IS_PARTIALLY_OBSCURED |
2439 InputTarget::Flags::DISPATCH_AS_IS,
Arthur Hung74c248d2022-11-23 07:09:59 +00002440 pointerIds, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441 }
2442 }
2443 }
2444 }
2445
2446 // Success! Output targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002447 touchedWindows = tempTouchState.windows;
2448 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002449
2450 // Drop the outside or hover touch windows since we will not care about them
2451 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002452 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002453
2454Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002455 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002456 if (switchedDevice) {
2457 if (DEBUG_FOCUS) {
2458 ALOGD("Conflicting pointer actions: Switched to a different device.");
2459 }
2460 *outConflictingPointerActions = true;
2461 }
2462
2463 if (isHoverAction) {
2464 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002465 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002466 ALOGD_IF(DEBUG_FOCUS,
2467 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002468 *outConflictingPointerActions = true;
2469 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002470 tempTouchState.reset();
2471 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2472 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2473 tempTouchState.deviceId = entry.deviceId;
2474 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002475 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002476 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2477 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2478 // All pointers up or canceled.
2479 tempTouchState.reset();
2480 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2481 // First pointer went down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002482 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002483 ALOGD("Conflicting pointer actions: Down received while already down.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002484 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002485 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002486 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2487 // One pointer went up.
2488 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2489 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002491 for (size_t i = 0; i < tempTouchState.windows.size();) {
2492 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2493 touchedWindow.pointerIds.clearBit(pointerId);
2494 if (touchedWindow.pointerIds.isEmpty()) {
2495 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2496 continue;
2497 }
2498 i += 1;
2499 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500 }
2501
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002502 // Save changes unless the action was scroll in which case the temporary touch
2503 // state was only valid for this one action.
2504 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002505 if (displayId >= 0) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002506 mTouchStatesByDisplay[displayId] = tempTouchState;
2507 } else {
2508 mTouchStatesByDisplay.erase(displayId);
2509 }
2510 }
2511
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002512 if (tempTouchState.windows.empty()) {
2513 mTouchStatesByDisplay.erase(displayId);
2514 }
2515
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002516 // Update hover state.
2517 mLastHoverWindowHandle = newHoverWindowHandle;
2518
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002519 return touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002520}
2521
arthurhung6d4bed92021-03-17 11:59:33 +08002522void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002523 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2524 // have an explicit reason to support it.
2525 constexpr bool isStylus = false;
2526
chaviw98318de2021-05-19 16:45:23 -05002527 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002528 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002529 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002530 if (dropWindow) {
2531 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002532 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002533 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002534 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002535 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002536 }
2537 mDragState.reset();
2538}
2539
2540void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002541 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002542 return;
2543 }
2544
arthurhung6d4bed92021-03-17 11:59:33 +08002545 if (!mDragState->isStartDrag) {
2546 mDragState->isStartDrag = true;
2547 mDragState->isStylusButtonDownAtStart =
2548 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2549 }
2550
Arthur Hung54745652022-04-20 07:17:41 +00002551 // Find the pointer index by id.
2552 int32_t pointerIndex = 0;
2553 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2554 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2555 if (pointerProperties.id == mDragState->pointerId) {
2556 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002557 }
Arthur Hung54745652022-04-20 07:17:41 +00002558 }
arthurhung6d4bed92021-03-17 11:59:33 +08002559
Arthur Hung54745652022-04-20 07:17:41 +00002560 if (uint32_t(pointerIndex) == entry.pointerCount) {
2561 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002562 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002563 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002564 return;
2565 }
2566
2567 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2568 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2569 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2570
2571 switch (maskedAction) {
2572 case AMOTION_EVENT_ACTION_MOVE: {
2573 // Handle the special case : stylus button no longer pressed.
2574 bool isStylusButtonDown =
2575 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2576 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2577 finishDragAndDrop(entry.displayId, x, y);
2578 return;
2579 }
2580
2581 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2582 // until we have an explicit reason to support it.
2583 constexpr bool isStylus = false;
2584
2585 const sp<WindowInfoHandle> hoverWindowHandle =
2586 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2587 isStylus, false /*addOutsideTargets*/,
2588 true /*ignoreDragWindow*/);
2589 // enqueue drag exit if needed.
2590 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2591 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2592 if (mDragState->dragHoverWindowHandle != nullptr) {
2593 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2594 y);
2595 }
2596 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2597 }
2598 // enqueue drag location if needed.
2599 if (hoverWindowHandle != nullptr) {
2600 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2601 }
2602 break;
2603 }
2604
2605 case AMOTION_EVENT_ACTION_POINTER_UP:
2606 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2607 break;
2608 }
2609 // The drag pointer is up.
2610 [[fallthrough]];
2611 case AMOTION_EVENT_ACTION_UP:
2612 finishDragAndDrop(entry.displayId, x, y);
2613 break;
2614 case AMOTION_EVENT_ACTION_CANCEL: {
2615 ALOGD("Receiving cancel when drag and drop.");
2616 sendDropWindowCommandLocked(nullptr, 0, 0);
2617 mDragState.reset();
2618 break;
2619 }
arthurhungb89ccb02020-12-30 16:19:01 +08002620 }
2621}
2622
chaviw98318de2021-05-19 16:45:23 -05002623void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002624 ftl::Flags<InputTarget::Flags> targetFlags,
2625 BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002626 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002627 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002628 std::vector<InputTarget>::iterator it =
2629 std::find_if(inputTargets.begin(), inputTargets.end(),
2630 [&windowHandle](const InputTarget& inputTarget) {
2631 return inputTarget.inputChannel->getConnectionToken() ==
2632 windowHandle->getToken();
2633 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002634
chaviw98318de2021-05-19 16:45:23 -05002635 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002636
2637 if (it == inputTargets.end()) {
2638 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002639 std::shared_ptr<InputChannel> inputChannel =
2640 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002641 if (inputChannel == nullptr) {
2642 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2643 return;
2644 }
2645 inputTarget.inputChannel = inputChannel;
2646 inputTarget.flags = targetFlags;
2647 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002648 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002649 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2650 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002651 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002652 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002653 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002654 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002655 inputTargets.push_back(inputTarget);
2656 it = inputTargets.end() - 1;
2657 }
2658
2659 ALOG_ASSERT(it->flags == targetFlags);
2660 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2661
chaviw1ff3d1e2020-07-01 15:53:47 -07002662 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002663}
2664
Michael Wright3dd60e22019-03-27 22:06:44 +00002665void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002666 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002667 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2668 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002669
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002670 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2671 InputTarget target;
2672 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002673 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002674 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2675 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002676 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2677 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002678 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002679 target.setDefaultPointerTransform(target.displayTransform);
2680 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002681 }
2682}
2683
Robert Carrc9bf1d32020-04-13 17:21:08 -07002684/**
2685 * Indicate whether one window handle should be considered as obscuring
2686 * another window handle. We only check a few preconditions. Actually
2687 * checking the bounds is left to the caller.
2688 */
chaviw98318de2021-05-19 16:45:23 -05002689static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2690 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002691 // Compare by token so cloned layers aren't counted
2692 if (haveSameToken(windowHandle, otherHandle)) {
2693 return false;
2694 }
2695 auto info = windowHandle->getInfo();
2696 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002697 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002698 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002699 } else if (otherInfo->alpha == 0 &&
2700 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002701 // Those act as if they were invisible, so we don't need to flag them.
2702 // We do want to potentially flag touchable windows even if they have 0
2703 // opacity, since they can consume touches and alter the effects of the
2704 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002705 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002706 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2707 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002708 } else if (info->ownerUid == otherInfo->ownerUid) {
2709 // If ownerUid is the same we don't generate occlusion events as there
2710 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002711 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002712 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002713 return false;
2714 } else if (otherInfo->displayId != info->displayId) {
2715 return false;
2716 }
2717 return true;
2718}
2719
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002720/**
2721 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2722 * untrusted, one should check:
2723 *
2724 * 1. If result.hasBlockingOcclusion is true.
2725 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2726 * BLOCK_UNTRUSTED.
2727 *
2728 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2729 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2730 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2731 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2732 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2733 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2734 *
2735 * If neither of those is true, then it means the touch can be allowed.
2736 */
2737InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002738 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2739 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002740 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002741 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002742 TouchOcclusionInfo info;
2743 info.hasBlockingOcclusion = false;
2744 info.obscuringOpacity = 0;
2745 info.obscuringUid = -1;
2746 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002747 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002748 if (windowHandle == otherHandle) {
2749 break; // All future windows are below us. Exit early.
2750 }
chaviw98318de2021-05-19 16:45:23 -05002751 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002752 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2753 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002754 if (DEBUG_TOUCH_OCCLUSION) {
2755 info.debugInfo.push_back(
2756 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2757 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002758 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2759 // we perform the checks below to see if the touch can be propagated or not based on the
2760 // window's touch occlusion mode
2761 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2762 info.hasBlockingOcclusion = true;
2763 info.obscuringUid = otherInfo->ownerUid;
2764 info.obscuringPackage = otherInfo->packageName;
2765 break;
2766 }
2767 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2768 uint32_t uid = otherInfo->ownerUid;
2769 float opacity =
2770 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2771 // Given windows A and B:
2772 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2773 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2774 opacityByUid[uid] = opacity;
2775 if (opacity > info.obscuringOpacity) {
2776 info.obscuringOpacity = opacity;
2777 info.obscuringUid = uid;
2778 info.obscuringPackage = otherInfo->packageName;
2779 }
2780 }
2781 }
2782 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002783 if (DEBUG_TOUCH_OCCLUSION) {
2784 info.debugInfo.push_back(
2785 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2786 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002787 return info;
2788}
2789
chaviw98318de2021-05-19 16:45:23 -05002790std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002791 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002792 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2793 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2794 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2795 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002796 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2797 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2798 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2799 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2800 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002801 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002802 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002803}
2804
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002805bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2806 if (occlusionInfo.hasBlockingOcclusion) {
2807 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2808 occlusionInfo.obscuringUid);
2809 return false;
2810 }
2811 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2812 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2813 "%.2f, maximum allowed = %.2f)",
2814 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2815 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2816 return false;
2817 }
2818 return true;
2819}
2820
chaviw98318de2021-05-19 16:45:23 -05002821bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002822 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002824 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2825 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002826 if (windowHandle == otherHandle) {
2827 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828 }
chaviw98318de2021-05-19 16:45:23 -05002829 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002830 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002831 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002832 return true;
2833 }
2834 }
2835 return false;
2836}
2837
chaviw98318de2021-05-19 16:45:23 -05002838bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002839 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002840 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2841 const WindowInfo* windowInfo = windowHandle->getInfo();
2842 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002843 if (windowHandle == otherHandle) {
2844 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002845 }
chaviw98318de2021-05-19 16:45:23 -05002846 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002847 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002848 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002849 return true;
2850 }
2851 }
2852 return false;
2853}
2854
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002855std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002856 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002857 if (applicationHandle != nullptr) {
2858 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002859 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002860 } else {
2861 return applicationHandle->getName();
2862 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002863 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002864 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002865 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002866 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867 }
2868}
2869
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002870void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002871 if (!isUserActivityEvent(eventEntry)) {
2872 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002873 return;
2874 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002875 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002876 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002877 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002878 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002879 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002880 if (DEBUG_DISPATCH_CYCLE) {
2881 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2882 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883 return;
2884 }
2885 }
2886
2887 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002888 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002889 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002890 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2891 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002892 return;
2893 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002894
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002895 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002896 eventType = USER_ACTIVITY_EVENT_TOUCH;
2897 }
2898 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002899 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002900 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002901 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2902 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002903 return;
2904 }
2905 eventType = USER_ACTIVITY_EVENT_BUTTON;
2906 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002907 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002908 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002909 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002910 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002911 break;
2912 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002913 }
2914
Prabir Pradhancef936d2021-07-21 16:17:52 +00002915 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2916 REQUIRES(mLock) {
2917 scoped_unlock unlock(mLock);
2918 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2919 };
2920 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002921}
2922
2923void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002924 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002925 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002926 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002927 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002928 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002929 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002930 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002931 ATRACE_NAME(message.c_str());
2932 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002933 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002934 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002935 "globalScaleFactor=%f, pointerIds=0x%x %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002936 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002937 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2938 inputTarget.getPointerInfoString().c_str());
2939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940
2941 // Skip this event if the connection status is not normal.
2942 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002943 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002944 if (DEBUG_DISPATCH_CYCLE) {
2945 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002946 connection->getInputChannelName().c_str(),
2947 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002949 return;
2950 }
2951
2952 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002953 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002954 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002955 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002956 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002957
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002958 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002959 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002960 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
2961 "Splitting motion events requires a down time to be set for the "
2962 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002963 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002964 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
2965 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002966 if (!splitMotionEntry) {
2967 return; // split event was dropped
2968 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002969 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2970 std::string reason = std::string("reason=pointer cancel on split window");
2971 android_log_event_list(LOGTAG_INPUT_CANCEL)
2972 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2973 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002974 if (DEBUG_FOCUS) {
2975 ALOGD("channel '%s' ~ Split motion event.",
2976 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002977 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002978 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002979 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2980 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002981 return;
2982 }
2983 }
2984
2985 // Not splitting. Enqueue dispatch entries for the event as is.
2986 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2987}
2988
2989void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002990 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002991 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002992 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002993 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002994 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002995 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002996 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002997 ATRACE_NAME(message.c_str());
2998 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002999 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3000 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003001
hongzuo liu95785e22022-09-06 02:51:35 +00003002 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003003
3004 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003005 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003006 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003007 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003008 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003009 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003010 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003011 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003012 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003013 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003014 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003015 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003016 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017
3018 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003019 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003020 startDispatchCycleLocked(currentTime, connection);
3021 }
3022}
3023
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003024void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003025 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003026 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003027 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003028 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003029 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3030 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003031 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003032 ATRACE_NAME(message.c_str());
3033 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003034 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3035 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003036 return;
3037 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003038
3039 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3040 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003041
3042 // This is a new event.
3043 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003044 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003045 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003046
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003047 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3048 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003049 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003050 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003051 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003052 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003053 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003054 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003055 dispatchEntry->resolvedAction = keyEntry.action;
3056 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003057
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003058 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3059 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003060 if (DEBUG_DISPATCH_CYCLE) {
3061 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3062 "event",
3063 connection->getInputChannelName().c_str());
3064 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003065 return; // skip the inconsistent event
3066 }
3067 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003069
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003070 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003071 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003072 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3073 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3074 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3075 static_cast<int32_t>(IdGenerator::Source::OTHER);
3076 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003077 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003078 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003079 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003080 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003081 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003082 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003083 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003084 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003085 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003086 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3087 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003088 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003089 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003090 }
3091 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003092 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3093 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003094 if (DEBUG_DISPATCH_CYCLE) {
3095 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3096 "enter event",
3097 connection->getInputChannelName().c_str());
3098 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003099 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3100 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003101 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3102 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003104 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003105 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003106 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3107 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003108 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003109 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3110 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003111
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003112 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3113 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003114 if (DEBUG_DISPATCH_CYCLE) {
3115 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3116 "event",
3117 connection->getInputChannelName().c_str());
3118 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003119 return; // skip the inconsistent event
3120 }
3121
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003122 dispatchEntry->resolvedEventId =
3123 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3124 ? mIdGenerator.nextId()
3125 : motionEntry.id;
3126 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3127 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3128 ") to MotionEvent(id=0x%" PRIx32 ").",
3129 motionEntry.id, dispatchEntry->resolvedEventId);
3130 ATRACE_NAME(message.c_str());
3131 }
3132
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003133 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3134 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3135 // Skip reporting pointer down outside focus to the policy.
3136 break;
3137 }
3138
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003139 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003140 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003141
3142 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003143 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003144 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003145 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003146 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3147 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003148 break;
3149 }
Chris Yef59a2f42020-10-16 12:55:26 -07003150 case EventEntry::Type::SENSOR: {
3151 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3152 break;
3153 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003154 case EventEntry::Type::CONFIGURATION_CHANGED:
3155 case EventEntry::Type::DEVICE_RESET: {
3156 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003157 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003158 break;
3159 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160 }
3161
3162 // Remember that we are waiting for this dispatch to complete.
3163 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003164 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165 }
3166
3167 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003168 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003169 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003170}
3171
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003172/**
3173 * This function is purely for debugging. It helps us understand where the user interaction
3174 * was taking place. For example, if user is touching launcher, we will see a log that user
3175 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3176 * We will see both launcher and wallpaper in that list.
3177 * Once the interaction with a particular set of connections starts, no new logs will be printed
3178 * until the set of interacted connections changes.
3179 *
3180 * The following items are skipped, to reduce the logspam:
3181 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3182 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3183 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3184 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3185 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003186 */
3187void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3188 const std::vector<InputTarget>& targets) {
3189 // Skip ACTION_UP events, and all events other than keys and motions
3190 if (entry.type == EventEntry::Type::KEY) {
3191 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3192 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3193 return;
3194 }
3195 } else if (entry.type == EventEntry::Type::MOTION) {
3196 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3197 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3198 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3199 return;
3200 }
3201 } else {
3202 return; // Not a key or a motion
3203 }
3204
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003205 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003206 std::vector<sp<Connection>> newConnections;
3207 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003208 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003209 continue; // Skip windows that receive ACTION_OUTSIDE
3210 }
3211
3212 sp<IBinder> token = target.inputChannel->getConnectionToken();
3213 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003214 if (connection == nullptr) {
3215 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003216 }
3217 newConnectionTokens.insert(std::move(token));
3218 newConnections.emplace_back(connection);
3219 }
3220 if (newConnectionTokens == mInteractionConnectionTokens) {
3221 return; // no change
3222 }
3223 mInteractionConnectionTokens = newConnectionTokens;
3224
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003225 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003226 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003227 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003228 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003229 std::string message = "Interaction with: " + targetList;
3230 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003231 message += "<none>";
3232 }
3233 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3234}
3235
chaviwfd6d3512019-03-25 13:23:49 -07003236void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003237 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003238 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003239 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3240 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003241 return;
3242 }
3243
Vishnu Nairc519ff72021-01-21 08:23:08 -08003244 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003245 if (focusedToken == token) {
3246 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003247 return;
3248 }
3249
Prabir Pradhancef936d2021-07-21 16:17:52 +00003250 auto command = [this, token]() REQUIRES(mLock) {
3251 scoped_unlock unlock(mLock);
3252 mPolicy->onPointerDownOutsideFocus(token);
3253 };
3254 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255}
3256
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003257status_t InputDispatcher::publishMotionEvent(Connection& connection,
3258 DispatchEntry& dispatchEntry) const {
3259 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3260 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3261
3262 PointerCoords scaledCoords[MAX_POINTERS];
3263 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3264
3265 // Set the X and Y offset and X and Y scale depending on the input source.
3266 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003267 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003268 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3269 if (globalScaleFactor != 1.0f) {
3270 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3271 scaledCoords[i] = motionEntry.pointerCoords[i];
3272 // Don't apply window scale here since we don't want scale to affect raw
3273 // coordinates. The scale will be sent back to the client and applied
3274 // later when requesting relative coordinates.
3275 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3276 1 /* windowYScale */);
3277 }
3278 usingCoords = scaledCoords;
3279 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003280 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003281 // We don't want the dispatch target to know the coordinates
3282 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3283 scaledCoords[i].clear();
3284 }
3285 usingCoords = scaledCoords;
3286 }
3287
3288 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3289
3290 // Publish the motion event.
3291 return connection.inputPublisher
3292 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3293 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3294 std::move(hmac), dispatchEntry.resolvedAction,
3295 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3296 motionEntry.edgeFlags, motionEntry.metaState,
3297 motionEntry.buttonState, motionEntry.classification,
3298 dispatchEntry.transform, motionEntry.xPrecision,
3299 motionEntry.yPrecision, motionEntry.xCursorPosition,
3300 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3301 motionEntry.downTime, motionEntry.eventTime,
3302 motionEntry.pointerCount, motionEntry.pointerProperties,
3303 usingCoords);
3304}
3305
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003307 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003308 if (ATRACE_ENABLED()) {
3309 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003310 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003311 ATRACE_NAME(message.c_str());
3312 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003313 if (DEBUG_DISPATCH_CYCLE) {
3314 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003316
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003317 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003318 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003320 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003321 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003322
3323 // Publish the event.
3324 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003325 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3326 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003327 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003328 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3329 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003331 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003332 status = connection->inputPublisher
3333 .publishKeyEvent(dispatchEntry->seq,
3334 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3335 keyEntry.source, keyEntry.displayId,
3336 std::move(hmac), dispatchEntry->resolvedAction,
3337 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3338 keyEntry.scanCode, keyEntry.metaState,
3339 keyEntry.repeatCount, keyEntry.downTime,
3340 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003341 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342 }
3343
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003344 case EventEntry::Type::MOTION: {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003345 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003346 break;
3347 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003348
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003349 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003350 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003351 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003352 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003353 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003354 break;
3355 }
3356
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003357 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3358 const TouchModeEntry& touchModeEntry =
3359 static_cast<const TouchModeEntry&>(eventEntry);
3360 status = connection->inputPublisher
3361 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3362 touchModeEntry.inTouchMode);
3363
3364 break;
3365 }
3366
Prabir Pradhan99987712020-11-10 18:43:05 -08003367 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3368 const auto& captureEntry =
3369 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3370 status = connection->inputPublisher
3371 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003372 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003373 break;
3374 }
3375
arthurhungb89ccb02020-12-30 16:19:01 +08003376 case EventEntry::Type::DRAG: {
3377 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3378 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3379 dragEntry.id, dragEntry.x,
3380 dragEntry.y,
3381 dragEntry.isExiting);
3382 break;
3383 }
3384
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003385 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003386 case EventEntry::Type::DEVICE_RESET:
3387 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003388 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003389 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003390 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392 }
3393
3394 // Check the result.
3395 if (status) {
3396 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003397 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003398 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003399 "This is unexpected because the wait queue is empty, so the pipe "
3400 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003401 "event to it, status=%s(%d)",
3402 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3403 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3405 } else {
3406 // Pipe is full and we are waiting for the app to finish process some events
3407 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003408 if (DEBUG_DISPATCH_CYCLE) {
3409 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3410 "waiting for the application to catch up",
3411 connection->getInputChannelName().c_str());
3412 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413 }
3414 } else {
3415 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003416 "status=%s(%d)",
3417 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3418 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3420 }
3421 return;
3422 }
3423
3424 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003425 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3426 connection->outboundQueue.end(),
3427 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003428 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003429 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003430 if (connection->responsive) {
3431 mAnrTracker.insert(dispatchEntry->timeoutTime,
3432 connection->inputChannel->getConnectionToken());
3433 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003434 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435 }
3436}
3437
chaviw09c8d2d2020-08-24 15:48:26 -07003438std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3439 size_t size;
3440 switch (event.type) {
3441 case VerifiedInputEvent::Type::KEY: {
3442 size = sizeof(VerifiedKeyEvent);
3443 break;
3444 }
3445 case VerifiedInputEvent::Type::MOTION: {
3446 size = sizeof(VerifiedMotionEvent);
3447 break;
3448 }
3449 }
3450 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3451 return mHmacKeyManager.sign(start, size);
3452}
3453
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003454const std::array<uint8_t, 32> InputDispatcher::getSignature(
3455 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003456 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3457 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003458 // Only sign events up and down events as the purely move events
3459 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003460 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003461 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003462
3463 VerifiedMotionEvent verifiedEvent =
3464 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3465 verifiedEvent.actionMasked = actionMasked;
3466 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3467 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003468}
3469
3470const std::array<uint8_t, 32> InputDispatcher::getSignature(
3471 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3472 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3473 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3474 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003475 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003476}
3477
Michael Wrightd02c5b62014-02-10 15:10:22 -08003478void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003479 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003480 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003481 if (DEBUG_DISPATCH_CYCLE) {
3482 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3483 connection->getInputChannelName().c_str(), seq, toString(handled));
3484 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003485
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003486 if (connection->status == Connection::Status::BROKEN ||
3487 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003488 return;
3489 }
3490
3491 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003492 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3493 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3494 };
3495 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496}
3497
3498void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003499 const sp<Connection>& connection,
3500 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003501 if (DEBUG_DISPATCH_CYCLE) {
3502 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3503 connection->getInputChannelName().c_str(), toString(notify));
3504 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505
3506 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003507 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003508 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003509 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003510 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511
3512 // The connection appears to be unrecoverably broken.
3513 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003514 if (connection->status == Connection::Status::NORMAL) {
3515 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516
3517 if (notify) {
3518 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003519 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3520 connection->getInputChannelName().c_str());
3521
3522 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003523 scoped_unlock unlock(mLock);
3524 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3525 };
3526 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 }
3528 }
3529}
3530
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003531void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3532 while (!queue.empty()) {
3533 DispatchEntry* dispatchEntry = queue.front();
3534 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003535 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003536 }
3537}
3538
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003539void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003541 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542 }
3543 delete dispatchEntry;
3544}
3545
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003546int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3547 std::scoped_lock _l(mLock);
3548 sp<Connection> connection = getConnectionLocked(connectionToken);
3549 if (connection == nullptr) {
3550 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3551 connectionToken.get(), events);
3552 return 0; // remove the callback
3553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003554
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003555 bool notify;
3556 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3557 if (!(events & ALOOPER_EVENT_INPUT)) {
3558 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3559 "events=0x%x",
3560 connection->getInputChannelName().c_str(), events);
3561 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003562 }
3563
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003564 nsecs_t currentTime = now();
3565 bool gotOne = false;
3566 status_t status = OK;
3567 for (;;) {
3568 Result<InputPublisher::ConsumerResponse> result =
3569 connection->inputPublisher.receiveConsumerResponse();
3570 if (!result.ok()) {
3571 status = result.error().code();
3572 break;
3573 }
3574
3575 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3576 const InputPublisher::Finished& finish =
3577 std::get<InputPublisher::Finished>(*result);
3578 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3579 finish.consumeTime);
3580 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003581 if (shouldReportMetricsForConnection(*connection)) {
3582 const InputPublisher::Timeline& timeline =
3583 std::get<InputPublisher::Timeline>(*result);
3584 mLatencyTracker
3585 .trackGraphicsLatency(timeline.inputEventId,
3586 connection->inputChannel->getConnectionToken(),
3587 std::move(timeline.graphicsTimeline));
3588 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003589 }
3590 gotOne = true;
3591 }
3592 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003593 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003594 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595 return 1;
3596 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 }
3598
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003599 notify = status != DEAD_OBJECT || !connection->monitor;
3600 if (notify) {
3601 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3602 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3603 status);
3604 }
3605 } else {
3606 // Monitor channels are never explicitly unregistered.
3607 // We do it automatically when the remote endpoint is closed so don't warn about them.
3608 const bool stillHaveWindowHandle =
3609 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3610 notify = !connection->monitor && stillHaveWindowHandle;
3611 if (notify) {
3612 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3613 connection->getInputChannelName().c_str(), events);
3614 }
3615 }
3616
3617 // Remove the channel.
3618 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3619 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620}
3621
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003622void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003624 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003625 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 }
3627}
3628
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003629void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003630 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003631 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003632 for (const Monitor& monitor : monitors) {
3633 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003634 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003635 }
3636}
3637
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003639 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003640 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003641 if (connection == nullptr) {
3642 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003644
3645 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646}
3647
3648void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3649 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003650 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003651 return;
3652 }
3653
3654 nsecs_t currentTime = now();
3655
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003656 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003657 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003659 if (cancelationEvents.empty()) {
3660 return;
3661 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003662 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3663 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3664 "with reality: %s, mode=%d.",
3665 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3666 options.mode);
3667 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003668
Arthur Hungb3307ee2021-10-14 10:57:37 +00003669 std::string reason = std::string("reason=").append(options.reason);
3670 android_log_event_list(LOGTAG_INPUT_CANCEL)
3671 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3672
Svet Ganov5d3bc372020-01-26 23:11:07 -08003673 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003674 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003675 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3676 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003677 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003678 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003679 target.globalScaleFactor = windowInfo->globalScaleFactor;
3680 }
3681 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003682 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003683
hongzuo liu95785e22022-09-06 02:51:35 +00003684 const bool wasEmpty = connection->outboundQueue.empty();
3685
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003686 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003687 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003688 switch (cancelationEventEntry->type) {
3689 case EventEntry::Type::KEY: {
3690 logOutboundKeyDetails("cancel - ",
3691 static_cast<const KeyEntry&>(*cancelationEventEntry));
3692 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003694 case EventEntry::Type::MOTION: {
3695 logOutboundMotionDetails("cancel - ",
3696 static_cast<const MotionEntry&>(*cancelationEventEntry));
3697 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003699 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003700 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003701 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3702 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003703 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003704 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003705 break;
3706 }
3707 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003708 case EventEntry::Type::DEVICE_RESET:
3709 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003710 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003711 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003712 break;
3713 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714 }
3715
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003716 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003717 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003718 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003719
hongzuo liu95785e22022-09-06 02:51:35 +00003720 // If the outbound queue was previously empty, start the dispatch cycle going.
3721 if (wasEmpty && !connection->outboundQueue.empty()) {
3722 startDispatchCycleLocked(currentTime, connection);
3723 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724}
3725
Svet Ganov5d3bc372020-01-26 23:11:07 -08003726void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003727 const nsecs_t downTime, const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003728 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003729 return;
3730 }
3731
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003732 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003733 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003734
3735 if (downEvents.empty()) {
3736 return;
3737 }
3738
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003739 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003740 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3741 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003742 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003743
3744 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003745 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003746 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3747 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003748 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003749 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003750 target.globalScaleFactor = windowInfo->globalScaleFactor;
3751 }
3752 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003753 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003754
hongzuo liu95785e22022-09-06 02:51:35 +00003755 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003756 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003757 switch (downEventEntry->type) {
3758 case EventEntry::Type::MOTION: {
3759 logOutboundMotionDetails("down - ",
3760 static_cast<const MotionEntry&>(*downEventEntry));
3761 break;
3762 }
3763
3764 case EventEntry::Type::KEY:
3765 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003766 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003767 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003768 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003769 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003770 case EventEntry::Type::SENSOR:
3771 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003772 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003773 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003774 break;
3775 }
3776 }
3777
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003778 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003779 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003780 }
3781
hongzuo liu95785e22022-09-06 02:51:35 +00003782 // If the outbound queue was previously empty, start the dispatch cycle going.
3783 if (wasEmpty && !connection->outboundQueue.empty()) {
3784 startDispatchCycleLocked(downTime, connection);
3785 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003786}
3787
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003788std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003789 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790 ALOG_ASSERT(pointerIds.value != 0);
3791
3792 uint32_t splitPointerIndexMap[MAX_POINTERS];
3793 PointerProperties splitPointerProperties[MAX_POINTERS];
3794 PointerCoords splitPointerCoords[MAX_POINTERS];
3795
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003796 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797 uint32_t splitPointerCount = 0;
3798
3799 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003800 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003801 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003802 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803 uint32_t pointerId = uint32_t(pointerProperties.id);
3804 if (pointerIds.hasBit(pointerId)) {
3805 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3806 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3807 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003808 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003809 splitPointerCount += 1;
3810 }
3811 }
3812
3813 if (splitPointerCount != pointerIds.count()) {
3814 // This is bad. We are missing some of the pointers that we expected to deliver.
3815 // Most likely this indicates that we received an ACTION_MOVE events that has
3816 // different pointer ids than we expected based on the previous ACTION_DOWN
3817 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3818 // in this way.
3819 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003820 "we expected there to be %d pointers. This probably means we received "
3821 "a broken sequence of pointer ids from the input device.",
3822 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003823 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824 }
3825
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003826 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003827 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003828 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3829 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003830 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3831 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003832 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833 uint32_t pointerId = uint32_t(pointerProperties.id);
3834 if (pointerIds.hasBit(pointerId)) {
3835 if (pointerIds.count() == 1) {
3836 // The first/last pointer went down/up.
3837 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003838 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003839 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3840 ? AMOTION_EVENT_ACTION_CANCEL
3841 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003842 } else {
3843 // A secondary pointer went down/up.
3844 uint32_t splitPointerIndex = 0;
3845 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3846 splitPointerIndex += 1;
3847 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003848 action = maskedAction |
3849 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003850 }
3851 } else {
3852 // An unrelated pointer changed.
3853 action = AMOTION_EVENT_ACTION_MOVE;
3854 }
3855 }
3856
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003857 if (action == AMOTION_EVENT_ACTION_DOWN) {
3858 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3859 "Split motion event has mismatching downTime and eventTime for "
3860 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3861 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3862 }
3863
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003864 int32_t newId = mIdGenerator.nextId();
3865 if (ATRACE_ENABLED()) {
3866 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3867 ") to MotionEvent(id=0x%" PRIx32 ").",
3868 originalMotionEntry.id, newId);
3869 ATRACE_NAME(message.c_str());
3870 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003871 std::unique_ptr<MotionEntry> splitMotionEntry =
3872 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3873 originalMotionEntry.deviceId, originalMotionEntry.source,
3874 originalMotionEntry.displayId,
3875 originalMotionEntry.policyFlags, action,
3876 originalMotionEntry.actionButton,
3877 originalMotionEntry.flags, originalMotionEntry.metaState,
3878 originalMotionEntry.buttonState,
3879 originalMotionEntry.classification,
3880 originalMotionEntry.edgeFlags,
3881 originalMotionEntry.xPrecision,
3882 originalMotionEntry.yPrecision,
3883 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003884 originalMotionEntry.yCursorPosition, splitDownTime,
3885 splitPointerCount, splitPointerProperties,
3886 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003888 if (originalMotionEntry.injectionState) {
3889 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003890 splitMotionEntry->injectionState->refCount += 1;
3891 }
3892
3893 return splitMotionEntry;
3894}
3895
3896void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003897 if (DEBUG_INBOUND_EVENT_DETAILS) {
3898 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3899 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900
Antonio Kantekf16f2832021-09-28 04:39:20 +00003901 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003903 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003905 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3906 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3907 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908 } // release lock
3909
3910 if (needWake) {
3911 mLooper->wake();
3912 }
3913}
3914
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003915/**
3916 * If one of the meta shortcuts is detected, process them here:
3917 * Meta + Backspace -> generate BACK
3918 * Meta + Enter -> generate HOME
3919 * This will potentially overwrite keyCode and metaState.
3920 */
3921void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003922 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003923 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3924 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3925 if (keyCode == AKEYCODE_DEL) {
3926 newKeyCode = AKEYCODE_BACK;
3927 } else if (keyCode == AKEYCODE_ENTER) {
3928 newKeyCode = AKEYCODE_HOME;
3929 }
3930 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003931 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003932 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003933 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003934 keyCode = newKeyCode;
3935 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3936 }
3937 } else if (action == AKEY_EVENT_ACTION_UP) {
3938 // In order to maintain a consistent stream of up and down events, check to see if the key
3939 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3940 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003941 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003942 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003943 auto replacementIt = mReplacedKeys.find(replacement);
3944 if (replacementIt != mReplacedKeys.end()) {
3945 keyCode = replacementIt->second;
3946 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003947 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3948 }
3949 }
3950}
3951
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003953 if (DEBUG_INBOUND_EVENT_DETAILS) {
3954 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3955 "policyFlags=0x%x, action=0x%x, "
3956 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3957 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3958 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3959 args->downTime);
3960 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961 if (!validateKeyEvent(args->action)) {
3962 return;
3963 }
3964
3965 uint32_t policyFlags = args->policyFlags;
3966 int32_t flags = args->flags;
3967 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003968 // InputDispatcher tracks and generates key repeats on behalf of
3969 // whatever notifies it, so repeatCount should always be set to 0
3970 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3972 policyFlags |= POLICY_FLAG_VIRTUAL;
3973 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 if (policyFlags & POLICY_FLAG_FUNCTION) {
3976 metaState |= AMETA_FUNCTION_ON;
3977 }
3978
3979 policyFlags |= POLICY_FLAG_TRUSTED;
3980
Michael Wright78f24442014-08-06 15:55:28 -07003981 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003982 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003983
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003985 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003986 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3987 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988
Michael Wright2b3c3302018-03-02 17:19:13 +00003989 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003991 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3992 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003993 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003994 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995
Antonio Kantekf16f2832021-09-28 04:39:20 +00003996 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003997 { // acquire lock
3998 mLock.lock();
3999
4000 if (shouldSendKeyToInputFilterLocked(args)) {
4001 mLock.unlock();
4002
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004003 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4005 return; // event was consumed by the filter
4006 }
4007
4008 mLock.lock();
4009 }
4010
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004011 std::unique_ptr<KeyEntry> newEntry =
4012 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4013 args->displayId, policyFlags, args->action, flags,
4014 keyCode, args->scanCode, metaState, repeatCount,
4015 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004017 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018 mLock.unlock();
4019 } // release lock
4020
4021 if (needWake) {
4022 mLooper->wake();
4023 }
4024}
4025
4026bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4027 return mInputFilterEnabled;
4028}
4029
4030void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004031 if (DEBUG_INBOUND_EVENT_DETAILS) {
4032 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4033 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004034 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004035 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4036 "yCursorPosition=%f, downTime=%" PRId64,
4037 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004038 args->policyFlags, MotionEvent::actionToString(args->action).c_str(),
4039 args->actionButton, args->flags, args->metaState, args->buttonState, args->edgeFlags,
4040 args->xPrecision, args->yPrecision, args->xCursorPosition, args->yCursorPosition,
4041 args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004042 for (uint32_t i = 0; i < args->pointerCount; i++) {
4043 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4044 "x=%f, y=%f, pressure=%f, size=%f, "
4045 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4046 "orientation=%f",
4047 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4048 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4049 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4050 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4051 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4052 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4053 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4054 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4055 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4056 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004059 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4060 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004061 return;
4062 }
4063
4064 uint32_t policyFlags = args->policyFlags;
4065 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004066
4067 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004068 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004069 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4070 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004071 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004072 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073
Antonio Kantekf16f2832021-09-28 04:39:20 +00004074 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075 { // acquire lock
4076 mLock.lock();
4077
4078 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004079 ui::Transform displayTransform;
4080 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4081 displayTransform = it->second.transform;
4082 }
4083
Michael Wrightd02c5b62014-02-10 15:10:22 -08004084 mLock.unlock();
4085
4086 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004087 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4088 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004089 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004090 displayTransform, args->xPrecision, args->yPrecision,
4091 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004092 args->downTime, args->eventTime, args->pointerCount,
4093 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094
4095 policyFlags |= POLICY_FLAG_FILTERED;
4096 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4097 return; // event was consumed by the filter
4098 }
4099
4100 mLock.lock();
4101 }
4102
4103 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004104 std::unique_ptr<MotionEntry> newEntry =
4105 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4106 args->source, args->displayId, policyFlags,
4107 args->action, args->actionButton, args->flags,
4108 args->metaState, args->buttonState,
4109 args->classification, args->edgeFlags,
4110 args->xPrecision, args->yPrecision,
4111 args->xCursorPosition, args->yCursorPosition,
4112 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004113 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004115 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4116 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4117 !mInputFilterEnabled) {
4118 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4119 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4120 }
4121
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004122 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123 mLock.unlock();
4124 } // release lock
4125
4126 if (needWake) {
4127 mLooper->wake();
4128 }
4129}
4130
Chris Yef59a2f42020-10-16 12:55:26 -07004131void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004132 if (DEBUG_INBOUND_EVENT_DETAILS) {
4133 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4134 " sensorType=%s",
4135 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004136 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004137 }
Chris Yef59a2f42020-10-16 12:55:26 -07004138
Antonio Kantekf16f2832021-09-28 04:39:20 +00004139 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004140 { // acquire lock
4141 mLock.lock();
4142
4143 // Just enqueue a new sensor event.
4144 std::unique_ptr<SensorEntry> newEntry =
4145 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4146 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4147 args->sensorType, args->accuracy,
4148 args->accuracyChanged, args->values);
4149
4150 needWake = enqueueInboundEventLocked(std::move(newEntry));
4151 mLock.unlock();
4152 } // release lock
4153
4154 if (needWake) {
4155 mLooper->wake();
4156 }
4157}
4158
Chris Yefb552902021-02-03 17:18:37 -08004159void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004160 if (DEBUG_INBOUND_EVENT_DETAILS) {
4161 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4162 args->deviceId, args->isOn);
4163 }
Chris Yefb552902021-02-03 17:18:37 -08004164 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4165}
4166
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004168 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169}
4170
4171void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004172 if (DEBUG_INBOUND_EVENT_DETAILS) {
4173 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4174 "switchMask=0x%08x",
4175 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4176 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004177
4178 uint32_t policyFlags = args->policyFlags;
4179 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004180 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181}
4182
4183void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004184 if (DEBUG_INBOUND_EVENT_DETAILS) {
4185 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4186 args->deviceId);
4187 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188
Antonio Kantekf16f2832021-09-28 04:39:20 +00004189 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004191 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004193 std::unique_ptr<DeviceResetEntry> newEntry =
4194 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4195 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196 } // release lock
4197
4198 if (needWake) {
4199 mLooper->wake();
4200 }
4201}
4202
Prabir Pradhan7e186182020-11-10 13:56:45 -08004203void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004204 if (DEBUG_INBOUND_EVENT_DETAILS) {
4205 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004206 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004207 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004208
Antonio Kantekf16f2832021-09-28 04:39:20 +00004209 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004210 { // acquire lock
4211 std::scoped_lock _l(mLock);
4212 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004213 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004214 needWake = enqueueInboundEventLocked(std::move(entry));
4215 } // release lock
4216
4217 if (needWake) {
4218 mLooper->wake();
4219 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004220}
4221
Prabir Pradhan5735a322022-04-11 17:23:34 +00004222InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4223 std::optional<int32_t> targetUid,
4224 InputEventInjectionSync syncMode,
4225 std::chrono::milliseconds timeout,
4226 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004227 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004228 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4229 "policyFlags=0x%08x",
4230 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4231 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004232 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004233 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234
Prabir Pradhan5735a322022-04-11 17:23:34 +00004235 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004237 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004238 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4239 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4240 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4241 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4242 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004243 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004244 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004245 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004246 }
4247
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004248 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004250 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004251 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4252 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004253 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004254 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004257 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004258 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4259 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4260 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004261 int32_t keyCode = incomingKey.getKeyCode();
4262 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004263 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004264 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004265 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004266 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004267 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4268 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4269 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004271 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4272 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004273 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004274
4275 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4276 android::base::Timer t;
4277 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4278 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4279 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4280 std::to_string(t.duration().count()).c_str());
4281 }
4282 }
4283
4284 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004285 std::unique_ptr<KeyEntry> injectedEntry =
4286 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004287 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004288 incomingKey.getDisplayId(), policyFlags, action,
4289 flags, keyCode, incomingKey.getScanCode(), metaState,
4290 incomingKey.getRepeatCount(),
4291 incomingKey.getDownTime());
4292 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004293 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294 }
4295
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004296 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004297 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004298 const int32_t action = motionEvent.getAction();
4299 const bool isPointerEvent =
4300 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4301 // If a pointer event has no displayId specified, inject it to the default display.
4302 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4303 ? ADISPLAY_ID_DEFAULT
4304 : event->getDisplayId();
4305 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004306 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004307 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004308 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004309 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004310 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004311 }
4312
4313 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004314 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004315 android::base::Timer t;
4316 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4317 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4318 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4319 std::to_string(t.duration().count()).c_str());
4320 }
4321 }
4322
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004323 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4324 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4325 }
4326
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004327 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004328 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4329 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004330 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004331 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4332 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004333 displayId, policyFlags, action, actionButton,
4334 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004335 motionEvent.getButtonState(),
4336 motionEvent.getClassification(),
4337 motionEvent.getEdgeFlags(),
4338 motionEvent.getXPrecision(),
4339 motionEvent.getYPrecision(),
4340 motionEvent.getRawXCursorPosition(),
4341 motionEvent.getRawYCursorPosition(),
4342 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004343 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004344 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004345 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004346 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004347 sampleEventTimes += 1;
4348 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004349 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004350 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4351 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004352 displayId, policyFlags, action, actionButton,
4353 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004354 motionEvent.getButtonState(),
4355 motionEvent.getClassification(),
4356 motionEvent.getEdgeFlags(),
4357 motionEvent.getXPrecision(),
4358 motionEvent.getYPrecision(),
4359 motionEvent.getRawXCursorPosition(),
4360 motionEvent.getRawYCursorPosition(),
4361 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004362 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004363 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004364 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4365 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004366 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004367 }
4368 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004370
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004371 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004372 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004373 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374 }
4375
Prabir Pradhan5735a322022-04-11 17:23:34 +00004376 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004377 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378 injectionState->injectionIsAsync = true;
4379 }
4380
4381 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004382 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383
4384 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004385 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004386 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004387 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388 }
4389
4390 mLock.unlock();
4391
4392 if (needWake) {
4393 mLooper->wake();
4394 }
4395
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004396 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004397 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004398 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004400 if (syncMode == InputEventInjectionSync::NONE) {
4401 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004402 } else {
4403 for (;;) {
4404 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004405 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004406 break;
4407 }
4408
4409 nsecs_t remainingTimeout = endTime - now();
4410 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004411 if (DEBUG_INJECTION) {
4412 ALOGD("injectInputEvent - Timed out waiting for injection result "
4413 "to become available.");
4414 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004415 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004416 break;
4417 }
4418
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004419 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420 }
4421
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004422 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4423 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004425 if (DEBUG_INJECTION) {
4426 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4427 injectionState->pendingForegroundDispatches);
4428 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004429 nsecs_t remainingTimeout = endTime - now();
4430 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004431 if (DEBUG_INJECTION) {
4432 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4433 "dispatches to finish.");
4434 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004435 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004436 break;
4437 }
4438
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004439 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004440 }
4441 }
4442 }
4443
4444 injectionState->release();
4445 } // release lock
4446
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004447 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004448 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004449 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004450
4451 return injectionResult;
4452}
4453
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004454std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004455 std::array<uint8_t, 32> calculatedHmac;
4456 std::unique_ptr<VerifiedInputEvent> result;
4457 switch (event.getType()) {
4458 case AINPUT_EVENT_TYPE_KEY: {
4459 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4460 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4461 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004462 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004463 break;
4464 }
4465 case AINPUT_EVENT_TYPE_MOTION: {
4466 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4467 VerifiedMotionEvent verifiedMotionEvent =
4468 verifiedMotionEventFromMotionEvent(motionEvent);
4469 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004470 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004471 break;
4472 }
4473 default: {
4474 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4475 return nullptr;
4476 }
4477 }
4478 if (calculatedHmac == INVALID_HMAC) {
4479 return nullptr;
4480 }
4481 if (calculatedHmac != event.getHmac()) {
4482 return nullptr;
4483 }
4484 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004485}
4486
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004487void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004488 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004489 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004490 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004491 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004492 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004493 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004494
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004495 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496 // Log the outcome since the injector did not wait for the injection result.
4497 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004498 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004499 ALOGV("Asynchronous input event injection succeeded.");
4500 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004501 case InputEventInjectionResult::TARGET_MISMATCH:
4502 ALOGV("Asynchronous input event injection target mismatch.");
4503 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004504 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004505 ALOGW("Asynchronous input event injection failed.");
4506 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004507 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004508 ALOGW("Asynchronous input event injection timed out.");
4509 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004510 case InputEventInjectionResult::PENDING:
4511 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4512 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004513 }
4514 }
4515
4516 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004517 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004518 }
4519}
4520
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004521void InputDispatcher::transformMotionEntryForInjectionLocked(
4522 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004523 // Input injection works in the logical display coordinate space, but the input pipeline works
4524 // display space, so we need to transform the injected events accordingly.
4525 const auto it = mDisplayInfos.find(entry.displayId);
4526 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004527 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004528
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004529 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4530 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4531 const vec2 cursor =
4532 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4533 {entry.xCursorPosition, entry.yCursorPosition});
4534 entry.xCursorPosition = cursor.x;
4535 entry.yCursorPosition = cursor.y;
4536 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004537 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004538 entry.pointerCoords[i] =
4539 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4540 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004541 }
4542}
4543
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004544void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4545 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546 if (injectionState) {
4547 injectionState->pendingForegroundDispatches += 1;
4548 }
4549}
4550
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004551void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4552 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553 if (injectionState) {
4554 injectionState->pendingForegroundDispatches -= 1;
4555
4556 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004557 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004558 }
4559 }
4560}
4561
chaviw98318de2021-05-19 16:45:23 -05004562const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004563 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004564 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004565 auto it = mWindowHandlesByDisplay.find(displayId);
4566 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004567}
4568
chaviw98318de2021-05-19 16:45:23 -05004569sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004570 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004571 if (windowHandleToken == nullptr) {
4572 return nullptr;
4573 }
4574
Arthur Hungb92218b2018-08-14 12:00:21 +08004575 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004576 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4577 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004578 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004579 return windowHandle;
4580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581 }
4582 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004583 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004584}
4585
chaviw98318de2021-05-19 16:45:23 -05004586sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4587 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004588 if (windowHandleToken == nullptr) {
4589 return nullptr;
4590 }
4591
chaviw98318de2021-05-19 16:45:23 -05004592 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004593 if (windowHandle->getToken() == windowHandleToken) {
4594 return windowHandle;
4595 }
4596 }
4597 return nullptr;
4598}
4599
chaviw98318de2021-05-19 16:45:23 -05004600sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4601 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004602 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004603 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4604 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004605 if (handle->getId() == windowHandle->getId() &&
4606 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004607 if (windowHandle->getInfo()->displayId != it.first) {
4608 ALOGE("Found window %s in display %" PRId32
4609 ", but it should belong to display %" PRId32,
4610 windowHandle->getName().c_str(), it.first,
4611 windowHandle->getInfo()->displayId);
4612 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004613 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004614 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004615 }
4616 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004617 return nullptr;
4618}
4619
chaviw98318de2021-05-19 16:45:23 -05004620sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004621 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4622 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004623}
4624
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004625bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4626 const MotionEntry& motionEntry) const {
4627 const WindowInfo& info = *window->getInfo();
4628
4629 // Skip spy window targets that are not valid for targeted injection.
4630 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004631 return false;
4632 }
4633
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004634 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4635 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4636 return false;
4637 }
4638
4639 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4640 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4641 window->getName().c_str());
4642 return false;
4643 }
4644
4645 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004646 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004647 ALOGW("Not sending touch to %s because there's no corresponding connection",
4648 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004649 return false;
4650 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004651
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004652 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004653 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004654 return false;
4655 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004656
4657 // Drop events that can't be trusted due to occlusion
4658 const auto [x, y] = resolveTouchedPosition(motionEntry);
4659 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4660 if (!isTouchTrustedLocked(occlusionInfo)) {
4661 if (DEBUG_TOUCH_OCCLUSION) {
4662 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4663 for (const auto& log : occlusionInfo.debugInfo) {
4664 ALOGD("%s", log.c_str());
4665 }
4666 }
4667 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4668 occlusionInfo.obscuringUid);
4669 return false;
4670 }
4671
4672 // Drop touch events if requested by input feature
4673 if (shouldDropInput(motionEntry, window)) {
4674 return false;
4675 }
4676
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004677 return true;
4678}
4679
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004680std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4681 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004682 auto connectionIt = mConnectionsByToken.find(token);
4683 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004684 return nullptr;
4685 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004686 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004687}
4688
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004689void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004690 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4691 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004692 // Remove all handles on a display if there are no windows left.
4693 mWindowHandlesByDisplay.erase(displayId);
4694 return;
4695 }
4696
4697 // Since we compare the pointer of input window handles across window updates, we need
4698 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004699 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4700 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4701 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004702 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004703 }
4704
chaviw98318de2021-05-19 16:45:23 -05004705 std::vector<sp<WindowInfoHandle>> newHandles;
4706 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004707 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004708 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004709 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004710 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004711 const bool canReceiveInput =
4712 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4713 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004714 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004715 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004716 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004717 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004718 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004719 }
4720
4721 if (info->displayId != displayId) {
4722 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4723 handle->getName().c_str(), displayId, info->displayId);
4724 continue;
4725 }
4726
Robert Carredd13602020-04-13 17:24:34 -07004727 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4728 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004729 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004730 oldHandle->updateFrom(handle);
4731 newHandles.push_back(oldHandle);
4732 } else {
4733 newHandles.push_back(handle);
4734 }
4735 }
4736
4737 // Insert or replace
4738 mWindowHandlesByDisplay[displayId] = newHandles;
4739}
4740
Arthur Hung72d8dc32020-03-28 00:48:39 +00004741void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004742 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004743 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004744 { // acquire lock
4745 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004746 for (const auto& [displayId, handles] : handlesPerDisplay) {
4747 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004748 }
4749 }
4750 // Wake up poll loop since it may need to make new input dispatching choices.
4751 mLooper->wake();
4752}
4753
Arthur Hungb92218b2018-08-14 12:00:21 +08004754/**
4755 * Called from InputManagerService, update window handle list by displayId that can receive input.
4756 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4757 * If set an empty list, remove all handles from the specific display.
4758 * For focused handle, check if need to change and send a cancel event to previous one.
4759 * For removed handle, check if need to send a cancel event if already in touch.
4760 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004761void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004762 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004763 if (DEBUG_FOCUS) {
4764 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004765 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004766 windowList += iwh->getName() + " ";
4767 }
4768 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4769 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004770
Prabir Pradhand65552b2021-10-07 11:23:50 -07004771 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004772 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004773 const WindowInfo& info = *window->getInfo();
4774
4775 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004776 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004777 if (noInputWindow && window->getToken() != nullptr) {
4778 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4779 window->getName().c_str());
4780 window->releaseChannel();
4781 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004782
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004783 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004784 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4785 !info.inputConfig.test(
4786 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004787 "%s has feature SPY, but is not a trusted overlay.",
4788 window->getName().c_str());
4789
Prabir Pradhand65552b2021-10-07 11:23:50 -07004790 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004791 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4792 !info.inputConfig.test(
4793 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004794 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4795 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004796 }
4797
Arthur Hung72d8dc32020-03-28 00:48:39 +00004798 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004799 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004800
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004801 // Save the old windows' orientation by ID before it gets updated.
4802 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004803 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004804 oldWindowOrientations.emplace(handle->getId(),
4805 handle->getInfo()->transform.getOrientation());
4806 }
4807
chaviw98318de2021-05-19 16:45:23 -05004808 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004809
chaviw98318de2021-05-19 16:45:23 -05004810 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Tommy Nordgrendae9dfc2022-10-13 11:25:57 +02004811 if (mLastHoverWindowHandle) {
4812 const WindowInfo* lastHoverWindowInfo = mLastHoverWindowHandle->getInfo();
4813 if (lastHoverWindowInfo->displayId == displayId &&
4814 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4815 windowHandles.end()) {
4816 mLastHoverWindowHandle = nullptr;
4817 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004818 }
4819
Vishnu Nairc519ff72021-01-21 08:23:08 -08004820 std::optional<FocusResolver::FocusChanges> changes =
4821 mFocusResolver.setInputWindows(displayId, windowHandles);
4822 if (changes) {
4823 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004825
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004826 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4827 mTouchStatesByDisplay.find(displayId);
4828 if (stateIt != mTouchStatesByDisplay.end()) {
4829 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004830 for (size_t i = 0; i < state.windows.size();) {
4831 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004832 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004833 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004834 ALOGD("Touched window was removed: %s in display %" PRId32,
4835 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004836 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004837 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004838 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4839 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004840 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00004841 "touched window was removed");
4842 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004843 // Since we are about to drop the touch, cancel the events for the wallpaper as
4844 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004845 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004846 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4847 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004848 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4849 if (wallpaper != nullptr) {
4850 sp<Connection> wallpaperConnection =
4851 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004852 if (wallpaperConnection != nullptr) {
4853 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4854 options);
4855 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004856 }
4857 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004858 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004859 state.windows.erase(state.windows.begin() + i);
4860 } else {
4861 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862 }
4863 }
arthurhungb89ccb02020-12-30 16:19:01 +08004864
arthurhung6d4bed92021-03-17 11:59:33 +08004865 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004866 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004867 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004868 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004869 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004870 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4871 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004872 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004873 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004874 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004875
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004876 // Determine if the orientation of any of the input windows have changed, and cancel all
4877 // pointer events if necessary.
4878 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4879 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4880 if (newWindowHandle != nullptr &&
4881 newWindowHandle->getInfo()->transform.getOrientation() !=
4882 oldWindowOrientations[oldWindowHandle->getId()]) {
4883 std::shared_ptr<InputChannel> inputChannel =
4884 getInputChannelLocked(newWindowHandle->getToken());
4885 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004886 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004887 "touched window's orientation changed");
4888 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004889 }
4890 }
4891 }
4892
Arthur Hung72d8dc32020-03-28 00:48:39 +00004893 // Release information for windows that are no longer present.
4894 // This ensures that unused input channels are released promptly.
4895 // Otherwise, they might stick around until the window handle is destroyed
4896 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004897 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004898 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004899 if (DEBUG_FOCUS) {
4900 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004901 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004902 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004903 }
chaviw291d88a2019-02-14 10:33:58 -08004904 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004905}
4906
4907void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004908 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004909 if (DEBUG_FOCUS) {
4910 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4911 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4912 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004913 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004914 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004915 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004916 } // release lock
4917
4918 // Wake up poll loop since it may need to make new input dispatching choices.
4919 mLooper->wake();
4920}
4921
Vishnu Nair599f1412021-06-21 10:39:58 -07004922void InputDispatcher::setFocusedApplicationLocked(
4923 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4924 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4925 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4926
4927 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4928 return; // This application is already focused. No need to wake up or change anything.
4929 }
4930
4931 // Set the new application handle.
4932 if (inputApplicationHandle != nullptr) {
4933 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4934 } else {
4935 mFocusedApplicationHandlesByDisplay.erase(displayId);
4936 }
4937
4938 // No matter what the old focused application was, stop waiting on it because it is
4939 // no longer focused.
4940 resetNoFocusedWindowTimeoutLocked();
4941}
4942
Tiger Huang721e26f2018-07-24 22:26:19 +08004943/**
4944 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4945 * the display not specified.
4946 *
4947 * We track any unreleased events for each window. If a window loses the ability to receive the
4948 * released event, we will send a cancel event to it. So when the focused display is changed, we
4949 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4950 * display. The display-specified events won't be affected.
4951 */
4952void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004953 if (DEBUG_FOCUS) {
4954 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4955 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004956 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004957 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004958
4959 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004960 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004961 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004962 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004963 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004964 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004965 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004966 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00004967 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004968 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004969 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004970 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4971 }
4972 }
4973 mFocusedDisplayId = displayId;
4974
Chris Ye3c2d6f52020-08-09 10:39:48 -07004975 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004976 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004977 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004978
Vishnu Nairad321cd2020-08-20 16:40:21 -07004979 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004980 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004981 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004982 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004983 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004984 }
4985 }
4986 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004987 } // release lock
4988
4989 // Wake up poll loop since it may need to make new input dispatching choices.
4990 mLooper->wake();
4991}
4992
Michael Wrightd02c5b62014-02-10 15:10:22 -08004993void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004994 if (DEBUG_FOCUS) {
4995 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4996 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004997
4998 bool changed;
4999 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005000 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005001
5002 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5003 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005004 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005005 }
5006
5007 if (mDispatchEnabled && !enabled) {
5008 resetAndDropEverythingLocked("dispatcher is being disabled");
5009 }
5010
5011 mDispatchEnabled = enabled;
5012 mDispatchFrozen = frozen;
5013 changed = true;
5014 } else {
5015 changed = false;
5016 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005017 } // release lock
5018
5019 if (changed) {
5020 // Wake up poll loop since it may need to make new input dispatching choices.
5021 mLooper->wake();
5022 }
5023}
5024
5025void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005026 if (DEBUG_FOCUS) {
5027 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005029
5030 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005031 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005032
5033 if (mInputFilterEnabled == enabled) {
5034 return;
5035 }
5036
5037 mInputFilterEnabled = enabled;
5038 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5039 } // release lock
5040
5041 // Wake up poll loop since there might be work to do to drop everything.
5042 mLooper->wake();
5043}
5044
Antonio Kanteka042c022022-07-06 16:51:07 -07005045bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5046 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005047 bool needWake = false;
5048 {
5049 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005050 ALOGD_IF(DEBUG_TOUCH_MODE,
5051 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5052 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5053 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5054 mTouchModePerDisplay.count(displayId) == 0
5055 ? "not set"
5056 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5057
Antonio Kantek15beb512022-06-13 22:35:41 +00005058 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5059 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005060 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005061 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005062 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005063 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5064 !recentWindowsAreOwnedByLocked(pid, uid)) {
5065 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5066 "window nor none of the previously interacted window",
5067 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005068 return false;
5069 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005070 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005071 mTouchModePerDisplay[displayId] = inTouchMode;
5072 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5073 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005074 needWake = enqueueInboundEventLocked(std::move(entry));
5075 } // release lock
5076
5077 if (needWake) {
5078 mLooper->wake();
5079 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005080 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005081}
5082
Antonio Kantek48710e42022-03-24 14:19:30 -07005083bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5084 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5085 if (focusedToken == nullptr) {
5086 return false;
5087 }
5088 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5089 return isWindowOwnedBy(windowHandle, pid, uid);
5090}
5091
5092bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5093 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5094 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5095 const sp<WindowInfoHandle> windowHandle =
5096 getWindowHandleLocked(connectionToken);
5097 return isWindowOwnedBy(windowHandle, pid, uid);
5098 }) != mInteractionConnectionTokens.end();
5099}
5100
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005101void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5102 if (opacity < 0 || opacity > 1) {
5103 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5104 return;
5105 }
5106
5107 std::scoped_lock lock(mLock);
5108 mMaximumObscuringOpacityForTouch = opacity;
5109}
5110
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005111std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5112InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005113 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5114 for (TouchedWindow& w : state.windows) {
5115 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005116 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005117 }
5118 }
5119 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005120 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005121}
5122
arthurhungb89ccb02020-12-30 16:19:01 +08005123bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5124 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005125 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005126 if (DEBUG_FOCUS) {
5127 ALOGD("Trivial transfer to same window.");
5128 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005129 return true;
5130 }
5131
Michael Wrightd02c5b62014-02-10 15:10:22 -08005132 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005133 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005134
Arthur Hungabbb9d82021-09-01 14:52:30 +00005135 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005136 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005137 if (state == nullptr || touchedWindow == nullptr) {
5138 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005139 return false;
5140 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005141
Arthur Hungabbb9d82021-09-01 14:52:30 +00005142 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5143 if (toWindowHandle == nullptr) {
5144 ALOGW("Cannot transfer focus because to window not found.");
5145 return false;
5146 }
5147
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005148 if (DEBUG_FOCUS) {
5149 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005150 touchedWindow->windowHandle->getName().c_str(),
5151 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005152 }
5153
Arthur Hungabbb9d82021-09-01 14:52:30 +00005154 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005155 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005156 BitSet32 pointerIds = touchedWindow->pointerIds;
5157 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005158
Arthur Hungabbb9d82021-09-01 14:52:30 +00005159 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005160 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005161 ftl::Flags<InputTarget::Flags> newTargetFlags =
5162 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005163 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005164 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005165 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005166 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005167
Arthur Hungabbb9d82021-09-01 14:52:30 +00005168 // Store the dragging window.
5169 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005170 if (pointerIds.count() != 1) {
5171 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5172 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005173 return false;
5174 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005175 // Track the pointer id for drag window and generate the drag state.
5176 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005177 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005178 }
5179
Arthur Hungabbb9d82021-09-01 14:52:30 +00005180 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005181 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5182 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005183 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005184 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005185 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005186 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005187 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005188 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005189 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005190 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005191 } // release lock
5192
5193 // Wake up poll loop since it may need to make new input dispatching choices.
5194 mLooper->wake();
5195 return true;
5196}
5197
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005198/**
5199 * Get the touched foreground window on the given display.
5200 * Return null if there are no windows touched on that display, or if more than one foreground
5201 * window is being touched.
5202 */
5203sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5204 auto stateIt = mTouchStatesByDisplay.find(displayId);
5205 if (stateIt == mTouchStatesByDisplay.end()) {
5206 ALOGI("No touch state on display %" PRId32, displayId);
5207 return nullptr;
5208 }
5209
5210 const TouchState& state = stateIt->second;
5211 sp<WindowInfoHandle> touchedForegroundWindow;
5212 // If multiple foreground windows are touched, return nullptr
5213 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005214 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005215 if (touchedForegroundWindow != nullptr) {
5216 ALOGI("Two or more foreground windows: %s and %s",
5217 touchedForegroundWindow->getName().c_str(),
5218 window.windowHandle->getName().c_str());
5219 return nullptr;
5220 }
5221 touchedForegroundWindow = window.windowHandle;
5222 }
5223 }
5224 return touchedForegroundWindow;
5225}
5226
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005227// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005228bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005229 sp<IBinder> fromToken;
5230 { // acquire lock
5231 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005232 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005233 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005234 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5235 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005236 return false;
5237 }
5238
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005239 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5240 if (from == nullptr) {
5241 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5242 return false;
5243 }
5244
5245 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005246 } // release lock
5247
5248 return transferTouchFocus(fromToken, destChannelToken);
5249}
5250
Michael Wrightd02c5b62014-02-10 15:10:22 -08005251void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005252 if (DEBUG_FOCUS) {
5253 ALOGD("Resetting and dropping all events (%s).", reason);
5254 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005255
Michael Wrightfb04fd52022-11-24 22:31:11 +00005256 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005257 synthesizeCancelationEventsForAllConnectionsLocked(options);
5258
5259 resetKeyRepeatLocked();
5260 releasePendingEventLocked();
5261 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005262 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005263
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005264 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005265 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005267 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005268}
5269
5270void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005271 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272 dumpDispatchStateLocked(dump);
5273
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005274 std::istringstream stream(dump);
5275 std::string line;
5276
5277 while (std::getline(stream, line, '\n')) {
5278 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005279 }
5280}
5281
Prabir Pradhan99987712020-11-10 18:43:05 -08005282std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5283 std::string dump;
5284
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005285 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5286 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005287
5288 std::string windowName = "None";
5289 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005290 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005291 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5292 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5293 : "token has capture without window";
5294 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005295 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005296
5297 return dump;
5298}
5299
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005300void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005301 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5302 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5303 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005304 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005305
Tiger Huang721e26f2018-07-24 22:26:19 +08005306 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5307 dump += StringPrintf(INDENT "FocusedApplications:\n");
5308 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5309 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005310 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005311 const std::chrono::duration timeout =
5312 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005313 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005314 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005315 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005317 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005318 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005319 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005320
Vishnu Nairc519ff72021-01-21 08:23:08 -08005321 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005322 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005324 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005325 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005326 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005327 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5328 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005329 }
5330 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005331 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005332 }
5333
arthurhung6d4bed92021-03-17 11:59:33 +08005334 if (mDragState) {
5335 dump += StringPrintf(INDENT "DragState:\n");
5336 mDragState->dump(dump, INDENT2);
5337 }
5338
Arthur Hungb92218b2018-08-14 12:00:21 +08005339 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005340 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5341 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5342 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5343 const auto& displayInfo = it->second;
5344 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5345 displayInfo.logicalHeight);
5346 displayInfo.transform.dump(dump, "transform", INDENT4);
5347 } else {
5348 dump += INDENT2 "No DisplayInfo found!\n";
5349 }
5350
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005351 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005352 dump += INDENT2 "Windows:\n";
5353 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005354 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5355 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005356
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005357 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005358 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005359 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005360 "applicationInfo.name=%s, "
5361 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005362 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005363 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005364 windowInfo->displayId,
5365 windowInfo->inputConfig.string().c_str(),
5366 windowInfo->alpha, windowInfo->frameLeft,
5367 windowInfo->frameTop, windowInfo->frameRight,
5368 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005369 windowInfo->applicationInfo.name.c_str(),
5370 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005371 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005372 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005373 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005374 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005375 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005376 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005377 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005378 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005379 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005380 }
5381 } else {
5382 dump += INDENT2 "Windows: <none>\n";
5383 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005384 }
5385 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005386 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005387 }
5388
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005389 if (!mGlobalMonitorsByDisplay.empty()) {
5390 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5391 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005392 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005393 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005394 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005395 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005396 }
5397
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005398 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005399
5400 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005401 if (!mRecentQueue.empty()) {
5402 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005403 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005404 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005405 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005406 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005407 }
5408 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005409 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410 }
5411
5412 // Dump event currently being dispatched.
5413 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005414 dump += INDENT "PendingEvent:\n";
5415 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005416 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005417 dump += StringPrintf(", age=%" PRId64 "ms\n",
5418 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005419 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005420 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005421 }
5422
5423 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005424 if (!mInboundQueue.empty()) {
5425 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005426 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005427 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005428 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005429 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005430 }
5431 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005432 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005433 }
5434
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005435 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005436 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005437 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005438 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005439 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005440 }
5441 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005442 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005443 }
5444
Prabir Pradhancef936d2021-07-21 16:17:52 +00005445 if (!mCommandQueue.empty()) {
5446 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5447 } else {
5448 dump += INDENT "CommandQueue: <empty>\n";
5449 }
5450
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005451 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005452 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005453 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005454 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005455 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005456 connection->inputChannel->getFd().get(),
5457 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005458 connection->getWindowName().c_str(),
5459 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005460 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005461
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005462 if (!connection->outboundQueue.empty()) {
5463 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5464 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005465 dump += dumpQueue(connection->outboundQueue, currentTime);
5466
Michael Wrightd02c5b62014-02-10 15:10:22 -08005467 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005468 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005469 }
5470
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005471 if (!connection->waitQueue.empty()) {
5472 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5473 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005474 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005475 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005476 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005477 }
5478 }
5479 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005480 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005481 }
5482
5483 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005484 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5485 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005486 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005487 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488 }
5489
Antonio Kantek15beb512022-06-13 22:35:41 +00005490 if (!mTouchModePerDisplay.empty()) {
5491 dump += INDENT "TouchModePerDisplay:\n";
5492 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5493 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5494 std::to_string(touchMode).c_str());
5495 }
5496 } else {
5497 dump += INDENT "TouchModePerDisplay: <none>\n";
5498 }
5499
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005500 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005501 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5502 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5503 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005504 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005505 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005506}
5507
Michael Wright3dd60e22019-03-27 22:06:44 +00005508void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5509 const size_t numMonitors = monitors.size();
5510 for (size_t i = 0; i < numMonitors; i++) {
5511 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005512 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005513 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5514 dump += "\n";
5515 }
5516}
5517
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005518class LooperEventCallback : public LooperCallback {
5519public:
5520 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5521 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5522
5523private:
5524 std::function<int(int events)> mCallback;
5525};
5526
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005527Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005528 if (DEBUG_CHANNEL_CREATION) {
5529 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5530 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005531
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005532 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005533 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005534 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005535
5536 if (result) {
5537 return base::Error(result) << "Failed to open input channel pair with name " << name;
5538 }
5539
Michael Wrightd02c5b62014-02-10 15:10:22 -08005540 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005541 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005542 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005543 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005544 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005545 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005546
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005547 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5548 ALOGE("Created a new connection, but the token %p is already known", token.get());
5549 }
5550 mConnectionsByToken.emplace(token, connection);
5551
5552 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5553 this, std::placeholders::_1, token);
5554
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005555 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5556 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005557 } // release lock
5558
5559 // Wake the looper because some connections have changed.
5560 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005561 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562}
5563
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005564Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005565 const std::string& name,
5566 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005567 std::shared_ptr<InputChannel> serverChannel;
5568 std::unique_ptr<InputChannel> clientChannel;
5569 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5570 if (result) {
5571 return base::Error(result) << "Failed to open input channel pair with name " << name;
5572 }
5573
Michael Wright3dd60e22019-03-27 22:06:44 +00005574 { // acquire lock
5575 std::scoped_lock _l(mLock);
5576
5577 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005578 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5579 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005580 }
5581
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005582 sp<Connection> connection =
5583 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005584 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005585 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005586
5587 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5588 ALOGE("Created a new connection, but the token %p is already known", token.get());
5589 }
5590 mConnectionsByToken.emplace(token, connection);
5591 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5592 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005593
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005594 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005595
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005596 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5597 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005598 }
Garfield Tan15601662020-09-22 15:32:38 -07005599
Michael Wright3dd60e22019-03-27 22:06:44 +00005600 // Wake the looper because some connections have changed.
5601 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005602 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005603}
5604
Garfield Tan15601662020-09-22 15:32:38 -07005605status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005606 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005607 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005608
Garfield Tan15601662020-09-22 15:32:38 -07005609 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005610 if (status) {
5611 return status;
5612 }
5613 } // release lock
5614
5615 // Wake the poll loop because removing the connection may have changed the current
5616 // synchronization state.
5617 mLooper->wake();
5618 return OK;
5619}
5620
Garfield Tan15601662020-09-22 15:32:38 -07005621status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5622 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005623 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005624 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005625 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005626 return BAD_VALUE;
5627 }
5628
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005629 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005630
Michael Wrightd02c5b62014-02-10 15:10:22 -08005631 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005632 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005633 }
5634
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005635 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005636
5637 nsecs_t currentTime = now();
5638 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5639
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005640 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005641 return OK;
5642}
5643
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005644void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005645 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5646 auto& [displayId, monitors] = *it;
5647 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5648 return monitor.inputChannel->getConnectionToken() == connectionToken;
5649 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005650
Michael Wright3dd60e22019-03-27 22:06:44 +00005651 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005652 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005653 } else {
5654 ++it;
5655 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005656 }
5657}
5658
Michael Wright3dd60e22019-03-27 22:06:44 +00005659status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005660 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005661 return pilferPointersLocked(token);
5662}
Michael Wright3dd60e22019-03-27 22:06:44 +00005663
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005664status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005665 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5666 if (!requestingChannel) {
5667 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5668 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005669 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005670
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005671 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07005672 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.isEmpty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005673 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5674 " Ignoring.");
5675 return BAD_VALUE;
5676 }
5677
5678 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005679 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005680 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005681 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005682 "input channel stole pointer stream");
5683 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005684 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005685 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005686 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005687 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005688 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005689 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005690 if (channel != nullptr && channel->getConnectionToken() != token) {
5691 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5692 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5693 canceledWindows += channel->getName();
5694 }
5695 }
5696 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5697 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5698 canceledWindows.c_str());
5699
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005700 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005701 // This only blocks relevant pointers to be sent to other windows
5702 window.isPilferingPointers = true;
5703
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005704 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005705 return OK;
5706}
5707
Prabir Pradhan99987712020-11-10 18:43:05 -08005708void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5709 { // acquire lock
5710 std::scoped_lock _l(mLock);
5711 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005712 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005713 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5714 windowHandle != nullptr ? windowHandle->getName().c_str()
5715 : "token without window");
5716 }
5717
Vishnu Nairc519ff72021-01-21 08:23:08 -08005718 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005719 if (focusedToken != windowToken) {
5720 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5721 enabled ? "enable" : "disable");
5722 return;
5723 }
5724
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005725 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005726 ALOGW("Ignoring request to %s Pointer Capture: "
5727 "window has %s requested pointer capture.",
5728 enabled ? "enable" : "disable", enabled ? "already" : "not");
5729 return;
5730 }
5731
Christine Franksb768bb42021-11-29 12:11:31 -08005732 if (enabled) {
5733 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5734 mIneligibleDisplaysForPointerCapture.end(),
5735 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5736 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5737 return;
5738 }
5739 }
5740
Prabir Pradhan99987712020-11-10 18:43:05 -08005741 setPointerCaptureLocked(enabled);
5742 } // release lock
5743
5744 // Wake the thread to process command entries.
5745 mLooper->wake();
5746}
5747
Christine Franksb768bb42021-11-29 12:11:31 -08005748void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5749 { // acquire lock
5750 std::scoped_lock _l(mLock);
5751 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5752 if (!isEligible) {
5753 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5754 }
5755 } // release lock
5756}
5757
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005758std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5759 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005760 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005761 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005762 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005763 }
5764 }
5765 }
5766 return std::nullopt;
5767}
5768
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005769sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005770 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005771 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005772 }
5773
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005774 for (const auto& [token, connection] : mConnectionsByToken) {
5775 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005776 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005777 }
5778 }
Robert Carr4e670e52018-08-15 13:26:12 -07005779
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005780 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005781}
5782
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005783std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5784 sp<Connection> connection = getConnectionLocked(connectionToken);
5785 if (connection == nullptr) {
5786 return "<nullptr>";
5787 }
5788 return connection->getInputChannelName();
5789}
5790
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005791void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005792 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005793 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005794}
5795
Prabir Pradhancef936d2021-07-21 16:17:52 +00005796void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5797 const sp<Connection>& connection, uint32_t seq,
5798 bool handled, nsecs_t consumeTime) {
5799 // Handle post-event policy actions.
5800 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5801 if (dispatchEntryIt == connection->waitQueue.end()) {
5802 return;
5803 }
5804 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5805 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5806 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5807 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5808 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5809 }
5810 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5811 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5812 connection->inputChannel->getConnectionToken(),
5813 dispatchEntry->deliveryTime, consumeTime, finishTime);
5814 }
5815
5816 bool restartEvent;
5817 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5818 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5819 restartEvent =
5820 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5821 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5822 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5823 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5824 handled);
5825 } else {
5826 restartEvent = false;
5827 }
5828
5829 // Dequeue the event and start the next cycle.
5830 // Because the lock might have been released, it is possible that the
5831 // contents of the wait queue to have been drained, so we need to double-check
5832 // a few things.
5833 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5834 if (dispatchEntryIt != connection->waitQueue.end()) {
5835 dispatchEntry = *dispatchEntryIt;
5836 connection->waitQueue.erase(dispatchEntryIt);
5837 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5838 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5839 if (!connection->responsive) {
5840 connection->responsive = isConnectionResponsive(*connection);
5841 if (connection->responsive) {
5842 // The connection was unresponsive, and now it's responsive.
5843 processConnectionResponsiveLocked(*connection);
5844 }
5845 }
5846 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005847 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005848 connection->outboundQueue.push_front(dispatchEntry);
5849 traceOutboundQueueLength(*connection);
5850 } else {
5851 releaseDispatchEntry(dispatchEntry);
5852 }
5853 }
5854
5855 // Start the next dispatch cycle for this connection.
5856 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005857}
5858
Prabir Pradhancef936d2021-07-21 16:17:52 +00005859void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5860 const sp<IBinder>& newToken) {
5861 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5862 scoped_unlock unlock(mLock);
5863 mPolicy->notifyFocusChanged(oldToken, newToken);
5864 };
5865 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005866}
5867
Prabir Pradhancef936d2021-07-21 16:17:52 +00005868void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5869 auto command = [this, token, x, y]() REQUIRES(mLock) {
5870 scoped_unlock unlock(mLock);
5871 mPolicy->notifyDropWindow(token, x, y);
5872 };
5873 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005874}
5875
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005876void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5877 if (connection == nullptr) {
5878 LOG_ALWAYS_FATAL("Caller must check for nullness");
5879 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005880 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5881 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005882 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005883 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005884 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005885 return;
5886 }
5887 /**
5888 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5889 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5890 * has changed. This could cause newer entries to time out before the already dispatched
5891 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5892 * processes the events linearly. So providing information about the oldest entry seems to be
5893 * most useful.
5894 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005895 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005896 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5897 std::string reason =
5898 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005899 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005900 ns2ms(currentWait),
5901 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005902 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005903 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005904
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005905 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5906
5907 // Stop waking up for events on this connection, it is already unresponsive
5908 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005909}
5910
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005911void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5912 std::string reason =
5913 StringPrintf("%s does not have a focused window", application->getName().c_str());
5914 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005915
Prabir Pradhancef936d2021-07-21 16:17:52 +00005916 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5917 scoped_unlock unlock(mLock);
5918 mPolicy->notifyNoFocusedWindowAnr(application);
5919 };
5920 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005921}
5922
chaviw98318de2021-05-19 16:45:23 -05005923void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005924 const std::string& reason) {
5925 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5926 updateLastAnrStateLocked(windowLabel, reason);
5927}
5928
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005929void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5930 const std::string& reason) {
5931 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005932 updateLastAnrStateLocked(windowLabel, reason);
5933}
5934
5935void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5936 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005937 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005938 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005939 struct tm tm;
5940 localtime_r(&t, &tm);
5941 char timestr[64];
5942 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005943 mLastAnrState.clear();
5944 mLastAnrState += INDENT "ANR:\n";
5945 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005946 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5947 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005948 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005949}
5950
Prabir Pradhancef936d2021-07-21 16:17:52 +00005951void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5952 KeyEntry& entry) {
5953 const KeyEvent event = createKeyEvent(entry);
5954 nsecs_t delay = 0;
5955 { // release lock
5956 scoped_unlock unlock(mLock);
5957 android::base::Timer t;
5958 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5959 entry.policyFlags);
5960 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5961 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5962 std::to_string(t.duration().count()).c_str());
5963 }
5964 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005965
5966 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00005967 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005968 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00005969 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005970 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00005971 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005972 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005973 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005974}
5975
Prabir Pradhancef936d2021-07-21 16:17:52 +00005976void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005977 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005978 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005979 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005980 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005981 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005982 };
5983 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005984}
5985
Prabir Pradhanedd96402022-02-15 01:46:16 -08005986void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5987 std::optional<int32_t> pid) {
5988 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005989 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005990 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005991 };
5992 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005993}
5994
5995/**
5996 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5997 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5998 * command entry to the command queue.
5999 */
6000void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6001 std::string reason) {
6002 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006003 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006004 if (connection.monitor) {
6005 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6006 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006007 pid = findMonitorPidByTokenLocked(connectionToken);
6008 } else {
6009 // The connection is a window
6010 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6011 reason.c_str());
6012 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6013 if (handle != nullptr) {
6014 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006015 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006016 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006017 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006018}
6019
6020/**
6021 * Tell the policy that a connection has become responsive so that it can stop ANR.
6022 */
6023void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6024 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006025 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006026 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006027 pid = findMonitorPidByTokenLocked(connectionToken);
6028 } else {
6029 // The connection is a window
6030 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6031 if (handle != nullptr) {
6032 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006033 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006034 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006035 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006036}
6037
Prabir Pradhancef936d2021-07-21 16:17:52 +00006038bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006039 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006040 KeyEntry& keyEntry, bool handled) {
6041 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006042 if (!handled) {
6043 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006044 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006045 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006046 return false;
6047 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006048
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006049 // Get the fallback key state.
6050 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006051 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006052 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006053 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006054 connection->inputState.removeFallbackKey(originalKeyCode);
6055 }
6056
6057 if (handled || !dispatchEntry->hasForegroundTarget()) {
6058 // If the application handles the original key for which we previously
6059 // generated a fallback or if the window is not a foreground window,
6060 // then cancel the associated fallback key, if any.
6061 if (fallbackKeyCode != -1) {
6062 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006063 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6064 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6065 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6066 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6067 keyEntry.policyFlags);
6068 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006069 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006070 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006071
6072 mLock.unlock();
6073
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006074 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006075 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006076
6077 mLock.lock();
6078
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006079 // Cancel the fallback key.
6080 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006081 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006082 "application handled the original non-fallback key "
6083 "or is no longer a foreground target, "
6084 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006085 options.keyCode = fallbackKeyCode;
6086 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006087 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006088 connection->inputState.removeFallbackKey(originalKeyCode);
6089 }
6090 } else {
6091 // If the application did not handle a non-fallback key, first check
6092 // that we are in a good state to perform unhandled key event processing
6093 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006094 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006095 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006096 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6097 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6098 "since this is not an initial down. "
6099 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6100 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6101 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006102 return false;
6103 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006104
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006105 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006106 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6107 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6108 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6109 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6110 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006111 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006112
6113 mLock.unlock();
6114
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006115 bool fallback =
6116 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006117 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006118
6119 mLock.lock();
6120
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006121 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006122 connection->inputState.removeFallbackKey(originalKeyCode);
6123 return false;
6124 }
6125
6126 // Latch the fallback keycode for this key on an initial down.
6127 // The fallback keycode cannot change at any other point in the lifecycle.
6128 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006129 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006130 fallbackKeyCode = event.getKeyCode();
6131 } else {
6132 fallbackKeyCode = AKEYCODE_UNKNOWN;
6133 }
6134 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6135 }
6136
6137 ALOG_ASSERT(fallbackKeyCode != -1);
6138
6139 // Cancel the fallback key if the policy decides not to send it anymore.
6140 // We will continue to dispatch the key to the policy but we will no
6141 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006142 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6143 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006144 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6145 if (fallback) {
6146 ALOGD("Unhandled key event: Policy requested to send key %d"
6147 "as a fallback for %d, but on the DOWN it had requested "
6148 "to send %d instead. Fallback canceled.",
6149 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6150 } else {
6151 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6152 "but on the DOWN it had requested to send %d. "
6153 "Fallback canceled.",
6154 originalKeyCode, fallbackKeyCode);
6155 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006156 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006157
Michael Wrightfb04fd52022-11-24 22:31:11 +00006158 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006159 "canceling fallback, policy no longer desires it");
6160 options.keyCode = fallbackKeyCode;
6161 synthesizeCancelationEventsForConnectionLocked(connection, options);
6162
6163 fallback = false;
6164 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006165 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006166 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006167 }
6168 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006169
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006170 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6171 {
6172 std::string msg;
6173 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6174 connection->inputState.getFallbackKeys();
6175 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6176 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6177 }
6178 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6179 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006180 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006181 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006182
6183 if (fallback) {
6184 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006185 keyEntry.eventTime = event.getEventTime();
6186 keyEntry.deviceId = event.getDeviceId();
6187 keyEntry.source = event.getSource();
6188 keyEntry.displayId = event.getDisplayId();
6189 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6190 keyEntry.keyCode = fallbackKeyCode;
6191 keyEntry.scanCode = event.getScanCode();
6192 keyEntry.metaState = event.getMetaState();
6193 keyEntry.repeatCount = event.getRepeatCount();
6194 keyEntry.downTime = event.getDownTime();
6195 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006196
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006197 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6198 ALOGD("Unhandled key event: Dispatching fallback key. "
6199 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6200 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6201 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006202 return true; // restart the event
6203 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006204 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6205 ALOGD("Unhandled key event: No fallback key.");
6206 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006207
6208 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006209 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006210 }
6211 }
6212 return false;
6213}
6214
Prabir Pradhancef936d2021-07-21 16:17:52 +00006215bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006216 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006217 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006218 return false;
6219}
6220
Michael Wrightd02c5b62014-02-10 15:10:22 -08006221void InputDispatcher::traceInboundQueueLengthLocked() {
6222 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006223 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006224 }
6225}
6226
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006227void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006228 if (ATRACE_ENABLED()) {
6229 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006230 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6231 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006232 }
6233}
6234
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006235void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006236 if (ATRACE_ENABLED()) {
6237 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006238 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6239 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006240 }
6241}
6242
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006243void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006244 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006245
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006246 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006247 dumpDispatchStateLocked(dump);
6248
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006249 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006250 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006251 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006252 }
6253}
6254
6255void InputDispatcher::monitor() {
6256 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006257 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006258 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006259 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006260}
6261
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006262/**
6263 * Wake up the dispatcher and wait until it processes all events and commands.
6264 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6265 * this method can be safely called from any thread, as long as you've ensured that
6266 * the work you are interested in completing has already been queued.
6267 */
6268bool InputDispatcher::waitForIdle() {
6269 /**
6270 * Timeout should represent the longest possible time that a device might spend processing
6271 * events and commands.
6272 */
6273 constexpr std::chrono::duration TIMEOUT = 100ms;
6274 std::unique_lock lock(mLock);
6275 mLooper->wake();
6276 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6277 return result == std::cv_status::no_timeout;
6278}
6279
Vishnu Naire798b472020-07-23 13:52:21 -07006280/**
6281 * Sets focus to the window identified by the token. This must be called
6282 * after updating any input window handles.
6283 *
6284 * Params:
6285 * request.token - input channel token used to identify the window that should gain focus.
6286 * request.focusedToken - the token that the caller expects currently to be focused. If the
6287 * specified token does not match the currently focused window, this request will be dropped.
6288 * If the specified focused token matches the currently focused window, the call will succeed.
6289 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6290 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6291 * when requesting the focus change. This determines which request gets
6292 * precedence if there is a focus change request from another source such as pointer down.
6293 */
Vishnu Nair958da932020-08-21 17:12:37 -07006294void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6295 { // acquire lock
6296 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006297 std::optional<FocusResolver::FocusChanges> changes =
6298 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6299 if (changes) {
6300 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006301 }
6302 } // release lock
6303 // Wake up poll loop since it may need to make new input dispatching choices.
6304 mLooper->wake();
6305}
6306
Vishnu Nairc519ff72021-01-21 08:23:08 -08006307void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6308 if (changes.oldFocus) {
6309 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006310 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006311 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006312 "focus left window");
6313 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006314 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006315 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006316 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006317 if (changes.newFocus) {
6318 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006319 }
6320
Prabir Pradhan99987712020-11-10 18:43:05 -08006321 // If a window has pointer capture, then it must have focus. We need to ensure that this
6322 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6323 // If the window loses focus before it loses pointer capture, then the window can be in a state
6324 // where it has pointer capture but not focus, violating the contract. Therefore we must
6325 // dispatch the pointer capture event before the focus event. Since focus events are added to
6326 // the front of the queue (above), we add the pointer capture event to the front of the queue
6327 // after the focus events are added. This ensures the pointer capture event ends up at the
6328 // front.
6329 disablePointerCaptureForcedLocked();
6330
Vishnu Nairc519ff72021-01-21 08:23:08 -08006331 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006332 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006333 }
6334}
Vishnu Nair958da932020-08-21 17:12:37 -07006335
Prabir Pradhan99987712020-11-10 18:43:05 -08006336void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006337 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006338 return;
6339 }
6340
6341 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6342
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006343 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006344 setPointerCaptureLocked(false);
6345 }
6346
6347 if (!mWindowTokenWithPointerCapture) {
6348 // No need to send capture changes because no window has capture.
6349 return;
6350 }
6351
6352 if (mPendingEvent != nullptr) {
6353 // Move the pending event to the front of the queue. This will give the chance
6354 // for the pending event to be dropped if it is a captured event.
6355 mInboundQueue.push_front(mPendingEvent);
6356 mPendingEvent = nullptr;
6357 }
6358
6359 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006360 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006361 mInboundQueue.push_front(std::move(entry));
6362}
6363
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006364void InputDispatcher::setPointerCaptureLocked(bool enable) {
6365 mCurrentPointerCaptureRequest.enable = enable;
6366 mCurrentPointerCaptureRequest.seq++;
6367 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006368 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006369 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006370 };
6371 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006372}
6373
Vishnu Nair599f1412021-06-21 10:39:58 -07006374void InputDispatcher::displayRemoved(int32_t displayId) {
6375 { // acquire lock
6376 std::scoped_lock _l(mLock);
6377 // Set an empty list to remove all handles from the specific display.
6378 setInputWindowsLocked(/* window handles */ {}, displayId);
6379 setFocusedApplicationLocked(displayId, nullptr);
6380 // Call focus resolver to clean up stale requests. This must be called after input windows
6381 // have been removed for the removed display.
6382 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006383 // Reset pointer capture eligibility, regardless of previous state.
6384 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006385 // Remove the associated touch mode state.
6386 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006387 } // release lock
6388
6389 // Wake up poll loop since it may need to make new input dispatching choices.
6390 mLooper->wake();
6391}
6392
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006393void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6394 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006395 // The listener sends the windows as a flattened array. Separate the windows by display for
6396 // more convenient parsing.
6397 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006398 for (const auto& info : windowInfos) {
6399 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006400 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006401 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006402
6403 { // acquire lock
6404 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006405
6406 // Ensure that we have an entry created for all existing displays so that if a displayId has
6407 // no windows, we can tell that the windows were removed from the display.
6408 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6409 handlesPerDisplay[displayId];
6410 }
6411
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006412 mDisplayInfos.clear();
6413 for (const auto& displayInfo : displayInfos) {
6414 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6415 }
6416
6417 for (const auto& [displayId, handles] : handlesPerDisplay) {
6418 setInputWindowsLocked(handles, displayId);
6419 }
6420 }
6421 // Wake up poll loop since it may need to make new input dispatching choices.
6422 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006423}
6424
Vishnu Nair062a8672021-09-03 16:07:44 -07006425bool InputDispatcher::shouldDropInput(
6426 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006427 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6428 (windowHandle->getInfo()->inputConfig.test(
6429 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006430 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006431 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6432 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006433 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006434 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006435 windowHandle->getInfo()->displayId);
6436 return true;
6437 }
6438 return false;
6439}
6440
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006441void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6442 const std::vector<gui::WindowInfo>& windowInfos,
6443 const std::vector<DisplayInfo>& displayInfos) {
6444 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6445}
6446
Arthur Hungdfd528e2021-12-08 13:23:04 +00006447void InputDispatcher::cancelCurrentTouch() {
6448 {
6449 std::scoped_lock _l(mLock);
6450 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006451 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006452 "cancel current touch");
6453 synthesizeCancelationEventsForAllConnectionsLocked(options);
6454
6455 mTouchStatesByDisplay.clear();
6456 mLastHoverWindowHandle.clear();
6457 }
6458 // Wake up poll loop since there might be work to do.
6459 mLooper->wake();
6460}
6461
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006462void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6463 std::scoped_lock _l(mLock);
6464 mMonitorDispatchingTimeout = timeout;
6465}
6466
Garfield Tane84e6f92019-08-29 17:28:41 -07006467} // namespace android::inputdispatcher