blob: dc9f02ad5ded67647df31ad275fdb7a8ba0ecdd4 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Siarhei Vishniakoud010b012023-01-18 15:00:53 -080023#include <android-base/logging.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080024#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080025#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050026#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070027#include <binder/Binder.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080028#include <ftl/enum.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070029#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050030#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070031#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080032#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080033#include <input/PrintTools.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070034#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010035#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070036#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080037
Michael Wright44753b12020-07-08 13:48:11 +010038#include <cerrno>
39#include <cinttypes>
40#include <climits>
41#include <cstddef>
42#include <ctime>
43#include <queue>
44#include <sstream>
45
46#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000047#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070048#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010049
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#define INDENT " "
51#define INDENT2 " "
52#define INDENT3 " "
53#define INDENT4 " "
54
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080055using namespace android::ftl::flag_operators;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080056using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000057using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080058using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070059using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050060using android::gui::FocusRequest;
61using android::gui::TouchOcclusionMode;
62using android::gui::WindowInfo;
63using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080064using android::os::InputEventInjectionResult;
65using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080066
Garfield Tane84e6f92019-08-29 17:28:41 -070067namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080068
Prabir Pradhancef936d2021-07-21 16:17:52 +000069namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000070// Temporarily releases a held mutex for the lifetime of the instance.
71// Named to match std::scoped_lock
72class scoped_unlock {
73public:
74 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
75 ~scoped_unlock() { mMutex.lock(); }
76
77private:
78 std::mutex& mMutex;
79};
80
Michael Wrightd02c5b62014-02-10 15:10:22 -080081// Default input dispatching timeout if there is no focused application or paused window
82// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080083const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
84 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
85 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080086
87// Amount of time to allow for all pending events to be processed when an app switch
88// key is on the way. This is used to preempt input dispatch and drop input events
89// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000090constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080092const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080093
Michael Wrightd02c5b62014-02-10 15:10:22 -080094// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000095constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
96
97// Log a warning when an interception call takes longer than this to process.
98constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700100// Additional key latency in case a connection is still processing some motion events.
101// This will help with the case when a user touched a button that opens a new window,
102// and gives us the chance to dispatch the key to this new window.
103constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
104
Michael Wrightd02c5b62014-02-10 15:10:22 -0800105// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000106constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
107
Antonio Kantekea47acb2021-12-23 12:41:25 -0800108// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000109constexpr int LOGTAG_INPUT_INTERACTION = 62000;
110constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000111constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000112
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000113inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800114 return systemTime(SYSTEM_TIME_MONOTONIC);
115}
116
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000117inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800118 return value ? "true" : "false";
119}
120
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000121inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000122 if (binder == nullptr) {
123 return "<null>";
124 }
125 return StringPrintf("%p", binder.get());
126}
127
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000128inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700129 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
130 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800131}
132
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000133bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800134 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700135 case AKEY_EVENT_ACTION_DOWN:
136 case AKEY_EVENT_ACTION_UP:
137 return true;
138 default:
139 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800140 }
141}
142
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000143bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700144 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800145 ALOGE("Key event has invalid action code 0x%x", action);
146 return false;
147 }
148 return true;
149}
150
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000151bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800152 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700153 case AMOTION_EVENT_ACTION_DOWN:
154 case AMOTION_EVENT_ACTION_UP:
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800155 return pointerCount == 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700156 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700157 case AMOTION_EVENT_ACTION_HOVER_ENTER:
158 case AMOTION_EVENT_ACTION_HOVER_MOVE:
159 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800160 return pointerCount >= 1;
161 case AMOTION_EVENT_ACTION_CANCEL:
162 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700163 case AMOTION_EVENT_ACTION_SCROLL:
164 return true;
165 case AMOTION_EVENT_ACTION_POINTER_DOWN:
166 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800167 const int32_t index = MotionEvent::getActionIndex(action);
168 return index >= 0 && index < pointerCount && pointerCount > 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700169 }
170 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
171 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
172 return actionButton != 0;
173 default:
174 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 }
176}
177
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000178int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500179 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
180}
181
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000182bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
183 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700184 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 ALOGE("Motion event has invalid action code 0x%x", action);
186 return false;
187 }
188 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800189 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %zu.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700190 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 return false;
192 }
193 BitSet32 pointerIdBits;
194 for (size_t i = 0; i < pointerCount; i++) {
195 int32_t id = pointerProperties[i].id;
196 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700197 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
198 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800199 return false;
200 }
201 if (pointerIdBits.hasBit(id)) {
202 ALOGE("Motion event has duplicate pointer id %d", id);
203 return false;
204 }
205 pointerIdBits.markBit(id);
206 }
207 return true;
208}
209
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000210std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000212 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800213 }
214
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000215 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 bool first = true;
217 Region::const_iterator cur = region.begin();
218 Region::const_iterator const tail = region.end();
219 while (cur != tail) {
220 if (first) {
221 first = false;
222 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800223 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800224 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800225 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226 cur++;
227 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000228 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800229}
230
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000231std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500232 constexpr size_t maxEntries = 50; // max events to print
233 constexpr size_t skipBegin = maxEntries / 2;
234 const size_t skipEnd = queue.size() - maxEntries / 2;
235 // skip from maxEntries / 2 ... size() - maxEntries/2
236 // only print from 0 .. skipBegin and then from skipEnd .. size()
237
238 std::string dump;
239 for (size_t i = 0; i < queue.size(); i++) {
240 const DispatchEntry& entry = *queue[i];
241 if (i >= skipBegin && i < skipEnd) {
242 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
243 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
244 continue;
245 }
246 dump.append(INDENT4);
247 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800248 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
249 "ms",
250 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500251 ns2ms(currentTime - entry.eventEntry->eventTime));
252 if (entry.deliveryTime != 0) {
253 // This entry was delivered, so add information on how long we've been waiting
254 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
255 }
256 dump.append("\n");
257 }
258 return dump;
259}
260
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700261/**
262 * Find the entry in std::unordered_map by key, and return it.
263 * If the entry is not found, return a default constructed entry.
264 *
265 * Useful when the entries are vectors, since an empty vector will be returned
266 * if the entry is not found.
267 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
268 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700269template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000270V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700271 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700272 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800273}
274
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000275bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700276 if (first == second) {
277 return true;
278 }
279
280 if (first == nullptr || second == nullptr) {
281 return false;
282 }
283
284 return first->getToken() == second->getToken();
285}
286
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000287bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000288 if (first == nullptr || second == nullptr) {
289 return false;
290 }
291 return first->applicationInfo.token != nullptr &&
292 first->applicationInfo.token == second->applicationInfo.token;
293}
294
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800295std::unique_ptr<DispatchEntry> createDispatchEntry(
296 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
297 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700298 if (inputTarget.useDefaultPointerTransform()) {
299 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700300 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700301 inputTarget.displayTransform,
302 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000303 }
304
305 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
306 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
307
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700308 std::vector<PointerCoords> pointerCoords;
309 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000310
311 // Use the first pointer information to normalize all other pointers. This could be any pointer
312 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700313 // uses the transform for the normalized pointer.
314 const ui::Transform& firstPointerTransform =
315 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
316 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000317
318 // Iterate through all pointers in the event to normalize against the first.
319 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
320 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
321 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700322 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000323
324 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700325 // First, apply the current pointer's transform to update the coordinates into
326 // window space.
327 pointerCoords[pointerIndex].transform(currTransform);
328 // Next, apply the inverse transform of the normalized coordinates so the
329 // current coordinates are transformed into the normalized coordinate space.
330 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000331 }
332
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700333 std::unique_ptr<MotionEntry> combinedMotionEntry =
334 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
335 motionEntry.deviceId, motionEntry.source,
336 motionEntry.displayId, motionEntry.policyFlags,
337 motionEntry.action, motionEntry.actionButton,
338 motionEntry.flags, motionEntry.metaState,
339 motionEntry.buttonState, motionEntry.classification,
340 motionEntry.edgeFlags, motionEntry.xPrecision,
341 motionEntry.yPrecision, motionEntry.xCursorPosition,
342 motionEntry.yCursorPosition, motionEntry.downTime,
343 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000344 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000345
346 if (motionEntry.injectionState) {
347 combinedMotionEntry->injectionState = motionEntry.injectionState;
348 combinedMotionEntry->injectionState->refCount += 1;
349 }
350
351 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700352 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700353 firstPointerTransform, inputTarget.displayTransform,
354 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000355 return dispatchEntry;
356}
357
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000358status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
359 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700360 std::unique_ptr<InputChannel> uniqueServerChannel;
361 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
362
363 serverChannel = std::move(uniqueServerChannel);
364 return result;
365}
366
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500367template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000368bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500369 if (lhs == nullptr && rhs == nullptr) {
370 return true;
371 }
372 if (lhs == nullptr || rhs == nullptr) {
373 return false;
374 }
375 return *lhs == *rhs;
376}
377
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000378KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000379 KeyEvent event;
380 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
381 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
382 entry.repeatCount, entry.downTime, entry.eventTime);
383 return event;
384}
385
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000386bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000387 // Do not keep track of gesture monitors. They receive every event and would disproportionately
388 // affect the statistics.
389 if (connection.monitor) {
390 return false;
391 }
392 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
393 if (!connection.responsive) {
394 return false;
395 }
396 return true;
397}
398
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000399bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000400 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
401 const int32_t& inputEventId = eventEntry.id;
402 if (inputEventId != dispatchEntry.resolvedEventId) {
403 // Event was transmuted
404 return false;
405 }
406 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
407 return false;
408 }
409 // Only track latency for events that originated from hardware
410 if (eventEntry.isSynthesized()) {
411 return false;
412 }
413 const EventEntry::Type& inputEventEntryType = eventEntry.type;
414 if (inputEventEntryType == EventEntry::Type::KEY) {
415 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
416 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
417 return false;
418 }
419 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
420 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
421 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
422 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
423 return false;
424 }
425 } else {
426 // Not a key or a motion
427 return false;
428 }
429 if (!shouldReportMetricsForConnection(connection)) {
430 return false;
431 }
432 return true;
433}
434
Prabir Pradhancef936d2021-07-21 16:17:52 +0000435/**
436 * Connection is responsive if it has no events in the waitQueue that are older than the
437 * current time.
438 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000439bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000440 const nsecs_t currentTime = now();
441 for (const DispatchEntry* entry : connection.waitQueue) {
442 if (entry->timeoutTime < currentTime) {
443 return false;
444 }
445 }
446 return true;
447}
448
Antonio Kantekf16f2832021-09-28 04:39:20 +0000449// Returns true if the event type passed as argument represents a user activity.
450bool isUserActivityEvent(const EventEntry& eventEntry) {
451 switch (eventEntry.type) {
452 case EventEntry::Type::FOCUS:
453 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
454 case EventEntry::Type::DRAG:
455 case EventEntry::Type::TOUCH_MODE_CHANGED:
456 case EventEntry::Type::SENSOR:
457 case EventEntry::Type::CONFIGURATION_CHANGED:
458 return false;
459 case EventEntry::Type::DEVICE_RESET:
460 case EventEntry::Type::KEY:
461 case EventEntry::Type::MOTION:
462 return true;
463 }
464}
465
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800466// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhand65552b2021-10-07 11:23:50 -0700467bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, int32_t x, int32_t y,
468 bool isStylus) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800469 const auto inputConfig = windowInfo.inputConfig;
470 if (windowInfo.displayId != displayId ||
471 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800472 return false;
473 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700474 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800475 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800476 return false;
477 }
Prabir Pradhan06349042022-02-04 09:19:17 -0800478 if (!windowInfo.touchableRegionContainsPoint(x, y)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800479 return false;
480 }
481 return true;
482}
483
Prabir Pradhand65552b2021-10-07 11:23:50 -0700484bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
485 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000486 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700487}
488
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800489// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000490// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
491// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
492// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800493// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000494bool canReceiveForegroundTouches(const WindowInfo& info) {
495 // A non-touchable window can still receive touch events (e.g. in the case of
496 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
497 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
498}
499
Antonio Kantek48710e42022-03-24 14:19:30 -0700500bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
501 if (windowHandle == nullptr) {
502 return false;
503 }
504 const WindowInfo* windowInfo = windowHandle->getInfo();
505 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
506 return true;
507 }
508 return false;
509}
510
Prabir Pradhan5735a322022-04-11 17:23:34 +0000511// Checks targeted injection using the window's owner's uid.
512// Returns an empty string if an entry can be sent to the given window, or an error message if the
513// entry is a targeted injection whose uid target doesn't match the window owner.
514std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
515 const EventEntry& entry) {
516 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
517 // The event was not injected, or the injected event does not target a window.
518 return {};
519 }
520 const int32_t uid = *entry.injectionState->targetUid;
521 if (window == nullptr) {
522 return StringPrintf("No valid window target for injection into uid %d.", uid);
523 }
524 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
525 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
526 "owned by uid %d.",
527 uid, window->getName().c_str(), window->getInfo()->ownerUid);
528 }
529 return {};
530}
531
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700532Point resolveTouchedPosition(const MotionEntry& entry) {
533 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
534 // Always dispatch mouse events to cursor position.
535 if (isFromMouse) {
536 return Point(static_cast<int32_t>(entry.xCursorPosition),
537 static_cast<int32_t>(entry.yCursorPosition));
538 }
539
540 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
541 return Point(static_cast<int32_t>(
542 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X)),
543 static_cast<int32_t>(
544 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)));
545}
546
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700547std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
548 if (eventEntry.type == EventEntry::Type::KEY) {
549 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
550 return keyEntry.downTime;
551 } else if (eventEntry.type == EventEntry::Type::MOTION) {
552 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
553 return motionEntry.downTime;
554 }
555 return std::nullopt;
556}
557
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000558/**
559 * Compare the old touch state to the new touch state, and generate the corresponding touched
560 * windows (== input targets).
561 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
562 * If the pointer just entered the new window, produce HOVER_ENTER.
563 * For pointers remaining in the window, produce HOVER_MOVE.
564 */
565std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
566 const TouchState& newTouchState,
567 const MotionEntry& entry) {
568 std::vector<TouchedWindow> out;
569 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
570 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
571 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
572 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
573 // Not a hover event - don't need to do anything
574 return out;
575 }
576
577 // We should consider all hovering pointers here. But for now, just use the first one
578 const int32_t pointerId = entry.pointerProperties[0].id;
579
580 std::set<sp<WindowInfoHandle>> oldWindows;
581 if (oldState != nullptr) {
582 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
583 }
584
585 std::set<sp<WindowInfoHandle>> newWindows =
586 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
587
588 // If the pointer is no longer in the new window set, send HOVER_EXIT.
589 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
590 if (newWindows.find(oldWindow) == newWindows.end()) {
591 TouchedWindow touchedWindow;
592 touchedWindow.windowHandle = oldWindow;
593 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
594 touchedWindow.pointerIds.markBit(pointerId);
595 out.push_back(touchedWindow);
596 }
597 }
598
599 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
600 TouchedWindow touchedWindow;
601 touchedWindow.windowHandle = newWindow;
602 if (oldWindows.find(newWindow) == oldWindows.end()) {
603 // Any windows that have this pointer now, and didn't have it before, should get
604 // HOVER_ENTER
605 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
606 } else {
607 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
608 LOG_ALWAYS_FATAL_IF(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE);
609 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
610 }
611 touchedWindow.pointerIds.markBit(pointerId);
612 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
613 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
614 }
615 out.push_back(touchedWindow);
616 }
617 return out;
618}
619
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800620template <typename T>
621std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
622 left.insert(left.end(), right.begin(), right.end());
623 return left;
624}
625
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000626} // namespace
627
Michael Wrightd02c5b62014-02-10 15:10:22 -0800628// --- InputDispatcher ---
629
Garfield Tan00f511d2019-06-12 16:55:40 -0700630InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800631 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
632
633InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
634 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700635 : mPolicy(policy),
636 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700637 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800638 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700639 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700640 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700641 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800642 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700643 mDispatchEnabled(false),
644 mDispatchFrozen(false),
645 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100646 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000647 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800648 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800649 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000650 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000651 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700652 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800653 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800654
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700655 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700656#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700657 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700658#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700659 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800660 policy->getDispatcherConfiguration(&mConfig);
661}
662
663InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000664 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800665
Prabir Pradhancef936d2021-07-21 16:17:52 +0000666 resetKeyRepeatLocked();
667 releasePendingEventLocked();
668 drainInboundQueueLocked();
669 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800670
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000671 while (!mConnectionsByToken.empty()) {
672 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000673 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
674 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800675 }
676}
677
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700678status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700679 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700680 return ALREADY_EXISTS;
681 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700682 mThread = std::make_unique<InputThread>(
683 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
684 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700685}
686
687status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700688 if (mThread && mThread->isCallingThread()) {
689 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700690 return INVALID_OPERATION;
691 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700692 mThread.reset();
693 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700694}
695
Michael Wrightd02c5b62014-02-10 15:10:22 -0800696void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700697 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800699 std::scoped_lock _l(mLock);
700 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800701
702 // Run a dispatch loop if there are no pending commands.
703 // The dispatch loop might enqueue commands to run afterwards.
704 if (!haveCommandsLocked()) {
705 dispatchOnceInnerLocked(&nextWakeupTime);
706 }
707
708 // Run all pending commands if there are any.
709 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000710 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700711 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800713
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700714 // If we are still waiting for ack on some events,
715 // we might have to wake up earlier to check if an app is anr'ing.
716 const nsecs_t nextAnrCheck = processAnrsLocked();
717 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
718
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800719 // We are about to enter an infinitely long sleep, because we have no commands or
720 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700721 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800722 mDispatcherEnteredIdle.notify_all();
723 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800724 } // release lock
725
726 // Wait for callback or timeout or wake. (make sure we round up, not down)
727 nsecs_t currentTime = now();
728 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
729 mLooper->pollOnce(timeoutMillis);
730}
731
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700732/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500733 * Raise ANR if there is no focused window.
734 * Before the ANR is raised, do a final state check:
735 * 1. The currently focused application must be the same one we are waiting for.
736 * 2. Ensure we still don't have a focused window.
737 */
738void InputDispatcher::processNoFocusedWindowAnrLocked() {
739 // Check if the application that we are waiting for is still focused.
740 std::shared_ptr<InputApplicationHandle> focusedApplication =
741 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
742 if (focusedApplication == nullptr ||
743 focusedApplication->getApplicationToken() !=
744 mAwaitedFocusedApplication->getApplicationToken()) {
745 // Unexpected because we should have reset the ANR timer when focused application changed
746 ALOGE("Waited for a focused window, but focused application has already changed to %s",
747 focusedApplication->getName().c_str());
748 return; // The focused application has changed.
749 }
750
chaviw98318de2021-05-19 16:45:23 -0500751 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500752 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
753 if (focusedWindowHandle != nullptr) {
754 return; // We now have a focused window. No need for ANR.
755 }
756 onAnrLocked(mAwaitedFocusedApplication);
757}
758
759/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700760 * Check if any of the connections' wait queues have events that are too old.
761 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
762 * Return the time at which we should wake up next.
763 */
764nsecs_t InputDispatcher::processAnrsLocked() {
765 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700766 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700767 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
768 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
769 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500770 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700771 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500772 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700773 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700774 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500775 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700776 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
777 }
778 }
779
780 // Check if any connection ANRs are due
781 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
782 if (currentTime < nextAnrCheck) { // most likely scenario
783 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
784 }
785
786 // If we reached here, we have an unresponsive connection.
787 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
788 if (connection == nullptr) {
789 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
790 return nextAnrCheck;
791 }
792 connection->responsive = false;
793 // Stop waking up for this unresponsive connection
794 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000795 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700796 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700797}
798
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800799std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
800 const sp<Connection>& connection) {
801 if (connection->monitor) {
802 return mMonitorDispatchingTimeout;
803 }
804 const sp<WindowInfoHandle> window =
805 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700806 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500807 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700808 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500809 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700810}
811
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
813 nsecs_t currentTime = now();
814
Jeff Browndc5992e2014-04-11 01:27:26 -0700815 // Reset the key repeat timer whenever normal dispatch is suspended while the
816 // device is in a non-interactive state. This is to ensure that we abort a key
817 // repeat if the device is just coming out of sleep.
818 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819 resetKeyRepeatLocked();
820 }
821
822 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
823 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100824 if (DEBUG_FOCUS) {
825 ALOGD("Dispatch frozen. Waiting some more.");
826 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 return;
828 }
829
830 // Optimize latency of app switches.
831 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
832 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
833 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
834 if (mAppSwitchDueTime < *nextWakeupTime) {
835 *nextWakeupTime = mAppSwitchDueTime;
836 }
837
838 // Ready to start a new event.
839 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700840 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700841 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800842 if (isAppSwitchDue) {
843 // The inbound queue is empty so the app switch key we were waiting
844 // for will never arrive. Stop waiting for it.
845 resetPendingAppSwitchLocked(false);
846 isAppSwitchDue = false;
847 }
848
849 // Synthesize a key repeat if appropriate.
850 if (mKeyRepeatState.lastKeyEntry) {
851 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
852 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
853 } else {
854 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
855 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
856 }
857 }
858 }
859
860 // Nothing to do if there is no pending event.
861 if (!mPendingEvent) {
862 return;
863 }
864 } else {
865 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700866 mPendingEvent = mInboundQueue.front();
867 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868 traceInboundQueueLengthLocked();
869 }
870
871 // Poke user activity for this event.
872 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700873 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 }
876
877 // Now we have an event to dispatch.
878 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700879 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700881 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700883 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700885 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886 }
887
888 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700889 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890 }
891
892 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700893 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700894 const ConfigurationChangedEntry& typedEntry =
895 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700896 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700897 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700898 break;
899 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700901 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700902 const DeviceResetEntry& typedEntry =
903 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700904 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700905 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700906 break;
907 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100909 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700910 std::shared_ptr<FocusEntry> typedEntry =
911 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100912 dispatchFocusLocked(currentTime, typedEntry);
913 done = true;
914 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
915 break;
916 }
917
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700918 case EventEntry::Type::TOUCH_MODE_CHANGED: {
919 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
920 dispatchTouchModeChangeLocked(currentTime, typedEntry);
921 done = true;
922 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
923 break;
924 }
925
Prabir Pradhan99987712020-11-10 18:43:05 -0800926 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
927 const auto typedEntry =
928 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
929 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
930 done = true;
931 break;
932 }
933
arthurhungb89ccb02020-12-30 16:19:01 +0800934 case EventEntry::Type::DRAG: {
935 std::shared_ptr<DragEntry> typedEntry =
936 std::static_pointer_cast<DragEntry>(mPendingEvent);
937 dispatchDragLocked(currentTime, typedEntry);
938 done = true;
939 break;
940 }
941
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700942 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700943 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700944 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700945 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700946 resetPendingAppSwitchLocked(true);
947 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700948 } else if (dropReason == DropReason::NOT_DROPPED) {
949 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700950 }
951 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700952 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700953 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700954 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700955 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
956 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700957 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700958 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700959 break;
960 }
961
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700962 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700963 std::shared_ptr<MotionEntry> motionEntry =
964 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700965 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
966 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700968 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700969 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700970 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700971 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
972 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700973 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700974 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700975 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800976 }
Chris Yef59a2f42020-10-16 12:55:26 -0700977
978 case EventEntry::Type::SENSOR: {
979 std::shared_ptr<SensorEntry> sensorEntry =
980 std::static_pointer_cast<SensorEntry>(mPendingEvent);
981 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
982 dropReason = DropReason::APP_SWITCH;
983 }
984 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
985 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
986 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
987 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
988 dropReason = DropReason::STALE;
989 }
990 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
991 done = true;
992 break;
993 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 }
995
996 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700997 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700998 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 }
Michael Wright3a981722015-06-10 15:26:13 +01001000 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001
1002 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001003 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004 }
1005}
1006
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001007bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1008 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1009}
1010
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001011/**
1012 * Return true if the events preceding this incoming motion event should be dropped
1013 * Return false otherwise (the default behaviour)
1014 */
1015bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001016 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001017 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001018
1019 // Optimize case where the current application is unresponsive and the user
1020 // decides to touch a window in a different application.
1021 // If the application takes too long to catch up then we drop all events preceding
1022 // the touch into the other window.
1023 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001024 const int32_t displayId = motionEntry.displayId;
1025 const auto [x, y] = resolveTouchedPosition(motionEntry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07001026 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001027
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001028 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001029 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001030 touchedWindowHandle->getApplicationToken() !=
1031 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001032 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001033 ALOGI("Pruning input queue because user touched a different application while waiting "
1034 "for %s",
1035 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001036 return true;
1037 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001038
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001039 // Alternatively, maybe there's a spy window that could handle this event.
1040 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1041 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1042 for (const auto& windowHandle : touchedSpies) {
1043 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001044 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001045 // This spy window could take more input. Drop all events preceding this
1046 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001047 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001048 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001049 mAwaitedFocusedApplication->getName().c_str());
1050 return true;
1051 }
1052 }
1053 }
1054
1055 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1056 // yet been processed by some connections, the dispatcher will wait for these motion
1057 // events to be processed before dispatching the key event. This is because these motion events
1058 // may cause a new window to be launched, which the user might expect to receive focus.
1059 // To prevent waiting forever for such events, just send the key to the currently focused window
1060 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1061 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1062 "just send the pending key event to the focused window.");
1063 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001064 }
1065 return false;
1066}
1067
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001068bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001069 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001070 mInboundQueue.push_back(std::move(newEntry));
1071 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072 traceInboundQueueLengthLocked();
1073
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001074 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001075 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001076 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1077 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078 // Optimize app switch latency.
1079 // If the application takes too long to catch up then we drop all events preceding
1080 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001081 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001082 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001083 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001084 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001085 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001086 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001087 if (DEBUG_APP_SWITCH) {
1088 ALOGD("App switch is pending!");
1089 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001090 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001091 mAppSwitchSawKeyDown = false;
1092 needWake = true;
1093 }
1094 }
1095 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001096
1097 // If a new up event comes in, and the pending event with same key code has been asked
1098 // to try again later because of the policy. We have to reset the intercept key wake up
1099 // time for it may have been handled in the policy and could be dropped.
1100 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1101 mPendingEvent->type == EventEntry::Type::KEY) {
1102 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1103 if (pendingKey.keyCode == keyEntry.keyCode &&
1104 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001105 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1106 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001107 pendingKey.interceptKeyWakeupTime = 0;
1108 needWake = true;
1109 }
1110 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001111 break;
1112 }
1113
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001114 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001115 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1116 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001117 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1118 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001119 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001121 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001123 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001124 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1125 break;
1126 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001127 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001128 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001129 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001130 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001131 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1132 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001133 // nothing to do
1134 break;
1135 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001136 }
1137
1138 return needWake;
1139}
1140
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001141void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001142 // Do not store sensor event in recent queue to avoid flooding the queue.
1143 if (entry->type != EventEntry::Type::SENSOR) {
1144 mRecentQueue.push_back(entry);
1145 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001146 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001147 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 }
1149}
1150
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001151std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
1152InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x, int32_t y, bool isStylus,
1153 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001155 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001156 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001157 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001158 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001159 continue;
1160 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001162 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001163 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001164 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001165 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001166
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001167 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1168 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
1169 BitSet32(0), /*firstDownTimeInTarget=*/std::nullopt,
1170 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171 }
1172 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001173 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174}
1175
Prabir Pradhand65552b2021-10-07 11:23:50 -07001176std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1177 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001178 // Traverse windows from front to back and gather the touched spy windows.
1179 std::vector<sp<WindowInfoHandle>> spyWindows;
1180 const auto& windowHandles = getWindowHandlesLocked(displayId);
1181 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1182 const WindowInfo& info = *windowHandle->getInfo();
1183
Prabir Pradhand65552b2021-10-07 11:23:50 -07001184 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001185 continue;
1186 }
1187 if (!info.isSpy()) {
1188 // The first touched non-spy window was found, so return the spy windows touched so far.
1189 return spyWindows;
1190 }
1191 spyWindows.push_back(windowHandle);
1192 }
1193 return spyWindows;
1194}
1195
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001196void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 const char* reason;
1198 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001199 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001200 if (DEBUG_INBOUND_EVENT_DETAILS) {
1201 ALOGD("Dropped event because policy consumed it.");
1202 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001203 reason = "inbound event was dropped because the policy consumed it";
1204 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001205 case DropReason::DISABLED:
1206 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001207 ALOGI("Dropped event because input dispatch is disabled.");
1208 }
1209 reason = "inbound event was dropped because input dispatch is disabled";
1210 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001211 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001212 ALOGI("Dropped event because of pending overdue app switch.");
1213 reason = "inbound event was dropped because of pending overdue app switch";
1214 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001215 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001216 ALOGI("Dropped event because the current application is not responding and the user "
1217 "has started interacting with a different application.");
1218 reason = "inbound event was dropped because the current application is not responding "
1219 "and the user has started interacting with a different application";
1220 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001221 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001222 ALOGI("Dropped event because it is stale.");
1223 reason = "inbound event was dropped because it is stale";
1224 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001225 case DropReason::NO_POINTER_CAPTURE:
1226 ALOGI("Dropped event because there is no window with Pointer Capture.");
1227 reason = "inbound event was dropped because there is no window with Pointer Capture";
1228 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001229 case DropReason::NOT_DROPPED: {
1230 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001231 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001232 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233 }
1234
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001235 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001236 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001237 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001239 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001241 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001242 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1243 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001244 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001245 synthesizeCancelationEventsForAllConnectionsLocked(options);
1246 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001247 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1248 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001249 synthesizeCancelationEventsForAllConnectionsLocked(options);
1250 }
1251 break;
1252 }
Chris Yef59a2f42020-10-16 12:55:26 -07001253 case EventEntry::Type::SENSOR: {
1254 break;
1255 }
arthurhungb89ccb02020-12-30 16:19:01 +08001256 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1257 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001258 break;
1259 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001260 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001261 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001262 case EventEntry::Type::CONFIGURATION_CHANGED:
1263 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001264 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001265 break;
1266 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267 }
1268}
1269
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001270static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001271 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1272 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273}
1274
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001275bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1276 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1277 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1278 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279}
1280
1281bool InputDispatcher::isAppSwitchPendingLocked() {
Colin Cross5b799302022-10-18 21:52:41 -07001282 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283}
1284
1285void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001286 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001287
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001288 if (DEBUG_APP_SWITCH) {
1289 if (handled) {
1290 ALOGD("App switch has arrived.");
1291 } else {
1292 ALOGD("App switch was abandoned.");
1293 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295}
1296
Michael Wrightd02c5b62014-02-10 15:10:22 -08001297bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001298 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299}
1300
Prabir Pradhancef936d2021-07-21 16:17:52 +00001301bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001302 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303 return false;
1304 }
1305
1306 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001307 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001308 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001309 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1310 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001311 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001312 return true;
1313}
1314
Prabir Pradhancef936d2021-07-21 16:17:52 +00001315void InputDispatcher::postCommandLocked(Command&& command) {
1316 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317}
1318
1319void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001320 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001321 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001322 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 releaseInboundEventLocked(entry);
1324 }
1325 traceInboundQueueLengthLocked();
1326}
1327
1328void InputDispatcher::releasePendingEventLocked() {
1329 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001331 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332 }
1333}
1334
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001335void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001336 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001337 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001338 if (DEBUG_DISPATCH_CYCLE) {
1339 ALOGD("Injected inbound event was dropped.");
1340 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001341 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001342 }
1343 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001344 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345 }
1346 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001347}
1348
1349void InputDispatcher::resetKeyRepeatLocked() {
1350 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001351 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352 }
1353}
1354
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001355std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1356 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001357
Michael Wright2e732952014-09-24 13:26:59 -07001358 uint32_t policyFlags = entry->policyFlags &
1359 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001360
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001361 std::shared_ptr<KeyEntry> newEntry =
1362 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1363 entry->source, entry->displayId, policyFlags, entry->action,
1364 entry->flags, entry->keyCode, entry->scanCode,
1365 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001367 newEntry->syntheticRepeat = true;
1368 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001370 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001371}
1372
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001373bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001374 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001375 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1376 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1377 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378
1379 // Reset key repeating in case a keyboard device was added or removed or something.
1380 resetKeyRepeatLocked();
1381
1382 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001383 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1384 scoped_unlock unlock(mLock);
1385 mPolicy->notifyConfigurationChanged(eventTime);
1386 };
1387 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388 return true;
1389}
1390
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001391bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1392 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001393 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1394 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1395 entry.deviceId);
1396 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397
liushenxiang42232912021-05-21 20:24:09 +08001398 // Reset key repeating in case a keyboard device was disabled or enabled.
1399 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1400 resetKeyRepeatLocked();
1401 }
1402
Michael Wrightfb04fd52022-11-24 22:31:11 +00001403 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001404 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405 synthesizeCancelationEventsForAllConnectionsLocked(options);
1406 return true;
1407}
1408
Vishnu Nairad321cd2020-08-20 16:40:21 -07001409void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001410 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001411 if (mPendingEvent != nullptr) {
1412 // Move the pending event to the front of the queue. This will give the chance
1413 // for the pending event to get dispatched to the newly focused window
1414 mInboundQueue.push_front(mPendingEvent);
1415 mPendingEvent = nullptr;
1416 }
1417
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001418 std::unique_ptr<FocusEntry> focusEntry =
1419 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1420 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001421
1422 // This event should go to the front of the queue, but behind all other focus events
1423 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001424 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001425 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001426 [](const std::shared_ptr<EventEntry>& event) {
1427 return event->type == EventEntry::Type::FOCUS;
1428 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001429
1430 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001431 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001432}
1433
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001434void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001435 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001436 if (channel == nullptr) {
1437 return; // Window has gone away
1438 }
1439 InputTarget target;
1440 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001441 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001442 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001443 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1444 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001445 std::string reason = std::string("reason=").append(entry->reason);
1446 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001447 dispatchEventLocked(currentTime, entry, {target});
1448}
1449
Prabir Pradhan99987712020-11-10 18:43:05 -08001450void InputDispatcher::dispatchPointerCaptureChangedLocked(
1451 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1452 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001453 dropReason = DropReason::NOT_DROPPED;
1454
Prabir Pradhan99987712020-11-10 18:43:05 -08001455 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001456 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001457
1458 if (entry->pointerCaptureRequest.enable) {
1459 // Enable Pointer Capture.
1460 if (haveWindowWithPointerCapture &&
1461 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001462 // This can happen if pointer capture is disabled and re-enabled before we notify the
1463 // app of the state change, so there is no need to notify the app.
1464 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1465 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001466 }
1467 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001468 // This can happen if a window requests capture and immediately releases capture.
1469 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001470 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001471 return;
1472 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001473 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1474 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1475 return;
1476 }
1477
Vishnu Nairc519ff72021-01-21 08:23:08 -08001478 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001479 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1480 mWindowTokenWithPointerCapture = token;
1481 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001482 // Disable Pointer Capture.
1483 // We do not check if the sequence number matches for requests to disable Pointer Capture
1484 // for two reasons:
1485 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1486 // to disable capture with the same sequence number: one generated by
1487 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1488 // Capture being disabled in InputReader.
1489 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1490 // actual Pointer Capture state that affects events being generated by input devices is
1491 // in InputReader.
1492 if (!haveWindowWithPointerCapture) {
1493 // Pointer capture was already forcefully disabled because of focus change.
1494 dropReason = DropReason::NOT_DROPPED;
1495 return;
1496 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001497 token = mWindowTokenWithPointerCapture;
1498 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001499 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001500 setPointerCaptureLocked(false);
1501 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001502 }
1503
1504 auto channel = getInputChannelLocked(token);
1505 if (channel == nullptr) {
1506 // Window has gone away, clean up Pointer Capture state.
1507 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001508 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001509 setPointerCaptureLocked(false);
1510 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001511 return;
1512 }
1513 InputTarget target;
1514 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001515 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001516 entry->dispatchInProgress = true;
1517 dispatchEventLocked(currentTime, entry, {target});
1518
1519 dropReason = DropReason::NOT_DROPPED;
1520}
1521
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001522void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1523 const std::shared_ptr<TouchModeEntry>& entry) {
1524 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001525 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001526 if (windowHandles.empty()) {
1527 return;
1528 }
1529 const std::vector<InputTarget> inputTargets =
1530 getInputTargetsFromWindowHandlesLocked(windowHandles);
1531 if (inputTargets.empty()) {
1532 return;
1533 }
1534 entry->dispatchInProgress = true;
1535 dispatchEventLocked(currentTime, entry, inputTargets);
1536}
1537
1538std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1539 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1540 std::vector<InputTarget> inputTargets;
1541 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001542 const sp<IBinder>& token = handle->getToken();
1543 if (token == nullptr) {
1544 continue;
1545 }
1546 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1547 if (channel == nullptr) {
1548 continue; // Window has gone away
1549 }
1550 InputTarget target;
1551 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001552 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001553 inputTargets.push_back(target);
1554 }
1555 return inputTargets;
1556}
1557
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001558bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001559 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001561 if (!entry->dispatchInProgress) {
1562 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1563 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1564 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1565 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001566 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 // We have seen two identical key downs in a row which indicates that the device
1568 // driver is automatically generating key repeats itself. We take note of the
1569 // repeat here, but we disable our own next key repeat timer since it is clear that
1570 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001571 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1572 // Make sure we don't get key down from a different device. If a different
1573 // device Id has same key pressed down, the new device Id will replace the
1574 // current one to hold the key repeat with repeat count reset.
1575 // In the future when got a KEY_UP on the device id, drop it and do not
1576 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1578 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001579 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580 } else {
1581 // Not a repeat. Save key down state in case we do see a repeat later.
1582 resetKeyRepeatLocked();
1583 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1584 }
1585 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001586 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1587 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001588 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001589 if (DEBUG_INBOUND_EVENT_DETAILS) {
1590 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1591 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001592 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001593 resetKeyRepeatLocked();
1594 }
1595
1596 if (entry->repeatCount == 1) {
1597 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1598 } else {
1599 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1600 }
1601
1602 entry->dispatchInProgress = true;
1603
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001604 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001605 }
1606
1607 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001608 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001609 if (currentTime < entry->interceptKeyWakeupTime) {
1610 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1611 *nextWakeupTime = entry->interceptKeyWakeupTime;
1612 }
1613 return false; // wait until next wakeup
1614 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001615 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001616 entry->interceptKeyWakeupTime = 0;
1617 }
1618
1619 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001620 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001622 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001623 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001624
1625 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1626 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1627 };
1628 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629 return false; // wait for the command to run
1630 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001631 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001633 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001634 if (*dropReason == DropReason::NOT_DROPPED) {
1635 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 }
1637 }
1638
1639 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001640 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001641 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001642 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1643 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001644 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 return true;
1646 }
1647
1648 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001649 InputEventInjectionResult injectionResult;
1650 sp<WindowInfoHandle> focusedWindow =
1651 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1652 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001653 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 return false;
1655 }
1656
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001657 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001658 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659 return true;
1660 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001661 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1662
1663 std::vector<InputTarget> inputTargets;
1664 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001665 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001666 BitSet32(0), getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001668 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001669 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670
1671 // Dispatch the key.
1672 dispatchEventLocked(currentTime, entry, inputTargets);
1673 return true;
1674}
1675
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001676void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001677 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1678 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1679 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1680 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1681 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1682 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1683 entry.metaState, entry.repeatCount, entry.downTime);
1684 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685}
1686
Prabir Pradhancef936d2021-07-21 16:17:52 +00001687void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1688 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001689 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001690 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1691 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1692 "source=0x%x, sensorType=%s",
1693 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001694 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001695 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001696 auto command = [this, entry]() REQUIRES(mLock) {
1697 scoped_unlock unlock(mLock);
1698
1699 if (entry->accuracyChanged) {
1700 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1701 }
1702 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1703 entry->hwTimestamp, entry->values);
1704 };
1705 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001706}
1707
1708bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001709 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1710 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001711 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001712 }
Chris Yef59a2f42020-10-16 12:55:26 -07001713 { // acquire lock
1714 std::scoped_lock _l(mLock);
1715
1716 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1717 std::shared_ptr<EventEntry> entry = *it;
1718 if (entry->type == EventEntry::Type::SENSOR) {
1719 it = mInboundQueue.erase(it);
1720 releaseInboundEventLocked(entry);
1721 }
1722 }
1723 }
1724 return true;
1725}
1726
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001727bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001728 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001729 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001731 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001732 entry->dispatchInProgress = true;
1733
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001734 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001735 }
1736
1737 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001738 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001739 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001740 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1741 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742 return true;
1743 }
1744
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001745 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746
1747 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001748 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749
1750 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001751 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752 if (isPointerEvent) {
1753 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001754
1755 if (mDragState &&
1756 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1757 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1758 pilferPointersLocked(mDragState->dragWindow->getToken());
1759 }
1760
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001761 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001762 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001763 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001764 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1765 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766 } else {
1767 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001768 sp<WindowInfoHandle> focusedWindow =
1769 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1770 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1771 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1772 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001773 InputTarget::Flags::FOREGROUND |
1774 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001775 BitSet32(0), getDownTime(*entry), inputTargets);
1776 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001778 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001779 return false;
1780 }
1781
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001782 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001783 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001784 return true;
1785 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001786 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001787 CancelationOptions::Mode mode(
1788 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1789 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001790 CancelationOptions options(mode, "input event injection failed");
1791 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792 return true;
1793 }
1794
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001795 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001796 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797
1798 // Dispatch the motion.
1799 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001800 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001801 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802 synthesizeCancelationEventsForAllConnectionsLocked(options);
1803 }
1804 dispatchEventLocked(currentTime, entry, inputTargets);
1805 return true;
1806}
1807
chaviw98318de2021-05-19 16:45:23 -05001808void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001809 bool isExiting, const int32_t rawX,
1810 const int32_t rawY) {
1811 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001812 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001813 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1814 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001815
1816 enqueueInboundEventLocked(std::move(dragEntry));
1817}
1818
1819void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1820 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1821 if (channel == nullptr) {
1822 return; // Window has gone away
1823 }
1824 InputTarget target;
1825 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001826 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001827 entry->dispatchInProgress = true;
1828 dispatchEventLocked(currentTime, entry, {target});
1829}
1830
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001831void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001832 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001833 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001834 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001835 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001836 "metaState=0x%x, buttonState=0x%x,"
1837 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001838 prefix, entry.eventTime, entry.deviceId,
1839 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1840 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1841 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1842 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001844 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1845 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1846 "x=%f, y=%f, pressure=%f, size=%f, "
1847 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1848 "orientation=%f",
1849 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1850 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1851 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1852 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1853 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1854 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1855 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1856 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1857 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1858 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1859 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861}
1862
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001863void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1864 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001865 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001866 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001867 if (DEBUG_DISPATCH_CYCLE) {
1868 ALOGD("dispatchEventToCurrentInputTargets");
1869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001871 updateInteractionTokensLocked(*eventEntry, inputTargets);
1872
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1874
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001875 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001877 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001878 sp<Connection> connection =
1879 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001880 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001881 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001883 if (DEBUG_FOCUS) {
1884 ALOGD("Dropping event delivery to target with channel '%s' because it "
1885 "is no longer registered with the input dispatcher.",
1886 inputTarget.inputChannel->getName().c_str());
1887 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 }
1889 }
1890}
1891
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001892void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1893 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1894 // If the policy decides to close the app, we will get a channel removal event via
1895 // unregisterInputChannel, and will clean up the connection that way. We are already not
1896 // sending new pointers to the connection when it blocked, but focused events will continue to
1897 // pile up.
1898 ALOGW("Canceling events for %s because it is unresponsive",
1899 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001900 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001901 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001902 "application not responding");
1903 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 }
1905}
1906
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001907void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001908 if (DEBUG_FOCUS) {
1909 ALOGD("Resetting ANR timeouts.");
1910 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911
1912 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001913 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001914 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915}
1916
Tiger Huang721e26f2018-07-24 22:26:19 +08001917/**
1918 * Get the display id that the given event should go to. If this event specifies a valid display id,
1919 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1920 * Focused display is the display that the user most recently interacted with.
1921 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001922int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001923 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001924 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001925 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001926 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1927 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001928 break;
1929 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001930 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001931 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1932 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001933 break;
1934 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001935 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001936 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001937 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001938 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001939 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001940 case EventEntry::Type::SENSOR:
1941 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001942 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001943 return ADISPLAY_ID_NONE;
1944 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001945 }
1946 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1947}
1948
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001949bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1950 const char* focusedWindowName) {
1951 if (mAnrTracker.empty()) {
1952 // already processed all events that we waited for
1953 mKeyIsWaitingForEventsTimeout = std::nullopt;
1954 return false;
1955 }
1956
1957 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1958 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001959 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001960 mKeyIsWaitingForEventsTimeout = currentTime +
1961 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1962 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001963 return true;
1964 }
1965
1966 // We still have pending events, and already started the timer
1967 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1968 return true; // Still waiting
1969 }
1970
1971 // Waited too long, and some connection still hasn't processed all motions
1972 // Just send the key to the focused window
1973 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1974 focusedWindowName);
1975 mKeyIsWaitingForEventsTimeout = std::nullopt;
1976 return false;
1977}
1978
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001979sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
1980 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
1981 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001982 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001983 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984
Tiger Huang721e26f2018-07-24 22:26:19 +08001985 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001986 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001987 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001988 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1989
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990 // If there is no currently focused window and no focused application
1991 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001992 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1993 ALOGI("Dropping %s event because there is no focused window or focused application in "
1994 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001995 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001996 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997 }
1998
Vishnu Nair062a8672021-09-03 16:07:44 -07001999 // Drop key events if requested by input feature
2000 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002001 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002002 }
2003
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002004 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2005 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2006 // start interacting with another application via touch (app switch). This code can be removed
2007 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2008 // an app is expected to have a focused window.
2009 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2010 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2011 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002012 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2013 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2014 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002015 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002016 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002017 ALOGW("Waiting because no window has focus but %s may eventually add a "
2018 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002019 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002020 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002021 outInjectionResult = InputEventInjectionResult::PENDING;
2022 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002023 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2024 // Already raised ANR. Drop the event
2025 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002026 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002027 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002028 } else {
2029 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002030 outInjectionResult = InputEventInjectionResult::PENDING;
2031 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002032 }
2033 }
2034
2035 // we have a valid, non-null focused window
2036 resetNoFocusedWindowTimeoutLocked();
2037
Prabir Pradhan5735a322022-04-11 17:23:34 +00002038 // Verify targeted injection.
2039 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2040 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002041 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2042 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043 }
2044
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002045 if (focusedWindowHandle->getInfo()->inputConfig.test(
2046 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002047 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002048 outInjectionResult = InputEventInjectionResult::PENDING;
2049 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002050 }
2051
2052 // If the event is a key event, then we must wait for all previous events to
2053 // complete before delivering it because previous events may have the
2054 // side-effect of transferring focus to a different window and we want to
2055 // ensure that the following keys are sent to the new window.
2056 //
2057 // Suppose the user touches a button in a window then immediately presses "A".
2058 // If the button causes a pop-up window to appear then we want to ensure that
2059 // the "A" key is delivered to the new pop-up window. This is because users
2060 // often anticipate pending UI changes when typing on a keyboard.
2061 // To obtain this behavior, we must serialize key events with respect to all
2062 // prior input events.
2063 if (entry.type == EventEntry::Type::KEY) {
2064 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2065 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002066 outInjectionResult = InputEventInjectionResult::PENDING;
2067 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069 }
2070
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002071 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2072 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073}
2074
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002075/**
2076 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2077 * that are currently unresponsive.
2078 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002079std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2080 const std::vector<Monitor>& monitors) const {
2081 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002082 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002083 [this](const Monitor& monitor) REQUIRES(mLock) {
2084 sp<Connection> connection =
2085 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002086 if (connection == nullptr) {
2087 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002088 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002089 return false;
2090 }
2091 if (!connection->responsive) {
2092 ALOGW("Unresponsive monitor %s will not get the new gesture",
2093 connection->inputChannel->getName().c_str());
2094 return false;
2095 }
2096 return true;
2097 });
2098 return responsiveMonitors;
2099}
2100
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002101/**
2102 * In general, touch should be always split between windows. Some exceptions:
2103 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2104 * from the same device, *and* the window that's receiving the current pointer does not support
2105 * split touch.
2106 * 2. Don't split mouse events
2107 */
2108bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2109 const MotionEntry& entry) const {
2110 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2111 // We should never split mouse events
2112 return false;
2113 }
2114 for (const TouchedWindow& touchedWindow : touchState.windows) {
2115 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2116 // Spy windows should not affect whether or not touch is split.
2117 continue;
2118 }
2119 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2120 continue;
2121 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002122 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2123 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2124 // Wallpaper window should not affect whether or not touch is split
2125 continue;
2126 }
2127
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002128 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2129 // being sent there. For now, use deviceId from touch state.
2130 if (entry.deviceId == touchState.deviceId && !touchedWindow.pointerIds.isEmpty()) {
2131 return false;
2132 }
2133 }
2134 return true;
2135}
2136
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002137std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002138 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2139 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002140 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002141
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002142 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143 // For security reasons, we defer updating the touch state until we are sure that
2144 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002145 const int32_t displayId = entry.displayId;
2146 const int32_t action = entry.action;
2147 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148
2149 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002150 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002151
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002152 // Copy current touch state into tempTouchState.
2153 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2154 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002155 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002156 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002157 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2158 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002159 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002160 }
2161
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002162 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002163 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002164 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002165
2166 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2167 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2168 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002169 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2170 // touchable windows.
2171 const bool wasDown = oldState != nullptr && oldState->isDown();
2172 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2173 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
2174 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002175 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002176
Michael Wrightd02c5b62014-02-10 15:10:22 -08002177 if (newGesture) {
2178 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002179 if (switchedDevice && tempTouchState.isDown() && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002180 ALOGI("Dropping event because a pointer for a different device is already down "
2181 "in display %" PRId32,
2182 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002183 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002184 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002185 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002187 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002188 tempTouchState.deviceId = entry.deviceId;
2189 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002191 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002192 ALOGI("Dropping move event because a pointer for a different device is already active "
2193 "in display %" PRId32,
2194 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002195 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002196 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002197 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198 }
2199
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002200 if (isHoverAction) {
2201 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2202 // all of the existing hovering pointers and recompute.
2203 tempTouchState.clearHoveringPointers();
2204 }
2205
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2207 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002208 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002209 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002210 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2211 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002212 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002213 auto [newTouchedWindowHandle, outsideTargets] =
2214 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002215
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002216 if (isDown) {
2217 targets += outsideTargets;
2218 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002220 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002221 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2222 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002223 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002224 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002225 }
2226
Prabir Pradhan5735a322022-04-11 17:23:34 +00002227 // Verify targeted injection.
2228 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2229 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002230 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002231 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002232 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002233 }
2234
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002235 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002236 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002237 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2238 // New window supports splitting, but we should never split mouse events.
2239 isSplit = !isFromMouse;
2240 } else if (isSplit) {
2241 // New window does not support splitting but we have already split events.
2242 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002243 newTouchedWindowHandle = nullptr;
2244 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002245 } else {
2246 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002247 // be delivered to a new window which supports split touch. Pointers from a mouse device
2248 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002249 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002250 }
2251
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002252 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002253 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002254 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002255 // Process the foreground window first so that it is the first to receive the event.
2256 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002257 }
2258
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002259 if (newTouchedWindows.empty()) {
2260 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2261 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002262 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002263 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002264 }
2265
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002266 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002267 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002268 continue;
2269 }
2270
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002271 if (isHoverAction) {
2272 const int32_t pointerId = entry.pointerProperties[0].id;
2273 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2274 // Pointer left. Remove it
2275 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2276 } else {
2277 // The "windowHandle" is the target of this hovering pointer.
2278 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId,
2279 pointerId);
2280 }
2281 }
2282
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002283 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002284 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002285
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002286 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2287 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002288 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002289 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002290
2291 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002292 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002293 }
2294 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002295 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002296 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002297 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002298 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002299
2300 // Update the temporary touch state.
2301 BitSet32 pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002302 if (!isHoverAction) {
2303 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2304 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002305
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002306 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
2307 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002308
2309 // If this is the pointer going down and the touched window has a wallpaper
2310 // then also add the touched wallpaper windows so they are locked in for the duration
2311 // of the touch gesture.
2312 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2313 // engine only supports touch events. We would need to add a mechanism similar
2314 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2315 if (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2316 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2317 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2318 windowHandle->getInfo()->inputConfig.test(
2319 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2320 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2321 if (wallpaper != nullptr) {
2322 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2323 InputTarget::Flags::WINDOW_IS_OBSCURED |
2324 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2325 InputTarget::Flags::DISPATCH_AS_IS;
2326 if (isSplit) {
2327 wallpaperFlags |= InputTarget::Flags::SPLIT;
2328 }
2329 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2330 entry.eventTime);
2331 }
2332 }
2333 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002335
2336 // If any existing window is pilfering pointers from newly added window, remove it
2337 BitSet32 canceledPointers = BitSet32(0);
2338 for (const TouchedWindow& window : tempTouchState.windows) {
2339 if (window.isPilferingPointers) {
2340 canceledPointers |= window.pointerIds;
2341 }
2342 }
2343 tempTouchState.cancelPointersForNonPilferingWindows(canceledPointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344 } else {
2345 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2346
2347 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002348 if (!tempTouchState.isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002349 ALOGD_IF(DEBUG_FOCUS,
2350 "Dropping event because the pointer is not down or we previously "
2351 "dropped the pointer down event in display %" PRId32 ": %s",
2352 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002353 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002354 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 }
2356
arthurhung6d4bed92021-03-17 11:59:33 +08002357 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002358
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002360 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002361 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002362 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07002363 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002364 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002365 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002366 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002367
Prabir Pradhan5735a322022-04-11 17:23:34 +00002368 // Verify targeted injection.
2369 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2370 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002371 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002372 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002373 }
2374
Vishnu Nair062a8672021-09-03 16:07:44 -07002375 // Drop touch events if requested by input feature
2376 if (newTouchedWindowHandle != nullptr &&
2377 shouldDropInput(entry, newTouchedWindowHandle)) {
2378 newTouchedWindowHandle = nullptr;
2379 }
2380
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002381 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2382 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002383 if (DEBUG_FOCUS) {
2384 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2385 oldTouchedWindowHandle->getName().c_str(),
2386 newTouchedWindowHandle->getName().c_str(), displayId);
2387 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002388 // Make a slippery exit from the old window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002389 BitSet32 pointerIds;
2390 const int32_t pointerId = entry.pointerProperties[0].id;
2391 pointerIds.markBit(pointerId);
2392
2393 const TouchedWindow& touchedWindow =
2394 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2395 addWindowTargetLocked(oldTouchedWindowHandle,
2396 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
2397 touchedWindow.firstDownTimeInTarget, targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398
2399 // Make a slippery entrance into the new window.
2400 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002401 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002402 }
2403
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002404 ftl::Flags<InputTarget::Flags> targetFlags =
2405 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002406 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002407 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002408 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002409 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002410 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002411 }
2412 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002413 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002414 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002415 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002416 }
2417
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002418 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2419 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002420
2421 // Check if the wallpaper window should deliver the corresponding event.
2422 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002423 tempTouchState, pointerId, targets);
2424 tempTouchState.removeTouchedPointerFromWindow(pointerId, oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425 }
2426 }
Arthur Hung96483742022-11-15 03:30:48 +00002427
2428 // Update the pointerIds for non-splittable when it received pointer down.
2429 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2430 // If no split, we suppose all touched windows should receive pointer down.
2431 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2432 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2433 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2434 // Ignore drag window for it should just track one pointer.
2435 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2436 continue;
2437 }
2438 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2439 }
2440 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441 }
2442
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002443 // Update dispatching for hover enter and exit.
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002444 {
2445 std::vector<TouchedWindow> hoveringWindows =
2446 getHoveringWindowsLocked(oldState, tempTouchState, entry);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002447 for (const TouchedWindow& touchedWindow : hoveringWindows) {
2448 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2449 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2450 targets);
2451 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452 }
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002453 // Ensure that we have at least one foreground window or at least one window that cannot be a
2454 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2455 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2456 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002457 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2458 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002459 return !canReceiveForegroundTouches(
2460 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002461 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002462 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002463 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2464 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002465 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002466 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002467 }
2468
Prabir Pradhan5735a322022-04-11 17:23:34 +00002469 // Ensure that all touched windows are valid for injection.
2470 if (entry.injectionState != nullptr) {
2471 std::string errs;
2472 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002473 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002474 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2475 // dispatched to any uid, since the coords will be zeroed out later.
2476 continue;
2477 }
2478 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2479 if (err) errs += "\n - " + *err;
2480 }
2481 if (!errs.empty()) {
2482 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2483 "%d:%s",
2484 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002485 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002486 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002487 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002488 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002489
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002490 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2491 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002492 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002493 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002494 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002495 if (foregroundWindowHandle) {
2496 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002497 for (InputTarget& target : targets) {
2498 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2499 sp<WindowInfoHandle> targetWindow =
2500 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2501 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2502 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 }
2505 }
2506 }
2507 }
2508
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002509 // Success! Output targets from the touch state.
2510 tempTouchState.clearWindowsWithoutPointers();
2511 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
2512 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2513 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2514 targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002515 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002516
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002517 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002518 // Drop the outside or hover touch windows since we will not care about them
2519 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002520 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002521
Michael Wrightd02c5b62014-02-10 15:10:22 -08002522 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002523 if (switchedDevice) {
2524 if (DEBUG_FOCUS) {
2525 ALOGD("Conflicting pointer actions: Switched to a different device.");
2526 }
2527 *outConflictingPointerActions = true;
2528 }
2529
2530 if (isHoverAction) {
2531 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002532 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002533 ALOGD_IF(DEBUG_FOCUS,
2534 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002535 *outConflictingPointerActions = true;
2536 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002537 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2538 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2539 tempTouchState.deviceId = entry.deviceId;
2540 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002541 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002542 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2543 // Pointer went up.
2544 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
2545 tempTouchState.clearWindowsWithoutPointers();
2546 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002547 // All pointers up or canceled.
2548 tempTouchState.reset();
2549 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2550 // First pointer went down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002551 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002552 ALOGD("Conflicting pointer actions: Down received while already down.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002553 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002554 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002555 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2556 // One pointer went up.
2557 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2558 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002560 for (size_t i = 0; i < tempTouchState.windows.size();) {
2561 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2562 touchedWindow.pointerIds.clearBit(pointerId);
2563 if (touchedWindow.pointerIds.isEmpty()) {
2564 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2565 continue;
2566 }
2567 i += 1;
2568 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569 }
2570
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002571 // Save changes unless the action was scroll in which case the temporary touch
2572 // state was only valid for this one action.
2573 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002574 if (displayId >= 0) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002575 mTouchStatesByDisplay[displayId] = tempTouchState;
2576 } else {
2577 mTouchStatesByDisplay.erase(displayId);
2578 }
2579 }
2580
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002581 if (tempTouchState.windows.empty()) {
2582 mTouchStatesByDisplay.erase(displayId);
2583 }
2584
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002585 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586}
2587
arthurhung6d4bed92021-03-17 11:59:33 +08002588void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002589 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2590 // have an explicit reason to support it.
2591 constexpr bool isStylus = false;
2592
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002593 auto [dropWindow, _] =
2594 findTouchedWindowAtLocked(displayId, x, y, isStylus, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002595 if (dropWindow) {
2596 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002597 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002598 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002599 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002600 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002601 }
2602 mDragState.reset();
2603}
2604
2605void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002606 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002607 return;
2608 }
2609
arthurhung6d4bed92021-03-17 11:59:33 +08002610 if (!mDragState->isStartDrag) {
2611 mDragState->isStartDrag = true;
2612 mDragState->isStylusButtonDownAtStart =
2613 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2614 }
2615
Arthur Hung54745652022-04-20 07:17:41 +00002616 // Find the pointer index by id.
2617 int32_t pointerIndex = 0;
2618 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2619 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2620 if (pointerProperties.id == mDragState->pointerId) {
2621 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002622 }
Arthur Hung54745652022-04-20 07:17:41 +00002623 }
arthurhung6d4bed92021-03-17 11:59:33 +08002624
Arthur Hung54745652022-04-20 07:17:41 +00002625 if (uint32_t(pointerIndex) == entry.pointerCount) {
2626 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002627 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002628 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002629 return;
2630 }
2631
2632 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2633 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2634 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2635
2636 switch (maskedAction) {
2637 case AMOTION_EVENT_ACTION_MOVE: {
2638 // Handle the special case : stylus button no longer pressed.
2639 bool isStylusButtonDown =
2640 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2641 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2642 finishDragAndDrop(entry.displayId, x, y);
2643 return;
2644 }
2645
2646 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2647 // until we have an explicit reason to support it.
2648 constexpr bool isStylus = false;
2649
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002650 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2651 true /*ignoreDragWindow*/);
Arthur Hung54745652022-04-20 07:17:41 +00002652 // enqueue drag exit if needed.
2653 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2654 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2655 if (mDragState->dragHoverWindowHandle != nullptr) {
2656 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2657 y);
2658 }
2659 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2660 }
2661 // enqueue drag location if needed.
2662 if (hoverWindowHandle != nullptr) {
2663 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2664 }
2665 break;
2666 }
2667
2668 case AMOTION_EVENT_ACTION_POINTER_UP:
2669 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2670 break;
2671 }
2672 // The drag pointer is up.
2673 [[fallthrough]];
2674 case AMOTION_EVENT_ACTION_UP:
2675 finishDragAndDrop(entry.displayId, x, y);
2676 break;
2677 case AMOTION_EVENT_ACTION_CANCEL: {
2678 ALOGD("Receiving cancel when drag and drop.");
2679 sendDropWindowCommandLocked(nullptr, 0, 0);
2680 mDragState.reset();
2681 break;
2682 }
arthurhungb89ccb02020-12-30 16:19:01 +08002683 }
2684}
2685
chaviw98318de2021-05-19 16:45:23 -05002686void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002687 ftl::Flags<InputTarget::Flags> targetFlags,
2688 BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002689 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002690 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002691 std::vector<InputTarget>::iterator it =
2692 std::find_if(inputTargets.begin(), inputTargets.end(),
2693 [&windowHandle](const InputTarget& inputTarget) {
2694 return inputTarget.inputChannel->getConnectionToken() ==
2695 windowHandle->getToken();
2696 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002697
chaviw98318de2021-05-19 16:45:23 -05002698 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002699
2700 if (it == inputTargets.end()) {
2701 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002702 std::shared_ptr<InputChannel> inputChannel =
2703 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002704 if (inputChannel == nullptr) {
2705 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2706 return;
2707 }
2708 inputTarget.inputChannel = inputChannel;
2709 inputTarget.flags = targetFlags;
2710 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002711 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002712 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2713 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002714 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002715 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002716 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002717 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002718 inputTargets.push_back(inputTarget);
2719 it = inputTargets.end() - 1;
2720 }
2721
2722 ALOG_ASSERT(it->flags == targetFlags);
2723 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2724
chaviw1ff3d1e2020-07-01 15:53:47 -07002725 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726}
2727
Michael Wright3dd60e22019-03-27 22:06:44 +00002728void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002729 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002730 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2731 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002732
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002733 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2734 InputTarget target;
2735 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002736 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002737 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2738 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002739 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2740 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002741 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002742 target.setDefaultPointerTransform(target.displayTransform);
2743 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744 }
2745}
2746
Robert Carrc9bf1d32020-04-13 17:21:08 -07002747/**
2748 * Indicate whether one window handle should be considered as obscuring
2749 * another window handle. We only check a few preconditions. Actually
2750 * checking the bounds is left to the caller.
2751 */
chaviw98318de2021-05-19 16:45:23 -05002752static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2753 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002754 // Compare by token so cloned layers aren't counted
2755 if (haveSameToken(windowHandle, otherHandle)) {
2756 return false;
2757 }
2758 auto info = windowHandle->getInfo();
2759 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002760 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002761 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002762 } else if (otherInfo->alpha == 0 &&
2763 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002764 // Those act as if they were invisible, so we don't need to flag them.
2765 // We do want to potentially flag touchable windows even if they have 0
2766 // opacity, since they can consume touches and alter the effects of the
2767 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002768 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002769 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2770 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002771 } else if (info->ownerUid == otherInfo->ownerUid) {
2772 // If ownerUid is the same we don't generate occlusion events as there
2773 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002774 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002775 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002776 return false;
2777 } else if (otherInfo->displayId != info->displayId) {
2778 return false;
2779 }
2780 return true;
2781}
2782
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002783/**
2784 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2785 * untrusted, one should check:
2786 *
2787 * 1. If result.hasBlockingOcclusion is true.
2788 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2789 * BLOCK_UNTRUSTED.
2790 *
2791 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2792 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2793 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2794 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2795 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2796 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2797 *
2798 * If neither of those is true, then it means the touch can be allowed.
2799 */
2800InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002801 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2802 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002803 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002804 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002805 TouchOcclusionInfo info;
2806 info.hasBlockingOcclusion = false;
2807 info.obscuringOpacity = 0;
2808 info.obscuringUid = -1;
2809 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002810 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002811 if (windowHandle == otherHandle) {
2812 break; // All future windows are below us. Exit early.
2813 }
chaviw98318de2021-05-19 16:45:23 -05002814 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002815 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2816 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002817 if (DEBUG_TOUCH_OCCLUSION) {
2818 info.debugInfo.push_back(
2819 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2820 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002821 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2822 // we perform the checks below to see if the touch can be propagated or not based on the
2823 // window's touch occlusion mode
2824 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2825 info.hasBlockingOcclusion = true;
2826 info.obscuringUid = otherInfo->ownerUid;
2827 info.obscuringPackage = otherInfo->packageName;
2828 break;
2829 }
2830 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2831 uint32_t uid = otherInfo->ownerUid;
2832 float opacity =
2833 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2834 // Given windows A and B:
2835 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2836 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2837 opacityByUid[uid] = opacity;
2838 if (opacity > info.obscuringOpacity) {
2839 info.obscuringOpacity = opacity;
2840 info.obscuringUid = uid;
2841 info.obscuringPackage = otherInfo->packageName;
2842 }
2843 }
2844 }
2845 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002846 if (DEBUG_TOUCH_OCCLUSION) {
2847 info.debugInfo.push_back(
2848 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2849 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002850 return info;
2851}
2852
chaviw98318de2021-05-19 16:45:23 -05002853std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002854 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002855 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2856 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2857 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2858 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002859 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2860 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2861 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2862 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2863 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002864 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002865 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002866}
2867
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002868bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2869 if (occlusionInfo.hasBlockingOcclusion) {
2870 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2871 occlusionInfo.obscuringUid);
2872 return false;
2873 }
2874 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2875 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2876 "%.2f, maximum allowed = %.2f)",
2877 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2878 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2879 return false;
2880 }
2881 return true;
2882}
2883
chaviw98318de2021-05-19 16:45:23 -05002884bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002885 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002887 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2888 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002889 if (windowHandle == otherHandle) {
2890 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891 }
chaviw98318de2021-05-19 16:45:23 -05002892 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002893 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002894 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002895 return true;
2896 }
2897 }
2898 return false;
2899}
2900
chaviw98318de2021-05-19 16:45:23 -05002901bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002902 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002903 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2904 const WindowInfo* windowInfo = windowHandle->getInfo();
2905 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002906 if (windowHandle == otherHandle) {
2907 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002908 }
chaviw98318de2021-05-19 16:45:23 -05002909 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002910 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002911 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002912 return true;
2913 }
2914 }
2915 return false;
2916}
2917
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002918std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002919 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002920 if (applicationHandle != nullptr) {
2921 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002922 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923 } else {
2924 return applicationHandle->getName();
2925 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002926 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002927 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002929 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930 }
2931}
2932
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002933void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002934 if (!isUserActivityEvent(eventEntry)) {
2935 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002936 return;
2937 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002938 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002939 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002940 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002941 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002942 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002943 if (DEBUG_DISPATCH_CYCLE) {
2944 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2945 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002946 return;
2947 }
2948 }
2949
2950 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002951 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002952 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002953 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2954 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002955 return;
2956 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002957
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002958 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002959 eventType = USER_ACTIVITY_EVENT_TOUCH;
2960 }
2961 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002962 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002963 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002964 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2965 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002966 return;
2967 }
2968 eventType = USER_ACTIVITY_EVENT_BUTTON;
2969 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002970 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002971 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002972 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002973 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002974 break;
2975 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002976 }
2977
Prabir Pradhancef936d2021-07-21 16:17:52 +00002978 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2979 REQUIRES(mLock) {
2980 scoped_unlock unlock(mLock);
2981 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2982 };
2983 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002984}
2985
2986void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002987 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002988 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002989 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002990 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002991 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002992 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002993 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002994 ATRACE_NAME(message.c_str());
2995 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002996 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002997 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002998 "globalScaleFactor=%f, pointerIds=0x%x %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002999 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003000 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
3001 inputTarget.getPointerInfoString().c_str());
3002 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003003
3004 // Skip this event if the connection status is not normal.
3005 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003006 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003007 if (DEBUG_DISPATCH_CYCLE) {
3008 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003009 connection->getInputChannelName().c_str(),
3010 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003012 return;
3013 }
3014
3015 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003016 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003017 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003018 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003019 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003020
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003021 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003022 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003023 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
3024 "Splitting motion events requires a down time to be set for the "
3025 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003026 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003027 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3028 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029 if (!splitMotionEntry) {
3030 return; // split event was dropped
3031 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003032 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3033 std::string reason = std::string("reason=pointer cancel on split window");
3034 android_log_event_list(LOGTAG_INPUT_CANCEL)
3035 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3036 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003037 if (DEBUG_FOCUS) {
3038 ALOGD("channel '%s' ~ Split motion event.",
3039 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003040 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003041 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003042 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3043 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003044 return;
3045 }
3046 }
3047
3048 // Not splitting. Enqueue dispatch entries for the event as is.
3049 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3050}
3051
3052void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003053 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003054 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003055 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003056 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003057 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003058 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003059 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003060 ATRACE_NAME(message.c_str());
3061 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003062 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3063 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003064
hongzuo liu95785e22022-09-06 02:51:35 +00003065 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066
3067 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003068 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003069 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003070 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003071 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003072 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003073 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003074 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003075 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003076 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003077 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003078 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003079 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003080
3081 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003082 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003083 startDispatchCycleLocked(currentTime, connection);
3084 }
3085}
3086
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003087void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003088 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003089 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003090 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003091 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003092 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3093 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003094 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003095 ATRACE_NAME(message.c_str());
3096 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003097 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3098 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003099 return;
3100 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003101
3102 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3103 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003104
3105 // This is a new event.
3106 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003107 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003108 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003109
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003110 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3111 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003112 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003113 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003114 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003115 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003116 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003117 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003118 dispatchEntry->resolvedAction = keyEntry.action;
3119 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003120
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003121 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3122 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003123 if (DEBUG_DISPATCH_CYCLE) {
3124 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3125 "event",
3126 connection->getInputChannelName().c_str());
3127 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003128 return; // skip the inconsistent event
3129 }
3130 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003131 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003133 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003134 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003135 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3136 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3137 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3138 static_cast<int32_t>(IdGenerator::Source::OTHER);
3139 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003140 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003141 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003142 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003143 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003144 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003145 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003146 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003147 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003148 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003149 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3150 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003151 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003152 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003153 }
3154 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003155 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3156 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003157 if (DEBUG_DISPATCH_CYCLE) {
3158 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3159 "enter event",
3160 connection->getInputChannelName().c_str());
3161 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003162 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3163 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003164 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3165 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003167 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003168 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003169 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3170 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003171 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003172 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003175 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3176 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003177 if (DEBUG_DISPATCH_CYCLE) {
3178 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3179 "event",
3180 connection->getInputChannelName().c_str());
3181 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003182 return; // skip the inconsistent event
3183 }
3184
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003185 dispatchEntry->resolvedEventId =
3186 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3187 ? mIdGenerator.nextId()
3188 : motionEntry.id;
3189 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3190 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3191 ") to MotionEvent(id=0x%" PRIx32 ").",
3192 motionEntry.id, dispatchEntry->resolvedEventId);
3193 ATRACE_NAME(message.c_str());
3194 }
3195
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003196 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3197 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3198 // Skip reporting pointer down outside focus to the policy.
3199 break;
3200 }
3201
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003202 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003203 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003204
3205 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003206 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003207 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003208 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003209 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3210 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003211 break;
3212 }
Chris Yef59a2f42020-10-16 12:55:26 -07003213 case EventEntry::Type::SENSOR: {
3214 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3215 break;
3216 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003217 case EventEntry::Type::CONFIGURATION_CHANGED:
3218 case EventEntry::Type::DEVICE_RESET: {
3219 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003220 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003221 break;
3222 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003223 }
3224
3225 // Remember that we are waiting for this dispatch to complete.
3226 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003227 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228 }
3229
3230 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003231 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003232 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003233}
3234
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003235/**
3236 * This function is purely for debugging. It helps us understand where the user interaction
3237 * was taking place. For example, if user is touching launcher, we will see a log that user
3238 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3239 * We will see both launcher and wallpaper in that list.
3240 * Once the interaction with a particular set of connections starts, no new logs will be printed
3241 * until the set of interacted connections changes.
3242 *
3243 * The following items are skipped, to reduce the logspam:
3244 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3245 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3246 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3247 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3248 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003249 */
3250void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3251 const std::vector<InputTarget>& targets) {
3252 // Skip ACTION_UP events, and all events other than keys and motions
3253 if (entry.type == EventEntry::Type::KEY) {
3254 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3255 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3256 return;
3257 }
3258 } else if (entry.type == EventEntry::Type::MOTION) {
3259 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3260 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3261 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3262 return;
3263 }
3264 } else {
3265 return; // Not a key or a motion
3266 }
3267
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003268 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003269 std::vector<sp<Connection>> newConnections;
3270 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003271 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003272 continue; // Skip windows that receive ACTION_OUTSIDE
3273 }
3274
3275 sp<IBinder> token = target.inputChannel->getConnectionToken();
3276 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003277 if (connection == nullptr) {
3278 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003279 }
3280 newConnectionTokens.insert(std::move(token));
3281 newConnections.emplace_back(connection);
3282 }
3283 if (newConnectionTokens == mInteractionConnectionTokens) {
3284 return; // no change
3285 }
3286 mInteractionConnectionTokens = newConnectionTokens;
3287
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003288 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003289 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003290 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003291 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003292 std::string message = "Interaction with: " + targetList;
3293 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003294 message += "<none>";
3295 }
3296 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3297}
3298
chaviwfd6d3512019-03-25 13:23:49 -07003299void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003300 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003301 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003302 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3303 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003304 return;
3305 }
3306
Vishnu Nairc519ff72021-01-21 08:23:08 -08003307 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003308 if (focusedToken == token) {
3309 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003310 return;
3311 }
3312
Prabir Pradhancef936d2021-07-21 16:17:52 +00003313 auto command = [this, token]() REQUIRES(mLock) {
3314 scoped_unlock unlock(mLock);
3315 mPolicy->onPointerDownOutsideFocus(token);
3316 };
3317 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318}
3319
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003320status_t InputDispatcher::publishMotionEvent(Connection& connection,
3321 DispatchEntry& dispatchEntry) const {
3322 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3323 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3324
3325 PointerCoords scaledCoords[MAX_POINTERS];
3326 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3327
3328 // Set the X and Y offset and X and Y scale depending on the input source.
3329 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003330 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003331 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3332 if (globalScaleFactor != 1.0f) {
3333 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3334 scaledCoords[i] = motionEntry.pointerCoords[i];
3335 // Don't apply window scale here since we don't want scale to affect raw
3336 // coordinates. The scale will be sent back to the client and applied
3337 // later when requesting relative coordinates.
3338 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3339 1 /* windowYScale */);
3340 }
3341 usingCoords = scaledCoords;
3342 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003343 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003344 // We don't want the dispatch target to know the coordinates
3345 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3346 scaledCoords[i].clear();
3347 }
3348 usingCoords = scaledCoords;
3349 }
3350
3351 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3352
3353 // Publish the motion event.
3354 return connection.inputPublisher
3355 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3356 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3357 std::move(hmac), dispatchEntry.resolvedAction,
3358 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3359 motionEntry.edgeFlags, motionEntry.metaState,
3360 motionEntry.buttonState, motionEntry.classification,
3361 dispatchEntry.transform, motionEntry.xPrecision,
3362 motionEntry.yPrecision, motionEntry.xCursorPosition,
3363 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3364 motionEntry.downTime, motionEntry.eventTime,
3365 motionEntry.pointerCount, motionEntry.pointerProperties,
3366 usingCoords);
3367}
3368
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003370 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003371 if (ATRACE_ENABLED()) {
3372 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003373 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003374 ATRACE_NAME(message.c_str());
3375 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003376 if (DEBUG_DISPATCH_CYCLE) {
3377 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003380 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003381 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003383 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003384 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385
3386 // Publish the event.
3387 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003388 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3389 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003390 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003391 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3392 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003393 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3394 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3395 << connection->getInputChannelName();
3396 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003397
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003398 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003399 status = connection->inputPublisher
3400 .publishKeyEvent(dispatchEntry->seq,
3401 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3402 keyEntry.source, keyEntry.displayId,
3403 std::move(hmac), dispatchEntry->resolvedAction,
3404 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3405 keyEntry.scanCode, keyEntry.metaState,
3406 keyEntry.repeatCount, keyEntry.downTime,
3407 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003408 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409 }
3410
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003411 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003412 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3413 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3414 << connection->getInputChannelName();
3415 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003416 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003417 break;
3418 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003419
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003420 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003421 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003422 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003423 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003424 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003425 break;
3426 }
3427
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003428 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3429 const TouchModeEntry& touchModeEntry =
3430 static_cast<const TouchModeEntry&>(eventEntry);
3431 status = connection->inputPublisher
3432 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3433 touchModeEntry.inTouchMode);
3434
3435 break;
3436 }
3437
Prabir Pradhan99987712020-11-10 18:43:05 -08003438 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3439 const auto& captureEntry =
3440 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3441 status = connection->inputPublisher
3442 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003443 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003444 break;
3445 }
3446
arthurhungb89ccb02020-12-30 16:19:01 +08003447 case EventEntry::Type::DRAG: {
3448 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3449 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3450 dragEntry.id, dragEntry.x,
3451 dragEntry.y,
3452 dragEntry.isExiting);
3453 break;
3454 }
3455
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003456 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003457 case EventEntry::Type::DEVICE_RESET:
3458 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003459 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003460 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003461 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003463 }
3464
3465 // Check the result.
3466 if (status) {
3467 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003468 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003469 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003470 "This is unexpected because the wait queue is empty, so the pipe "
3471 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003472 "event to it, status=%s(%d)",
3473 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3474 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3476 } else {
3477 // Pipe is full and we are waiting for the app to finish process some events
3478 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003479 if (DEBUG_DISPATCH_CYCLE) {
3480 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3481 "waiting for the application to catch up",
3482 connection->getInputChannelName().c_str());
3483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003484 }
3485 } else {
3486 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003487 "status=%s(%d)",
3488 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3489 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3491 }
3492 return;
3493 }
3494
3495 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003496 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3497 connection->outboundQueue.end(),
3498 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003499 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003500 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003501 if (connection->responsive) {
3502 mAnrTracker.insert(dispatchEntry->timeoutTime,
3503 connection->inputChannel->getConnectionToken());
3504 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003505 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506 }
3507}
3508
chaviw09c8d2d2020-08-24 15:48:26 -07003509std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3510 size_t size;
3511 switch (event.type) {
3512 case VerifiedInputEvent::Type::KEY: {
3513 size = sizeof(VerifiedKeyEvent);
3514 break;
3515 }
3516 case VerifiedInputEvent::Type::MOTION: {
3517 size = sizeof(VerifiedMotionEvent);
3518 break;
3519 }
3520 }
3521 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3522 return mHmacKeyManager.sign(start, size);
3523}
3524
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003525const std::array<uint8_t, 32> InputDispatcher::getSignature(
3526 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003527 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3528 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003529 // Only sign events up and down events as the purely move events
3530 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003531 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003532 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003533
3534 VerifiedMotionEvent verifiedEvent =
3535 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3536 verifiedEvent.actionMasked = actionMasked;
3537 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3538 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003539}
3540
3541const std::array<uint8_t, 32> InputDispatcher::getSignature(
3542 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3543 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3544 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3545 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003546 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003547}
3548
Michael Wrightd02c5b62014-02-10 15:10:22 -08003549void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003550 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003551 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003552 if (DEBUG_DISPATCH_CYCLE) {
3553 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3554 connection->getInputChannelName().c_str(), seq, toString(handled));
3555 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003556
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003557 if (connection->status == Connection::Status::BROKEN ||
3558 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559 return;
3560 }
3561
3562 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003563 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3564 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3565 };
3566 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567}
3568
3569void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003570 const sp<Connection>& connection,
3571 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003572 if (DEBUG_DISPATCH_CYCLE) {
3573 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3574 connection->getInputChannelName().c_str(), toString(notify));
3575 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003576
3577 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003578 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003579 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003580 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003581 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003582
3583 // The connection appears to be unrecoverably broken.
3584 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003585 if (connection->status == Connection::Status::NORMAL) {
3586 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003587
3588 if (notify) {
3589 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003590 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3591 connection->getInputChannelName().c_str());
3592
3593 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003594 scoped_unlock unlock(mLock);
3595 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3596 };
3597 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598 }
3599 }
3600}
3601
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003602void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3603 while (!queue.empty()) {
3604 DispatchEntry* dispatchEntry = queue.front();
3605 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003606 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003607 }
3608}
3609
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003610void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003612 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003613 }
3614 delete dispatchEntry;
3615}
3616
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003617int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3618 std::scoped_lock _l(mLock);
3619 sp<Connection> connection = getConnectionLocked(connectionToken);
3620 if (connection == nullptr) {
3621 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3622 connectionToken.get(), events);
3623 return 0; // remove the callback
3624 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003625
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003626 bool notify;
3627 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3628 if (!(events & ALOOPER_EVENT_INPUT)) {
3629 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3630 "events=0x%x",
3631 connection->getInputChannelName().c_str(), events);
3632 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633 }
3634
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003635 nsecs_t currentTime = now();
3636 bool gotOne = false;
3637 status_t status = OK;
3638 for (;;) {
3639 Result<InputPublisher::ConsumerResponse> result =
3640 connection->inputPublisher.receiveConsumerResponse();
3641 if (!result.ok()) {
3642 status = result.error().code();
3643 break;
3644 }
3645
3646 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3647 const InputPublisher::Finished& finish =
3648 std::get<InputPublisher::Finished>(*result);
3649 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3650 finish.consumeTime);
3651 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003652 if (shouldReportMetricsForConnection(*connection)) {
3653 const InputPublisher::Timeline& timeline =
3654 std::get<InputPublisher::Timeline>(*result);
3655 mLatencyTracker
3656 .trackGraphicsLatency(timeline.inputEventId,
3657 connection->inputChannel->getConnectionToken(),
3658 std::move(timeline.graphicsTimeline));
3659 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003660 }
3661 gotOne = true;
3662 }
3663 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003664 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003665 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666 return 1;
3667 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003668 }
3669
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003670 notify = status != DEAD_OBJECT || !connection->monitor;
3671 if (notify) {
3672 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3673 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3674 status);
3675 }
3676 } else {
3677 // Monitor channels are never explicitly unregistered.
3678 // We do it automatically when the remote endpoint is closed so don't warn about them.
3679 const bool stillHaveWindowHandle =
3680 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3681 notify = !connection->monitor && stillHaveWindowHandle;
3682 if (notify) {
3683 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3684 connection->getInputChannelName().c_str(), events);
3685 }
3686 }
3687
3688 // Remove the channel.
3689 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3690 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691}
3692
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003693void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003695 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003696 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003697 }
3698}
3699
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003700void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003701 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003702 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003703 for (const Monitor& monitor : monitors) {
3704 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003705 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003706 }
3707}
3708
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003710 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003711 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003712 if (connection == nullptr) {
3713 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003715
3716 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003717}
3718
3719void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3720 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003721 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722 return;
3723 }
3724
3725 nsecs_t currentTime = now();
3726
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003727 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003728 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003730 if (cancelationEvents.empty()) {
3731 return;
3732 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003733 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3734 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3735 "with reality: %s, mode=%d.",
3736 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3737 options.mode);
3738 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003739
Arthur Hungb3307ee2021-10-14 10:57:37 +00003740 std::string reason = std::string("reason=").append(options.reason);
3741 android_log_event_list(LOGTAG_INPUT_CANCEL)
3742 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3743
Svet Ganov5d3bc372020-01-26 23:11:07 -08003744 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();
3756
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003757 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003758 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003759 switch (cancelationEventEntry->type) {
3760 case EventEntry::Type::KEY: {
3761 logOutboundKeyDetails("cancel - ",
3762 static_cast<const KeyEntry&>(*cancelationEventEntry));
3763 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003765 case EventEntry::Type::MOTION: {
3766 logOutboundMotionDetails("cancel - ",
3767 static_cast<const MotionEntry&>(*cancelationEventEntry));
3768 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003770 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003771 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003772 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3773 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003774 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003775 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003776 break;
3777 }
3778 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003779 case EventEntry::Type::DEVICE_RESET:
3780 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003781 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003782 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003783 break;
3784 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785 }
3786
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003787 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003788 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003790
hongzuo liu95785e22022-09-06 02:51:35 +00003791 // If the outbound queue was previously empty, start the dispatch cycle going.
3792 if (wasEmpty && !connection->outboundQueue.empty()) {
3793 startDispatchCycleLocked(currentTime, connection);
3794 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795}
3796
Svet Ganov5d3bc372020-01-26 23:11:07 -08003797void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Arthur Hungc539dbb2022-12-08 07:45:36 +00003798 const nsecs_t downTime, const sp<Connection>& connection,
3799 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003800 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003801 return;
3802 }
3803
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003804 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003805 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003806
3807 if (downEvents.empty()) {
3808 return;
3809 }
3810
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003811 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003812 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3813 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003814 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003815
3816 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003817 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003818 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3819 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003820 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003821 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003822 target.globalScaleFactor = windowInfo->globalScaleFactor;
3823 }
3824 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00003825 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003826
hongzuo liu95785e22022-09-06 02:51:35 +00003827 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003828 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003829 switch (downEventEntry->type) {
3830 case EventEntry::Type::MOTION: {
3831 logOutboundMotionDetails("down - ",
3832 static_cast<const MotionEntry&>(*downEventEntry));
3833 break;
3834 }
3835
3836 case EventEntry::Type::KEY:
3837 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003838 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003839 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003840 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003841 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003842 case EventEntry::Type::SENSOR:
3843 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003844 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003845 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003846 break;
3847 }
3848 }
3849
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003850 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003851 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003852 }
3853
hongzuo liu95785e22022-09-06 02:51:35 +00003854 // If the outbound queue was previously empty, start the dispatch cycle going.
3855 if (wasEmpty && !connection->outboundQueue.empty()) {
3856 startDispatchCycleLocked(downTime, connection);
3857 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003858}
3859
Arthur Hungc539dbb2022-12-08 07:45:36 +00003860void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
3861 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
3862 if (windowHandle != nullptr) {
3863 sp<Connection> wallpaperConnection = getConnectionLocked(windowHandle->getToken());
3864 if (wallpaperConnection != nullptr) {
3865 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
3866 }
3867 }
3868}
3869
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003870std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003871 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872 ALOG_ASSERT(pointerIds.value != 0);
3873
3874 uint32_t splitPointerIndexMap[MAX_POINTERS];
3875 PointerProperties splitPointerProperties[MAX_POINTERS];
3876 PointerCoords splitPointerCoords[MAX_POINTERS];
3877
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003878 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879 uint32_t splitPointerCount = 0;
3880
3881 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003882 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003884 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003885 uint32_t pointerId = uint32_t(pointerProperties.id);
3886 if (pointerIds.hasBit(pointerId)) {
3887 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3888 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3889 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003890 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891 splitPointerCount += 1;
3892 }
3893 }
3894
3895 if (splitPointerCount != pointerIds.count()) {
3896 // This is bad. We are missing some of the pointers that we expected to deliver.
3897 // Most likely this indicates that we received an ACTION_MOVE events that has
3898 // different pointer ids than we expected based on the previous ACTION_DOWN
3899 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3900 // in this way.
3901 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003902 "we expected there to be %d pointers. This probably means we received "
3903 "a broken sequence of pointer ids from the input device.",
3904 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003905 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906 }
3907
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003908 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003909 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003910 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3911 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3913 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003914 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915 uint32_t pointerId = uint32_t(pointerProperties.id);
3916 if (pointerIds.hasBit(pointerId)) {
3917 if (pointerIds.count() == 1) {
3918 // The first/last pointer went down/up.
3919 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003920 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003921 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3922 ? AMOTION_EVENT_ACTION_CANCEL
3923 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924 } else {
3925 // A secondary pointer went down/up.
3926 uint32_t splitPointerIndex = 0;
3927 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3928 splitPointerIndex += 1;
3929 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003930 action = maskedAction |
3931 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932 }
3933 } else {
3934 // An unrelated pointer changed.
3935 action = AMOTION_EVENT_ACTION_MOVE;
3936 }
3937 }
3938
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003939 if (action == AMOTION_EVENT_ACTION_DOWN) {
3940 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3941 "Split motion event has mismatching downTime and eventTime for "
3942 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3943 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3944 }
3945
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003946 int32_t newId = mIdGenerator.nextId();
3947 if (ATRACE_ENABLED()) {
3948 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3949 ") to MotionEvent(id=0x%" PRIx32 ").",
3950 originalMotionEntry.id, newId);
3951 ATRACE_NAME(message.c_str());
3952 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003953 std::unique_ptr<MotionEntry> splitMotionEntry =
3954 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3955 originalMotionEntry.deviceId, originalMotionEntry.source,
3956 originalMotionEntry.displayId,
3957 originalMotionEntry.policyFlags, action,
3958 originalMotionEntry.actionButton,
3959 originalMotionEntry.flags, originalMotionEntry.metaState,
3960 originalMotionEntry.buttonState,
3961 originalMotionEntry.classification,
3962 originalMotionEntry.edgeFlags,
3963 originalMotionEntry.xPrecision,
3964 originalMotionEntry.yPrecision,
3965 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003966 originalMotionEntry.yCursorPosition, splitDownTime,
3967 splitPointerCount, splitPointerProperties,
3968 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003970 if (originalMotionEntry.injectionState) {
3971 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972 splitMotionEntry->injectionState->refCount += 1;
3973 }
3974
3975 return splitMotionEntry;
3976}
3977
3978void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003979 if (DEBUG_INBOUND_EVENT_DETAILS) {
3980 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003982
Antonio Kantekf16f2832021-09-28 04:39:20 +00003983 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003985 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003987 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3988 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3989 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990 } // release lock
3991
3992 if (needWake) {
3993 mLooper->wake();
3994 }
3995}
3996
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003997/**
3998 * If one of the meta shortcuts is detected, process them here:
3999 * Meta + Backspace -> generate BACK
4000 * Meta + Enter -> generate HOME
4001 * This will potentially overwrite keyCode and metaState.
4002 */
4003void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004004 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004005 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4006 int32_t newKeyCode = AKEYCODE_UNKNOWN;
4007 if (keyCode == AKEYCODE_DEL) {
4008 newKeyCode = AKEYCODE_BACK;
4009 } else if (keyCode == AKEYCODE_ENTER) {
4010 newKeyCode = AKEYCODE_HOME;
4011 }
4012 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004013 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004014 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004015 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004016 keyCode = newKeyCode;
4017 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4018 }
4019 } else if (action == AKEY_EVENT_ACTION_UP) {
4020 // In order to maintain a consistent stream of up and down events, check to see if the key
4021 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4022 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004023 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004024 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004025 auto replacementIt = mReplacedKeys.find(replacement);
4026 if (replacementIt != mReplacedKeys.end()) {
4027 keyCode = replacementIt->second;
4028 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004029 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4030 }
4031 }
4032}
4033
Michael Wrightd02c5b62014-02-10 15:10:22 -08004034void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004035 if (DEBUG_INBOUND_EVENT_DETAILS) {
4036 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
4037 "policyFlags=0x%x, action=0x%x, "
4038 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
4039 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
4040 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
4041 args->downTime);
4042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004043 if (!validateKeyEvent(args->action)) {
4044 return;
4045 }
4046
4047 uint32_t policyFlags = args->policyFlags;
4048 int32_t flags = args->flags;
4049 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004050 // InputDispatcher tracks and generates key repeats on behalf of
4051 // whatever notifies it, so repeatCount should always be set to 0
4052 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004053 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4054 policyFlags |= POLICY_FLAG_VIRTUAL;
4055 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004057 if (policyFlags & POLICY_FLAG_FUNCTION) {
4058 metaState |= AMETA_FUNCTION_ON;
4059 }
4060
4061 policyFlags |= POLICY_FLAG_TRUSTED;
4062
Michael Wright78f24442014-08-06 15:55:28 -07004063 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004064 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004065
Michael Wrightd02c5b62014-02-10 15:10:22 -08004066 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004067 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08004068 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
4069 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070
Michael Wright2b3c3302018-03-02 17:19:13 +00004071 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004073 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4074 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004075 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004076 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077
Antonio Kantekf16f2832021-09-28 04:39:20 +00004078 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079 { // acquire lock
4080 mLock.lock();
4081
4082 if (shouldSendKeyToInputFilterLocked(args)) {
4083 mLock.unlock();
4084
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004085 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4087 return; // event was consumed by the filter
4088 }
4089
4090 mLock.lock();
4091 }
4092
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004093 std::unique_ptr<KeyEntry> newEntry =
4094 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4095 args->displayId, policyFlags, args->action, flags,
4096 keyCode, args->scanCode, metaState, repeatCount,
4097 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004099 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100 mLock.unlock();
4101 } // release lock
4102
4103 if (needWake) {
4104 mLooper->wake();
4105 }
4106}
4107
4108bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4109 return mInputFilterEnabled;
4110}
4111
4112void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004113 if (DEBUG_INBOUND_EVENT_DETAILS) {
4114 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4115 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004116 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004117 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4118 "yCursorPosition=%f, downTime=%" PRId64,
4119 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004120 args->policyFlags, MotionEvent::actionToString(args->action).c_str(),
4121 args->actionButton, args->flags, args->metaState, args->buttonState, args->edgeFlags,
4122 args->xPrecision, args->yPrecision, args->xCursorPosition, args->yCursorPosition,
4123 args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004124 for (uint32_t i = 0; i < args->pointerCount; i++) {
4125 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4126 "x=%f, y=%f, pressure=%f, size=%f, "
4127 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4128 "orientation=%f",
4129 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4130 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4131 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4132 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4133 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4134 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4135 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4136 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4137 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4138 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4139 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -08004141 LOG_ALWAYS_FATAL_IF(!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4142 args->pointerProperties),
4143 "Invalid event: %s", args->dump().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144
4145 uint32_t policyFlags = args->policyFlags;
4146 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004147
4148 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004149 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004150 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4151 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004152 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004153 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154
Antonio Kantekf16f2832021-09-28 04:39:20 +00004155 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004156 { // acquire lock
4157 mLock.lock();
4158
4159 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004160 ui::Transform displayTransform;
4161 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4162 displayTransform = it->second.transform;
4163 }
4164
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165 mLock.unlock();
4166
4167 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004168 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4169 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004170 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004171 displayTransform, args->xPrecision, args->yPrecision,
4172 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004173 args->downTime, args->eventTime, args->pointerCount,
4174 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175
4176 policyFlags |= POLICY_FLAG_FILTERED;
4177 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4178 return; // event was consumed by the filter
4179 }
4180
4181 mLock.lock();
4182 }
4183
4184 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004185 std::unique_ptr<MotionEntry> newEntry =
4186 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4187 args->source, args->displayId, policyFlags,
4188 args->action, args->actionButton, args->flags,
4189 args->metaState, args->buttonState,
4190 args->classification, args->edgeFlags,
4191 args->xPrecision, args->yPrecision,
4192 args->xCursorPosition, args->yCursorPosition,
4193 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004194 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004196 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4197 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4198 !mInputFilterEnabled) {
4199 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4200 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4201 }
4202
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004203 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204 mLock.unlock();
4205 } // release lock
4206
4207 if (needWake) {
4208 mLooper->wake();
4209 }
4210}
4211
Chris Yef59a2f42020-10-16 12:55:26 -07004212void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004213 if (DEBUG_INBOUND_EVENT_DETAILS) {
4214 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4215 " sensorType=%s",
4216 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004217 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004218 }
Chris Yef59a2f42020-10-16 12:55:26 -07004219
Antonio Kantekf16f2832021-09-28 04:39:20 +00004220 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004221 { // acquire lock
4222 mLock.lock();
4223
4224 // Just enqueue a new sensor event.
4225 std::unique_ptr<SensorEntry> newEntry =
4226 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4227 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4228 args->sensorType, args->accuracy,
4229 args->accuracyChanged, args->values);
4230
4231 needWake = enqueueInboundEventLocked(std::move(newEntry));
4232 mLock.unlock();
4233 } // release lock
4234
4235 if (needWake) {
4236 mLooper->wake();
4237 }
4238}
4239
Chris Yefb552902021-02-03 17:18:37 -08004240void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004241 if (DEBUG_INBOUND_EVENT_DETAILS) {
4242 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4243 args->deviceId, args->isOn);
4244 }
Chris Yefb552902021-02-03 17:18:37 -08004245 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4246}
4247
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004249 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250}
4251
4252void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004253 if (DEBUG_INBOUND_EVENT_DETAILS) {
4254 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4255 "switchMask=0x%08x",
4256 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4257 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258
4259 uint32_t policyFlags = args->policyFlags;
4260 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004261 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262}
4263
4264void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004265 if (DEBUG_INBOUND_EVENT_DETAILS) {
4266 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4267 args->deviceId);
4268 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269
Antonio Kantekf16f2832021-09-28 04:39:20 +00004270 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004272 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004274 std::unique_ptr<DeviceResetEntry> newEntry =
4275 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4276 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 } // release lock
4278
4279 if (needWake) {
4280 mLooper->wake();
4281 }
4282}
4283
Prabir Pradhan7e186182020-11-10 13:56:45 -08004284void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004285 if (DEBUG_INBOUND_EVENT_DETAILS) {
4286 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004287 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004288 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004289
Antonio Kantekf16f2832021-09-28 04:39:20 +00004290 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004291 { // acquire lock
4292 std::scoped_lock _l(mLock);
4293 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004294 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004295 needWake = enqueueInboundEventLocked(std::move(entry));
4296 } // release lock
4297
4298 if (needWake) {
4299 mLooper->wake();
4300 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004301}
4302
Prabir Pradhan5735a322022-04-11 17:23:34 +00004303InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4304 std::optional<int32_t> targetUid,
4305 InputEventInjectionSync syncMode,
4306 std::chrono::milliseconds timeout,
4307 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004308 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004309 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4310 "policyFlags=0x%08x",
4311 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4312 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004313 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004314 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315
Prabir Pradhan5735a322022-04-11 17:23:34 +00004316 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004318 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004319 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4320 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4321 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4322 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4323 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004324 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004325 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004326 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004327 }
4328
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004329 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004331 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004332 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4333 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004334 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004335 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004336 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004337
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004338 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004339 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4340 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4341 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004342 int32_t keyCode = incomingKey.getKeyCode();
4343 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004344 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004345 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004346 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004347 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004348 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4349 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4350 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004352 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4353 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004354 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004355
4356 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4357 android::base::Timer t;
4358 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4359 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4360 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4361 std::to_string(t.duration().count()).c_str());
4362 }
4363 }
4364
4365 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004366 std::unique_ptr<KeyEntry> injectedEntry =
4367 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004368 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004369 incomingKey.getDisplayId(), policyFlags, action,
4370 flags, keyCode, incomingKey.getScanCode(), metaState,
4371 incomingKey.getRepeatCount(),
4372 incomingKey.getDownTime());
4373 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004374 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375 }
4376
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004377 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004378 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004379 const int32_t action = motionEvent.getAction();
4380 const bool isPointerEvent =
4381 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4382 // If a pointer event has no displayId specified, inject it to the default display.
4383 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4384 ? ADISPLAY_ID_DEFAULT
4385 : event->getDisplayId();
4386 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004387 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004388 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004389 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004390 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004391 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004392 }
4393
4394 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004395 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004396 android::base::Timer t;
4397 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4398 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4399 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4400 std::to_string(t.duration().count()).c_str());
4401 }
4402 }
4403
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004404 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4405 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4406 }
4407
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004408 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004409 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4410 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004411 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004412 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4413 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004414 displayId, policyFlags, action, actionButton,
4415 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004416 motionEvent.getButtonState(),
4417 motionEvent.getClassification(),
4418 motionEvent.getEdgeFlags(),
4419 motionEvent.getXPrecision(),
4420 motionEvent.getYPrecision(),
4421 motionEvent.getRawXCursorPosition(),
4422 motionEvent.getRawYCursorPosition(),
4423 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004424 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004425 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004426 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004427 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004428 sampleEventTimes += 1;
4429 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004430 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004431 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4432 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004433 displayId, policyFlags, action, actionButton,
4434 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004435 motionEvent.getButtonState(),
4436 motionEvent.getClassification(),
4437 motionEvent.getEdgeFlags(),
4438 motionEvent.getXPrecision(),
4439 motionEvent.getYPrecision(),
4440 motionEvent.getRawXCursorPosition(),
4441 motionEvent.getRawYCursorPosition(),
4442 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004443 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004444 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004445 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4446 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004447 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004448 }
4449 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004450 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004451
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004452 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004453 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004454 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004455 }
4456
Prabir Pradhan5735a322022-04-11 17:23:34 +00004457 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004458 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004459 injectionState->injectionIsAsync = true;
4460 }
4461
4462 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004463 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004464
4465 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004466 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004467 if (DEBUG_INJECTION) {
4468 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4469 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004470 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004471 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004472 }
4473
4474 mLock.unlock();
4475
4476 if (needWake) {
4477 mLooper->wake();
4478 }
4479
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004480 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004481 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004482 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004483
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004484 if (syncMode == InputEventInjectionSync::NONE) {
4485 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004486 } else {
4487 for (;;) {
4488 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004489 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004490 break;
4491 }
4492
4493 nsecs_t remainingTimeout = endTime - now();
4494 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004495 if (DEBUG_INJECTION) {
4496 ALOGD("injectInputEvent - Timed out waiting for injection result "
4497 "to become available.");
4498 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004499 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500 break;
4501 }
4502
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004503 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504 }
4505
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004506 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4507 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004509 if (DEBUG_INJECTION) {
4510 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4511 injectionState->pendingForegroundDispatches);
4512 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004513 nsecs_t remainingTimeout = endTime - now();
4514 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004515 if (DEBUG_INJECTION) {
4516 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4517 "dispatches to finish.");
4518 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004519 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004520 break;
4521 }
4522
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004523 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524 }
4525 }
4526 }
4527
4528 injectionState->release();
4529 } // release lock
4530
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004531 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004532 LOG(DEBUG) << "injectInputEvent - Finished with result "
4533 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004534 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004535
4536 return injectionResult;
4537}
4538
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004539std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004540 std::array<uint8_t, 32> calculatedHmac;
4541 std::unique_ptr<VerifiedInputEvent> result;
4542 switch (event.getType()) {
4543 case AINPUT_EVENT_TYPE_KEY: {
4544 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4545 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4546 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004547 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004548 break;
4549 }
4550 case AINPUT_EVENT_TYPE_MOTION: {
4551 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4552 VerifiedMotionEvent verifiedMotionEvent =
4553 verifiedMotionEventFromMotionEvent(motionEvent);
4554 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004555 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004556 break;
4557 }
4558 default: {
4559 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4560 return nullptr;
4561 }
4562 }
4563 if (calculatedHmac == INVALID_HMAC) {
4564 return nullptr;
4565 }
4566 if (calculatedHmac != event.getHmac()) {
4567 return nullptr;
4568 }
4569 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004570}
4571
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004572void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004573 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004574 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004576 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004577 LOG(DEBUG) << "Setting input event injection result to "
4578 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004579 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004580
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004581 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004582 // Log the outcome since the injector did not wait for the injection result.
4583 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004584 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004585 ALOGV("Asynchronous input event injection succeeded.");
4586 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004587 case InputEventInjectionResult::TARGET_MISMATCH:
4588 ALOGV("Asynchronous input event injection target mismatch.");
4589 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004590 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004591 ALOGW("Asynchronous input event injection failed.");
4592 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004593 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004594 ALOGW("Asynchronous input event injection timed out.");
4595 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004596 case InputEventInjectionResult::PENDING:
4597 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4598 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004599 }
4600 }
4601
4602 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004603 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004604 }
4605}
4606
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004607void InputDispatcher::transformMotionEntryForInjectionLocked(
4608 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004609 // Input injection works in the logical display coordinate space, but the input pipeline works
4610 // display space, so we need to transform the injected events accordingly.
4611 const auto it = mDisplayInfos.find(entry.displayId);
4612 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004613 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004614
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004615 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4616 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4617 const vec2 cursor =
4618 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4619 {entry.xCursorPosition, entry.yCursorPosition});
4620 entry.xCursorPosition = cursor.x;
4621 entry.yCursorPosition = cursor.y;
4622 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004623 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004624 entry.pointerCoords[i] =
4625 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4626 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004627 }
4628}
4629
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004630void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4631 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632 if (injectionState) {
4633 injectionState->pendingForegroundDispatches += 1;
4634 }
4635}
4636
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004637void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4638 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639 if (injectionState) {
4640 injectionState->pendingForegroundDispatches -= 1;
4641
4642 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004643 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004644 }
4645 }
4646}
4647
chaviw98318de2021-05-19 16:45:23 -05004648const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004649 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004650 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004651 auto it = mWindowHandlesByDisplay.find(displayId);
4652 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004653}
4654
chaviw98318de2021-05-19 16:45:23 -05004655sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004656 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004657 if (windowHandleToken == nullptr) {
4658 return nullptr;
4659 }
4660
Arthur Hungb92218b2018-08-14 12:00:21 +08004661 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004662 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4663 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004664 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004665 return windowHandle;
4666 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004667 }
4668 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004669 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004670}
4671
chaviw98318de2021-05-19 16:45:23 -05004672sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4673 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004674 if (windowHandleToken == nullptr) {
4675 return nullptr;
4676 }
4677
chaviw98318de2021-05-19 16:45:23 -05004678 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004679 if (windowHandle->getToken() == windowHandleToken) {
4680 return windowHandle;
4681 }
4682 }
4683 return nullptr;
4684}
4685
chaviw98318de2021-05-19 16:45:23 -05004686sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4687 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004688 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004689 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4690 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004691 if (handle->getId() == windowHandle->getId() &&
4692 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004693 if (windowHandle->getInfo()->displayId != it.first) {
4694 ALOGE("Found window %s in display %" PRId32
4695 ", but it should belong to display %" PRId32,
4696 windowHandle->getName().c_str(), it.first,
4697 windowHandle->getInfo()->displayId);
4698 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004699 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004700 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004701 }
4702 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004703 return nullptr;
4704}
4705
chaviw98318de2021-05-19 16:45:23 -05004706sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004707 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4708 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004709}
4710
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004711bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4712 const MotionEntry& motionEntry) const {
4713 const WindowInfo& info = *window->getInfo();
4714
4715 // Skip spy window targets that are not valid for targeted injection.
4716 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004717 return false;
4718 }
4719
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004720 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4721 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4722 return false;
4723 }
4724
4725 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4726 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4727 window->getName().c_str());
4728 return false;
4729 }
4730
4731 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004732 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004733 ALOGW("Not sending touch to %s because there's no corresponding connection",
4734 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004735 return false;
4736 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004737
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004738 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004739 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004740 return false;
4741 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004742
4743 // Drop events that can't be trusted due to occlusion
4744 const auto [x, y] = resolveTouchedPosition(motionEntry);
4745 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4746 if (!isTouchTrustedLocked(occlusionInfo)) {
4747 if (DEBUG_TOUCH_OCCLUSION) {
4748 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4749 for (const auto& log : occlusionInfo.debugInfo) {
4750 ALOGD("%s", log.c_str());
4751 }
4752 }
4753 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4754 occlusionInfo.obscuringUid);
4755 return false;
4756 }
4757
4758 // Drop touch events if requested by input feature
4759 if (shouldDropInput(motionEntry, window)) {
4760 return false;
4761 }
4762
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004763 return true;
4764}
4765
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004766std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4767 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004768 auto connectionIt = mConnectionsByToken.find(token);
4769 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004770 return nullptr;
4771 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004772 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004773}
4774
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004775void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004776 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4777 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004778 // Remove all handles on a display if there are no windows left.
4779 mWindowHandlesByDisplay.erase(displayId);
4780 return;
4781 }
4782
4783 // Since we compare the pointer of input window handles across window updates, we need
4784 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004785 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4786 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4787 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004788 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004789 }
4790
chaviw98318de2021-05-19 16:45:23 -05004791 std::vector<sp<WindowInfoHandle>> newHandles;
4792 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004793 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004794 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004795 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004796 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004797 const bool canReceiveInput =
4798 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4799 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004800 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004801 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004802 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004803 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004804 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004805 }
4806
4807 if (info->displayId != displayId) {
4808 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4809 handle->getName().c_str(), displayId, info->displayId);
4810 continue;
4811 }
4812
Robert Carredd13602020-04-13 17:24:34 -07004813 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4814 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004815 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004816 oldHandle->updateFrom(handle);
4817 newHandles.push_back(oldHandle);
4818 } else {
4819 newHandles.push_back(handle);
4820 }
4821 }
4822
4823 // Insert or replace
4824 mWindowHandlesByDisplay[displayId] = newHandles;
4825}
4826
Arthur Hung72d8dc32020-03-28 00:48:39 +00004827void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004828 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004829 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004830 { // acquire lock
4831 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004832 for (const auto& [displayId, handles] : handlesPerDisplay) {
4833 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004834 }
4835 }
4836 // Wake up poll loop since it may need to make new input dispatching choices.
4837 mLooper->wake();
4838}
4839
Arthur Hungb92218b2018-08-14 12:00:21 +08004840/**
4841 * Called from InputManagerService, update window handle list by displayId that can receive input.
4842 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4843 * If set an empty list, remove all handles from the specific display.
4844 * For focused handle, check if need to change and send a cancel event to previous one.
4845 * For removed handle, check if need to send a cancel event if already in touch.
4846 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004847void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004848 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004849 if (DEBUG_FOCUS) {
4850 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004851 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004852 windowList += iwh->getName() + " ";
4853 }
4854 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4855 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004856
Prabir Pradhand65552b2021-10-07 11:23:50 -07004857 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004858 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004859 const WindowInfo& info = *window->getInfo();
4860
4861 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004862 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004863 if (noInputWindow && window->getToken() != nullptr) {
4864 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4865 window->getName().c_str());
4866 window->releaseChannel();
4867 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004868
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004869 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004870 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4871 !info.inputConfig.test(
4872 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004873 "%s has feature SPY, but is not a trusted overlay.",
4874 window->getName().c_str());
4875
Prabir Pradhand65552b2021-10-07 11:23:50 -07004876 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004877 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4878 !info.inputConfig.test(
4879 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004880 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4881 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004882 }
4883
Arthur Hung72d8dc32020-03-28 00:48:39 +00004884 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004885 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004886
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004887 // Save the old windows' orientation by ID before it gets updated.
4888 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004889 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004890 oldWindowOrientations.emplace(handle->getId(),
4891 handle->getInfo()->transform.getOrientation());
4892 }
4893
chaviw98318de2021-05-19 16:45:23 -05004894 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004895
chaviw98318de2021-05-19 16:45:23 -05004896 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004897
Vishnu Nairc519ff72021-01-21 08:23:08 -08004898 std::optional<FocusResolver::FocusChanges> changes =
4899 mFocusResolver.setInputWindows(displayId, windowHandles);
4900 if (changes) {
4901 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004902 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004903
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004904 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4905 mTouchStatesByDisplay.find(displayId);
4906 if (stateIt != mTouchStatesByDisplay.end()) {
4907 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004908 for (size_t i = 0; i < state.windows.size();) {
4909 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004910 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004911 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004912 ALOGD("Touched window was removed: %s in display %" PRId32,
4913 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004914 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004915 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004916 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4917 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004918 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00004919 "touched window was removed");
4920 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004921 // Since we are about to drop the touch, cancel the events for the wallpaper as
4922 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004923 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004924 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4925 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004926 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004927 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004928 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004929 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004930 state.windows.erase(state.windows.begin() + i);
4931 } else {
4932 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933 }
4934 }
arthurhungb89ccb02020-12-30 16:19:01 +08004935
arthurhung6d4bed92021-03-17 11:59:33 +08004936 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004937 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004938 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004939 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004940 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004941 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4942 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004943 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004944 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004945 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004946
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004947 // Determine if the orientation of any of the input windows have changed, and cancel all
4948 // pointer events if necessary.
4949 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4950 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4951 if (newWindowHandle != nullptr &&
4952 newWindowHandle->getInfo()->transform.getOrientation() !=
4953 oldWindowOrientations[oldWindowHandle->getId()]) {
4954 std::shared_ptr<InputChannel> inputChannel =
4955 getInputChannelLocked(newWindowHandle->getToken());
4956 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004957 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004958 "touched window's orientation changed");
4959 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004960 }
4961 }
4962 }
4963
Arthur Hung72d8dc32020-03-28 00:48:39 +00004964 // Release information for windows that are no longer present.
4965 // This ensures that unused input channels are released promptly.
4966 // Otherwise, they might stick around until the window handle is destroyed
4967 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004968 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004969 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004970 if (DEBUG_FOCUS) {
4971 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004972 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004973 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004974 }
chaviw291d88a2019-02-14 10:33:58 -08004975 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004976}
4977
4978void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004979 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004980 if (DEBUG_FOCUS) {
4981 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4982 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4983 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004984 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004985 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004986 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004987 } // release lock
4988
4989 // Wake up poll loop since it may need to make new input dispatching choices.
4990 mLooper->wake();
4991}
4992
Vishnu Nair599f1412021-06-21 10:39:58 -07004993void InputDispatcher::setFocusedApplicationLocked(
4994 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4995 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4996 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4997
4998 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4999 return; // This application is already focused. No need to wake up or change anything.
5000 }
5001
5002 // Set the new application handle.
5003 if (inputApplicationHandle != nullptr) {
5004 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5005 } else {
5006 mFocusedApplicationHandlesByDisplay.erase(displayId);
5007 }
5008
5009 // No matter what the old focused application was, stop waiting on it because it is
5010 // no longer focused.
5011 resetNoFocusedWindowTimeoutLocked();
5012}
5013
Tiger Huang721e26f2018-07-24 22:26:19 +08005014/**
5015 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5016 * the display not specified.
5017 *
5018 * We track any unreleased events for each window. If a window loses the ability to receive the
5019 * released event, we will send a cancel event to it. So when the focused display is changed, we
5020 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5021 * display. The display-specified events won't be affected.
5022 */
5023void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005024 if (DEBUG_FOCUS) {
5025 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5026 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005027 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005028 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005029
5030 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005031 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005032 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005033 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005034 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005035 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005036 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005037 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005038 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005039 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005040 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005041 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5042 }
5043 }
5044 mFocusedDisplayId = displayId;
5045
Chris Ye3c2d6f52020-08-09 10:39:48 -07005046 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005047 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005048 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005049
Vishnu Nairad321cd2020-08-20 16:40:21 -07005050 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005051 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005052 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005053 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005054 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005055 }
5056 }
5057 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005058 } // release lock
5059
5060 // Wake up poll loop since it may need to make new input dispatching choices.
5061 mLooper->wake();
5062}
5063
Michael Wrightd02c5b62014-02-10 15:10:22 -08005064void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005065 if (DEBUG_FOCUS) {
5066 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005068
5069 bool changed;
5070 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005071 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005072
5073 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5074 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005075 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005076 }
5077
5078 if (mDispatchEnabled && !enabled) {
5079 resetAndDropEverythingLocked("dispatcher is being disabled");
5080 }
5081
5082 mDispatchEnabled = enabled;
5083 mDispatchFrozen = frozen;
5084 changed = true;
5085 } else {
5086 changed = false;
5087 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005088 } // release lock
5089
5090 if (changed) {
5091 // Wake up poll loop since it may need to make new input dispatching choices.
5092 mLooper->wake();
5093 }
5094}
5095
5096void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005097 if (DEBUG_FOCUS) {
5098 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5099 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005100
5101 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005102 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103
5104 if (mInputFilterEnabled == enabled) {
5105 return;
5106 }
5107
5108 mInputFilterEnabled = enabled;
5109 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5110 } // release lock
5111
5112 // Wake up poll loop since there might be work to do to drop everything.
5113 mLooper->wake();
5114}
5115
Antonio Kanteka042c022022-07-06 16:51:07 -07005116bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5117 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005118 bool needWake = false;
5119 {
5120 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005121 ALOGD_IF(DEBUG_TOUCH_MODE,
5122 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5123 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5124 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5125 mTouchModePerDisplay.count(displayId) == 0
5126 ? "not set"
5127 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5128
Antonio Kantek15beb512022-06-13 22:35:41 +00005129 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5130 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005131 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005132 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005133 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005134 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5135 !recentWindowsAreOwnedByLocked(pid, uid)) {
5136 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5137 "window nor none of the previously interacted window",
5138 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005139 return false;
5140 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005141 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005142 mTouchModePerDisplay[displayId] = inTouchMode;
5143 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5144 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005145 needWake = enqueueInboundEventLocked(std::move(entry));
5146 } // release lock
5147
5148 if (needWake) {
5149 mLooper->wake();
5150 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005151 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005152}
5153
Antonio Kantek48710e42022-03-24 14:19:30 -07005154bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5155 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5156 if (focusedToken == nullptr) {
5157 return false;
5158 }
5159 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5160 return isWindowOwnedBy(windowHandle, pid, uid);
5161}
5162
5163bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5164 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5165 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5166 const sp<WindowInfoHandle> windowHandle =
5167 getWindowHandleLocked(connectionToken);
5168 return isWindowOwnedBy(windowHandle, pid, uid);
5169 }) != mInteractionConnectionTokens.end();
5170}
5171
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005172void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5173 if (opacity < 0 || opacity > 1) {
5174 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5175 return;
5176 }
5177
5178 std::scoped_lock lock(mLock);
5179 mMaximumObscuringOpacityForTouch = opacity;
5180}
5181
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005182std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5183InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005184 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5185 for (TouchedWindow& w : state.windows) {
5186 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005187 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005188 }
5189 }
5190 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005191 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005192}
5193
arthurhungb89ccb02020-12-30 16:19:01 +08005194bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5195 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005196 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005197 if (DEBUG_FOCUS) {
5198 ALOGD("Trivial transfer to same window.");
5199 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005200 return true;
5201 }
5202
Michael Wrightd02c5b62014-02-10 15:10:22 -08005203 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005204 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005205
Arthur Hungabbb9d82021-09-01 14:52:30 +00005206 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005207 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005208 if (state == nullptr || touchedWindow == nullptr) {
5209 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005210 return false;
5211 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005212
Arthur Hungabbb9d82021-09-01 14:52:30 +00005213 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5214 if (toWindowHandle == nullptr) {
5215 ALOGW("Cannot transfer focus because to window not found.");
5216 return false;
5217 }
5218
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005219 if (DEBUG_FOCUS) {
5220 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005221 touchedWindow->windowHandle->getName().c_str(),
5222 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005223 }
5224
Arthur Hungabbb9d82021-09-01 14:52:30 +00005225 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005226 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005227 BitSet32 pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005228 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005229 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005230
Arthur Hungabbb9d82021-09-01 14:52:30 +00005231 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005232 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005233 ftl::Flags<InputTarget::Flags> newTargetFlags =
5234 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005235 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005236 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005237 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005238 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005239
Arthur Hungabbb9d82021-09-01 14:52:30 +00005240 // Store the dragging window.
5241 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005242 if (pointerIds.count() != 1) {
5243 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5244 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005245 return false;
5246 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005247 // Track the pointer id for drag window and generate the drag state.
5248 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005249 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005250 }
5251
Arthur Hungabbb9d82021-09-01 14:52:30 +00005252 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005253 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5254 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005255 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005256 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005257 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005258 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005259 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005260 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005261 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5262 newTargetFlags);
5263
5264 // Check if the wallpaper window should deliver the corresponding event.
5265 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5266 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005267 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005268 } // release lock
5269
5270 // Wake up poll loop since it may need to make new input dispatching choices.
5271 mLooper->wake();
5272 return true;
5273}
5274
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005275/**
5276 * Get the touched foreground window on the given display.
5277 * Return null if there are no windows touched on that display, or if more than one foreground
5278 * window is being touched.
5279 */
5280sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5281 auto stateIt = mTouchStatesByDisplay.find(displayId);
5282 if (stateIt == mTouchStatesByDisplay.end()) {
5283 ALOGI("No touch state on display %" PRId32, displayId);
5284 return nullptr;
5285 }
5286
5287 const TouchState& state = stateIt->second;
5288 sp<WindowInfoHandle> touchedForegroundWindow;
5289 // If multiple foreground windows are touched, return nullptr
5290 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005291 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005292 if (touchedForegroundWindow != nullptr) {
5293 ALOGI("Two or more foreground windows: %s and %s",
5294 touchedForegroundWindow->getName().c_str(),
5295 window.windowHandle->getName().c_str());
5296 return nullptr;
5297 }
5298 touchedForegroundWindow = window.windowHandle;
5299 }
5300 }
5301 return touchedForegroundWindow;
5302}
5303
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005304// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005305bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005306 sp<IBinder> fromToken;
5307 { // acquire lock
5308 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005309 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005310 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005311 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5312 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005313 return false;
5314 }
5315
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005316 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5317 if (from == nullptr) {
5318 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5319 return false;
5320 }
5321
5322 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005323 } // release lock
5324
5325 return transferTouchFocus(fromToken, destChannelToken);
5326}
5327
Michael Wrightd02c5b62014-02-10 15:10:22 -08005328void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005329 if (DEBUG_FOCUS) {
5330 ALOGD("Resetting and dropping all events (%s).", reason);
5331 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005332
Michael Wrightfb04fd52022-11-24 22:31:11 +00005333 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005334 synthesizeCancelationEventsForAllConnectionsLocked(options);
5335
5336 resetKeyRepeatLocked();
5337 releasePendingEventLocked();
5338 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005339 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005340
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005341 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005342 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005343 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005344}
5345
5346void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005347 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005348 dumpDispatchStateLocked(dump);
5349
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005350 std::istringstream stream(dump);
5351 std::string line;
5352
5353 while (std::getline(stream, line, '\n')) {
5354 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005355 }
5356}
5357
Prabir Pradhan99987712020-11-10 18:43:05 -08005358std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5359 std::string dump;
5360
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005361 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5362 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005363
5364 std::string windowName = "None";
5365 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005366 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005367 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5368 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5369 : "token has capture without window";
5370 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005371 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005372
5373 return dump;
5374}
5375
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005376void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005377 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5378 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5379 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005380 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005381
Tiger Huang721e26f2018-07-24 22:26:19 +08005382 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5383 dump += StringPrintf(INDENT "FocusedApplications:\n");
5384 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5385 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005386 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005387 const std::chrono::duration timeout =
5388 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005389 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005390 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005391 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005393 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005394 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005395 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005396
Vishnu Nairc519ff72021-01-21 08:23:08 -08005397 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005398 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005399
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005400 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005401 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005402 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005403 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5404 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005405 }
5406 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005407 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408 }
5409
arthurhung6d4bed92021-03-17 11:59:33 +08005410 if (mDragState) {
5411 dump += StringPrintf(INDENT "DragState:\n");
5412 mDragState->dump(dump, INDENT2);
5413 }
5414
Arthur Hungb92218b2018-08-14 12:00:21 +08005415 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005416 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5417 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5418 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5419 const auto& displayInfo = it->second;
5420 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5421 displayInfo.logicalHeight);
5422 displayInfo.transform.dump(dump, "transform", INDENT4);
5423 } else {
5424 dump += INDENT2 "No DisplayInfo found!\n";
5425 }
5426
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005427 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005428 dump += INDENT2 "Windows:\n";
5429 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005430 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5431 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005432
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005433 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005434 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005435 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005436 "applicationInfo.name=%s, "
5437 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005438 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005439 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005440 windowInfo->displayId,
5441 windowInfo->inputConfig.string().c_str(),
5442 windowInfo->alpha, windowInfo->frameLeft,
5443 windowInfo->frameTop, windowInfo->frameRight,
5444 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005445 windowInfo->applicationInfo.name.c_str(),
5446 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005447 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005448 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005449 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005450 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005451 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005452 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005453 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005454 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005455 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005456 }
5457 } else {
5458 dump += INDENT2 "Windows: <none>\n";
5459 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460 }
5461 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005462 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005463 }
5464
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005465 if (!mGlobalMonitorsByDisplay.empty()) {
5466 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5467 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005468 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005469 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005470 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005471 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005472 }
5473
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005474 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005475
5476 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005477 if (!mRecentQueue.empty()) {
5478 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005479 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005480 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005481 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005482 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005483 }
5484 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005485 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005486 }
5487
5488 // Dump event currently being dispatched.
5489 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005490 dump += INDENT "PendingEvent:\n";
5491 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005492 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005493 dump += StringPrintf(", age=%" PRId64 "ms\n",
5494 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005495 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005496 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497 }
5498
5499 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005500 if (!mInboundQueue.empty()) {
5501 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005502 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005503 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005504 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005505 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005506 }
5507 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005508 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005509 }
5510
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005511 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005512 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005513 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005514 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005515 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005516 }
5517 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005518 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005519 }
5520
Prabir Pradhancef936d2021-07-21 16:17:52 +00005521 if (!mCommandQueue.empty()) {
5522 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5523 } else {
5524 dump += INDENT "CommandQueue: <empty>\n";
5525 }
5526
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005527 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005528 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005529 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005530 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005531 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005532 connection->inputChannel->getFd().get(),
5533 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005534 connection->getWindowName().c_str(),
5535 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005536 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005537
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005538 if (!connection->outboundQueue.empty()) {
5539 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5540 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005541 dump += dumpQueue(connection->outboundQueue, currentTime);
5542
Michael Wrightd02c5b62014-02-10 15:10:22 -08005543 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005544 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005545 }
5546
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005547 if (!connection->waitQueue.empty()) {
5548 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5549 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005550 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005551 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005552 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005553 }
5554 }
5555 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005556 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005557 }
5558
5559 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005560 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5561 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005563 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005564 }
5565
Antonio Kantek15beb512022-06-13 22:35:41 +00005566 if (!mTouchModePerDisplay.empty()) {
5567 dump += INDENT "TouchModePerDisplay:\n";
5568 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5569 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5570 std::to_string(touchMode).c_str());
5571 }
5572 } else {
5573 dump += INDENT "TouchModePerDisplay: <none>\n";
5574 }
5575
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005576 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005577 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5578 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5579 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005580 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005581 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005582}
5583
Michael Wright3dd60e22019-03-27 22:06:44 +00005584void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5585 const size_t numMonitors = monitors.size();
5586 for (size_t i = 0; i < numMonitors; i++) {
5587 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005588 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005589 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5590 dump += "\n";
5591 }
5592}
5593
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005594class LooperEventCallback : public LooperCallback {
5595public:
5596 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5597 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5598
5599private:
5600 std::function<int(int events)> mCallback;
5601};
5602
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005603Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005604 if (DEBUG_CHANNEL_CREATION) {
5605 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5606 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005608 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005609 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005610 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005611
5612 if (result) {
5613 return base::Error(result) << "Failed to open input channel pair with name " << name;
5614 }
5615
Michael Wrightd02c5b62014-02-10 15:10:22 -08005616 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005617 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005618 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005619 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005620 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005621 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005622
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005623 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5624 ALOGE("Created a new connection, but the token %p is already known", token.get());
5625 }
5626 mConnectionsByToken.emplace(token, connection);
5627
5628 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5629 this, std::placeholders::_1, token);
5630
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005631 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5632 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005633 } // release lock
5634
5635 // Wake the looper because some connections have changed.
5636 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005637 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005638}
5639
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005640Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005641 const std::string& name,
5642 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005643 std::shared_ptr<InputChannel> serverChannel;
5644 std::unique_ptr<InputChannel> clientChannel;
5645 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5646 if (result) {
5647 return base::Error(result) << "Failed to open input channel pair with name " << name;
5648 }
5649
Michael Wright3dd60e22019-03-27 22:06:44 +00005650 { // acquire lock
5651 std::scoped_lock _l(mLock);
5652
5653 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005654 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5655 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005656 }
5657
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005658 sp<Connection> connection =
5659 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005660 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005661 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005662
5663 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5664 ALOGE("Created a new connection, but the token %p is already known", token.get());
5665 }
5666 mConnectionsByToken.emplace(token, connection);
5667 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5668 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005669
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005670 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005671
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005672 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5673 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005674 }
Garfield Tan15601662020-09-22 15:32:38 -07005675
Michael Wright3dd60e22019-03-27 22:06:44 +00005676 // Wake the looper because some connections have changed.
5677 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005678 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005679}
5680
Garfield Tan15601662020-09-22 15:32:38 -07005681status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005682 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005683 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005684
Garfield Tan15601662020-09-22 15:32:38 -07005685 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005686 if (status) {
5687 return status;
5688 }
5689 } // release lock
5690
5691 // Wake the poll loop because removing the connection may have changed the current
5692 // synchronization state.
5693 mLooper->wake();
5694 return OK;
5695}
5696
Garfield Tan15601662020-09-22 15:32:38 -07005697status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5698 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005699 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005700 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005701 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005702 return BAD_VALUE;
5703 }
5704
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005705 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005706
Michael Wrightd02c5b62014-02-10 15:10:22 -08005707 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005708 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005709 }
5710
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005711 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005712
5713 nsecs_t currentTime = now();
5714 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5715
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005716 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005717 return OK;
5718}
5719
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005720void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005721 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5722 auto& [displayId, monitors] = *it;
5723 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5724 return monitor.inputChannel->getConnectionToken() == connectionToken;
5725 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005726
Michael Wright3dd60e22019-03-27 22:06:44 +00005727 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005728 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005729 } else {
5730 ++it;
5731 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005732 }
5733}
5734
Michael Wright3dd60e22019-03-27 22:06:44 +00005735status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005736 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005737 return pilferPointersLocked(token);
5738}
Michael Wright3dd60e22019-03-27 22:06:44 +00005739
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005740status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005741 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5742 if (!requestingChannel) {
5743 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5744 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005745 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005746
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005747 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07005748 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.isEmpty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005749 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5750 " Ignoring.");
5751 return BAD_VALUE;
5752 }
5753
5754 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005755 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005756 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005757 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005758 "input channel stole pointer stream");
5759 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005760 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005761 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005762 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005763 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005764 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005765 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005766 if (channel != nullptr && channel->getConnectionToken() != token) {
5767 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5768 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5769 canceledWindows += channel->getName();
5770 }
5771 }
5772 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5773 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5774 canceledWindows.c_str());
5775
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005776 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005777 // This only blocks relevant pointers to be sent to other windows
5778 window.isPilferingPointers = true;
5779
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005780 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005781 return OK;
5782}
5783
Prabir Pradhan99987712020-11-10 18:43:05 -08005784void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5785 { // acquire lock
5786 std::scoped_lock _l(mLock);
5787 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005788 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005789 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5790 windowHandle != nullptr ? windowHandle->getName().c_str()
5791 : "token without window");
5792 }
5793
Vishnu Nairc519ff72021-01-21 08:23:08 -08005794 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005795 if (focusedToken != windowToken) {
5796 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5797 enabled ? "enable" : "disable");
5798 return;
5799 }
5800
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005801 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005802 ALOGW("Ignoring request to %s Pointer Capture: "
5803 "window has %s requested pointer capture.",
5804 enabled ? "enable" : "disable", enabled ? "already" : "not");
5805 return;
5806 }
5807
Christine Franksb768bb42021-11-29 12:11:31 -08005808 if (enabled) {
5809 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5810 mIneligibleDisplaysForPointerCapture.end(),
5811 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5812 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5813 return;
5814 }
5815 }
5816
Prabir Pradhan99987712020-11-10 18:43:05 -08005817 setPointerCaptureLocked(enabled);
5818 } // release lock
5819
5820 // Wake the thread to process command entries.
5821 mLooper->wake();
5822}
5823
Christine Franksb768bb42021-11-29 12:11:31 -08005824void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5825 { // acquire lock
5826 std::scoped_lock _l(mLock);
5827 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5828 if (!isEligible) {
5829 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5830 }
5831 } // release lock
5832}
5833
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005834std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5835 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005836 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005837 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005838 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005839 }
5840 }
5841 }
5842 return std::nullopt;
5843}
5844
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005845sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005846 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005847 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005848 }
5849
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005850 for (const auto& [token, connection] : mConnectionsByToken) {
5851 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005852 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005853 }
5854 }
Robert Carr4e670e52018-08-15 13:26:12 -07005855
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005856 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005857}
5858
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005859std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5860 sp<Connection> connection = getConnectionLocked(connectionToken);
5861 if (connection == nullptr) {
5862 return "<nullptr>";
5863 }
5864 return connection->getInputChannelName();
5865}
5866
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005867void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005868 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005869 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005870}
5871
Prabir Pradhancef936d2021-07-21 16:17:52 +00005872void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5873 const sp<Connection>& connection, uint32_t seq,
5874 bool handled, nsecs_t consumeTime) {
5875 // Handle post-event policy actions.
5876 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5877 if (dispatchEntryIt == connection->waitQueue.end()) {
5878 return;
5879 }
5880 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5881 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5882 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5883 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5884 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5885 }
5886 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5887 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5888 connection->inputChannel->getConnectionToken(),
5889 dispatchEntry->deliveryTime, consumeTime, finishTime);
5890 }
5891
5892 bool restartEvent;
5893 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5894 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5895 restartEvent =
5896 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5897 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5898 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5899 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5900 handled);
5901 } else {
5902 restartEvent = false;
5903 }
5904
5905 // Dequeue the event and start the next cycle.
5906 // Because the lock might have been released, it is possible that the
5907 // contents of the wait queue to have been drained, so we need to double-check
5908 // a few things.
5909 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5910 if (dispatchEntryIt != connection->waitQueue.end()) {
5911 dispatchEntry = *dispatchEntryIt;
5912 connection->waitQueue.erase(dispatchEntryIt);
5913 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5914 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5915 if (!connection->responsive) {
5916 connection->responsive = isConnectionResponsive(*connection);
5917 if (connection->responsive) {
5918 // The connection was unresponsive, and now it's responsive.
5919 processConnectionResponsiveLocked(*connection);
5920 }
5921 }
5922 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005923 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005924 connection->outboundQueue.push_front(dispatchEntry);
5925 traceOutboundQueueLength(*connection);
5926 } else {
5927 releaseDispatchEntry(dispatchEntry);
5928 }
5929 }
5930
5931 // Start the next dispatch cycle for this connection.
5932 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005933}
5934
Prabir Pradhancef936d2021-07-21 16:17:52 +00005935void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5936 const sp<IBinder>& newToken) {
5937 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5938 scoped_unlock unlock(mLock);
5939 mPolicy->notifyFocusChanged(oldToken, newToken);
5940 };
5941 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005942}
5943
Prabir Pradhancef936d2021-07-21 16:17:52 +00005944void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5945 auto command = [this, token, x, y]() REQUIRES(mLock) {
5946 scoped_unlock unlock(mLock);
5947 mPolicy->notifyDropWindow(token, x, y);
5948 };
5949 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005950}
5951
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005952void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5953 if (connection == nullptr) {
5954 LOG_ALWAYS_FATAL("Caller must check for nullness");
5955 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005956 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5957 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005958 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005959 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005960 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005961 return;
5962 }
5963 /**
5964 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5965 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5966 * has changed. This could cause newer entries to time out before the already dispatched
5967 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5968 * processes the events linearly. So providing information about the oldest entry seems to be
5969 * most useful.
5970 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005971 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005972 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5973 std::string reason =
5974 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005975 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005976 ns2ms(currentWait),
5977 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005978 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005979 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005980
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005981 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5982
5983 // Stop waking up for events on this connection, it is already unresponsive
5984 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005985}
5986
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005987void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5988 std::string reason =
5989 StringPrintf("%s does not have a focused window", application->getName().c_str());
5990 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005991
Prabir Pradhancef936d2021-07-21 16:17:52 +00005992 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5993 scoped_unlock unlock(mLock);
5994 mPolicy->notifyNoFocusedWindowAnr(application);
5995 };
5996 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005997}
5998
chaviw98318de2021-05-19 16:45:23 -05005999void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006000 const std::string& reason) {
6001 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6002 updateLastAnrStateLocked(windowLabel, reason);
6003}
6004
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006005void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6006 const std::string& reason) {
6007 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006008 updateLastAnrStateLocked(windowLabel, reason);
6009}
6010
6011void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6012 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006013 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006014 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006015 struct tm tm;
6016 localtime_r(&t, &tm);
6017 char timestr[64];
6018 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006019 mLastAnrState.clear();
6020 mLastAnrState += INDENT "ANR:\n";
6021 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006022 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6023 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006024 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006025}
6026
Prabir Pradhancef936d2021-07-21 16:17:52 +00006027void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6028 KeyEntry& entry) {
6029 const KeyEvent event = createKeyEvent(entry);
6030 nsecs_t delay = 0;
6031 { // release lock
6032 scoped_unlock unlock(mLock);
6033 android::base::Timer t;
6034 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
6035 entry.policyFlags);
6036 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6037 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6038 std::to_string(t.duration().count()).c_str());
6039 }
6040 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006041
6042 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006043 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006044 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006045 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006046 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006047 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006048 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006049 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006050}
6051
Prabir Pradhancef936d2021-07-21 16:17:52 +00006052void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006053 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006054 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006055 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006056 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006057 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006058 };
6059 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006060}
6061
Prabir Pradhanedd96402022-02-15 01:46:16 -08006062void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6063 std::optional<int32_t> pid) {
6064 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006065 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006066 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006067 };
6068 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006069}
6070
6071/**
6072 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6073 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6074 * command entry to the command queue.
6075 */
6076void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6077 std::string reason) {
6078 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006079 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006080 if (connection.monitor) {
6081 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6082 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006083 pid = findMonitorPidByTokenLocked(connectionToken);
6084 } else {
6085 // The connection is a window
6086 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6087 reason.c_str());
6088 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6089 if (handle != nullptr) {
6090 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006091 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006092 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006093 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006094}
6095
6096/**
6097 * Tell the policy that a connection has become responsive so that it can stop ANR.
6098 */
6099void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6100 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006101 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006102 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006103 pid = findMonitorPidByTokenLocked(connectionToken);
6104 } else {
6105 // The connection is a window
6106 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6107 if (handle != nullptr) {
6108 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006109 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006110 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006111 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006112}
6113
Prabir Pradhancef936d2021-07-21 16:17:52 +00006114bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006115 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006116 KeyEntry& keyEntry, bool handled) {
6117 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006118 if (!handled) {
6119 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006120 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006121 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006122 return false;
6123 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006124
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006125 // Get the fallback key state.
6126 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006127 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006128 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006129 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006130 connection->inputState.removeFallbackKey(originalKeyCode);
6131 }
6132
6133 if (handled || !dispatchEntry->hasForegroundTarget()) {
6134 // If the application handles the original key for which we previously
6135 // generated a fallback or if the window is not a foreground window,
6136 // then cancel the associated fallback key, if any.
6137 if (fallbackKeyCode != -1) {
6138 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006139 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6140 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6141 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6142 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6143 keyEntry.policyFlags);
6144 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006145 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006146 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006147
6148 mLock.unlock();
6149
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006150 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006151 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006152
6153 mLock.lock();
6154
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006155 // Cancel the fallback key.
6156 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006157 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006158 "application handled the original non-fallback key "
6159 "or is no longer a foreground target, "
6160 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006161 options.keyCode = fallbackKeyCode;
6162 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006163 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006164 connection->inputState.removeFallbackKey(originalKeyCode);
6165 }
6166 } else {
6167 // If the application did not handle a non-fallback key, first check
6168 // that we are in a good state to perform unhandled key event processing
6169 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006170 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006171 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006172 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6173 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6174 "since this is not an initial down. "
6175 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6176 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6177 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006178 return false;
6179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006180
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006181 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006182 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6183 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6184 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6185 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6186 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006187 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006188
6189 mLock.unlock();
6190
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006191 bool fallback =
6192 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006193 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006194
6195 mLock.lock();
6196
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006197 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006198 connection->inputState.removeFallbackKey(originalKeyCode);
6199 return false;
6200 }
6201
6202 // Latch the fallback keycode for this key on an initial down.
6203 // The fallback keycode cannot change at any other point in the lifecycle.
6204 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006205 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006206 fallbackKeyCode = event.getKeyCode();
6207 } else {
6208 fallbackKeyCode = AKEYCODE_UNKNOWN;
6209 }
6210 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6211 }
6212
6213 ALOG_ASSERT(fallbackKeyCode != -1);
6214
6215 // Cancel the fallback key if the policy decides not to send it anymore.
6216 // We will continue to dispatch the key to the policy but we will no
6217 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006218 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6219 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006220 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6221 if (fallback) {
6222 ALOGD("Unhandled key event: Policy requested to send key %d"
6223 "as a fallback for %d, but on the DOWN it had requested "
6224 "to send %d instead. Fallback canceled.",
6225 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6226 } else {
6227 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6228 "but on the DOWN it had requested to send %d. "
6229 "Fallback canceled.",
6230 originalKeyCode, fallbackKeyCode);
6231 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006232 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006233
Michael Wrightfb04fd52022-11-24 22:31:11 +00006234 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006235 "canceling fallback, policy no longer desires it");
6236 options.keyCode = fallbackKeyCode;
6237 synthesizeCancelationEventsForConnectionLocked(connection, options);
6238
6239 fallback = false;
6240 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006241 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006242 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006243 }
6244 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006245
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006246 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6247 {
6248 std::string msg;
6249 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6250 connection->inputState.getFallbackKeys();
6251 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6252 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6253 }
6254 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6255 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006256 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006257 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006258
6259 if (fallback) {
6260 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006261 keyEntry.eventTime = event.getEventTime();
6262 keyEntry.deviceId = event.getDeviceId();
6263 keyEntry.source = event.getSource();
6264 keyEntry.displayId = event.getDisplayId();
6265 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6266 keyEntry.keyCode = fallbackKeyCode;
6267 keyEntry.scanCode = event.getScanCode();
6268 keyEntry.metaState = event.getMetaState();
6269 keyEntry.repeatCount = event.getRepeatCount();
6270 keyEntry.downTime = event.getDownTime();
6271 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006272
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006273 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6274 ALOGD("Unhandled key event: Dispatching fallback key. "
6275 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6276 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6277 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006278 return true; // restart the event
6279 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006280 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6281 ALOGD("Unhandled key event: No fallback key.");
6282 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006283
6284 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006285 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006286 }
6287 }
6288 return false;
6289}
6290
Prabir Pradhancef936d2021-07-21 16:17:52 +00006291bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006292 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006293 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006294 return false;
6295}
6296
Michael Wrightd02c5b62014-02-10 15:10:22 -08006297void InputDispatcher::traceInboundQueueLengthLocked() {
6298 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006299 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006300 }
6301}
6302
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006303void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006304 if (ATRACE_ENABLED()) {
6305 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006306 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6307 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006308 }
6309}
6310
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006311void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006312 if (ATRACE_ENABLED()) {
6313 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006314 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6315 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006316 }
6317}
6318
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006319void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006320 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006321
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006322 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006323 dumpDispatchStateLocked(dump);
6324
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006325 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006326 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006327 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006328 }
6329}
6330
6331void InputDispatcher::monitor() {
6332 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006333 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006334 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006335 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006336}
6337
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006338/**
6339 * Wake up the dispatcher and wait until it processes all events and commands.
6340 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6341 * this method can be safely called from any thread, as long as you've ensured that
6342 * the work you are interested in completing has already been queued.
6343 */
6344bool InputDispatcher::waitForIdle() {
6345 /**
6346 * Timeout should represent the longest possible time that a device might spend processing
6347 * events and commands.
6348 */
6349 constexpr std::chrono::duration TIMEOUT = 100ms;
6350 std::unique_lock lock(mLock);
6351 mLooper->wake();
6352 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6353 return result == std::cv_status::no_timeout;
6354}
6355
Vishnu Naire798b472020-07-23 13:52:21 -07006356/**
6357 * Sets focus to the window identified by the token. This must be called
6358 * after updating any input window handles.
6359 *
6360 * Params:
6361 * request.token - input channel token used to identify the window that should gain focus.
6362 * request.focusedToken - the token that the caller expects currently to be focused. If the
6363 * specified token does not match the currently focused window, this request will be dropped.
6364 * If the specified focused token matches the currently focused window, the call will succeed.
6365 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6366 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6367 * when requesting the focus change. This determines which request gets
6368 * precedence if there is a focus change request from another source such as pointer down.
6369 */
Vishnu Nair958da932020-08-21 17:12:37 -07006370void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6371 { // acquire lock
6372 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006373 std::optional<FocusResolver::FocusChanges> changes =
6374 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6375 if (changes) {
6376 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006377 }
6378 } // release lock
6379 // Wake up poll loop since it may need to make new input dispatching choices.
6380 mLooper->wake();
6381}
6382
Vishnu Nairc519ff72021-01-21 08:23:08 -08006383void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6384 if (changes.oldFocus) {
6385 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006386 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006387 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006388 "focus left window");
6389 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006390 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006391 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006392 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006393 if (changes.newFocus) {
6394 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006395 }
6396
Prabir Pradhan99987712020-11-10 18:43:05 -08006397 // If a window has pointer capture, then it must have focus. We need to ensure that this
6398 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6399 // If the window loses focus before it loses pointer capture, then the window can be in a state
6400 // where it has pointer capture but not focus, violating the contract. Therefore we must
6401 // dispatch the pointer capture event before the focus event. Since focus events are added to
6402 // the front of the queue (above), we add the pointer capture event to the front of the queue
6403 // after the focus events are added. This ensures the pointer capture event ends up at the
6404 // front.
6405 disablePointerCaptureForcedLocked();
6406
Vishnu Nairc519ff72021-01-21 08:23:08 -08006407 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006408 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006409 }
6410}
Vishnu Nair958da932020-08-21 17:12:37 -07006411
Prabir Pradhan99987712020-11-10 18:43:05 -08006412void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006413 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006414 return;
6415 }
6416
6417 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6418
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006419 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006420 setPointerCaptureLocked(false);
6421 }
6422
6423 if (!mWindowTokenWithPointerCapture) {
6424 // No need to send capture changes because no window has capture.
6425 return;
6426 }
6427
6428 if (mPendingEvent != nullptr) {
6429 // Move the pending event to the front of the queue. This will give the chance
6430 // for the pending event to be dropped if it is a captured event.
6431 mInboundQueue.push_front(mPendingEvent);
6432 mPendingEvent = nullptr;
6433 }
6434
6435 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006436 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006437 mInboundQueue.push_front(std::move(entry));
6438}
6439
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006440void InputDispatcher::setPointerCaptureLocked(bool enable) {
6441 mCurrentPointerCaptureRequest.enable = enable;
6442 mCurrentPointerCaptureRequest.seq++;
6443 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006444 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006445 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006446 };
6447 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006448}
6449
Vishnu Nair599f1412021-06-21 10:39:58 -07006450void InputDispatcher::displayRemoved(int32_t displayId) {
6451 { // acquire lock
6452 std::scoped_lock _l(mLock);
6453 // Set an empty list to remove all handles from the specific display.
6454 setInputWindowsLocked(/* window handles */ {}, displayId);
6455 setFocusedApplicationLocked(displayId, nullptr);
6456 // Call focus resolver to clean up stale requests. This must be called after input windows
6457 // have been removed for the removed display.
6458 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006459 // Reset pointer capture eligibility, regardless of previous state.
6460 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006461 // Remove the associated touch mode state.
6462 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006463 } // release lock
6464
6465 // Wake up poll loop since it may need to make new input dispatching choices.
6466 mLooper->wake();
6467}
6468
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006469void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6470 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006471 // The listener sends the windows as a flattened array. Separate the windows by display for
6472 // more convenient parsing.
6473 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006474 for (const auto& info : windowInfos) {
6475 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006476 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006477 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006478
6479 { // acquire lock
6480 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006481
6482 // Ensure that we have an entry created for all existing displays so that if a displayId has
6483 // no windows, we can tell that the windows were removed from the display.
6484 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6485 handlesPerDisplay[displayId];
6486 }
6487
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006488 mDisplayInfos.clear();
6489 for (const auto& displayInfo : displayInfos) {
6490 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6491 }
6492
6493 for (const auto& [displayId, handles] : handlesPerDisplay) {
6494 setInputWindowsLocked(handles, displayId);
6495 }
6496 }
6497 // Wake up poll loop since it may need to make new input dispatching choices.
6498 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006499}
6500
Vishnu Nair062a8672021-09-03 16:07:44 -07006501bool InputDispatcher::shouldDropInput(
6502 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006503 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6504 (windowHandle->getInfo()->inputConfig.test(
6505 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006506 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006507 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6508 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006509 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006510 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006511 windowHandle->getInfo()->displayId);
6512 return true;
6513 }
6514 return false;
6515}
6516
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006517void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6518 const std::vector<gui::WindowInfo>& windowInfos,
6519 const std::vector<DisplayInfo>& displayInfos) {
6520 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6521}
6522
Arthur Hungdfd528e2021-12-08 13:23:04 +00006523void InputDispatcher::cancelCurrentTouch() {
6524 {
6525 std::scoped_lock _l(mLock);
6526 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006527 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006528 "cancel current touch");
6529 synthesizeCancelationEventsForAllConnectionsLocked(options);
6530
6531 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006532 }
6533 // Wake up poll loop since there might be work to do.
6534 mLooper->wake();
6535}
6536
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006537void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6538 std::scoped_lock _l(mLock);
6539 mMonitorDispatchingTimeout = timeout;
6540}
6541
Arthur Hungc539dbb2022-12-08 07:45:36 +00006542void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6543 const sp<WindowInfoHandle>& oldWindowHandle,
6544 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006545 TouchState& state, int32_t pointerId,
6546 std::vector<InputTarget>& targets) {
6547 BitSet32 pointerIds;
6548 pointerIds.markBit(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006549 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6550 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6551 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6552 newWindowHandle->getInfo()->inputConfig.test(
6553 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6554 const sp<WindowInfoHandle> oldWallpaper =
6555 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6556 const sp<WindowInfoHandle> newWallpaper =
6557 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6558 if (oldWallpaper == newWallpaper) {
6559 return;
6560 }
6561
6562 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006563 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6564 addWindowTargetLocked(oldWallpaper,
6565 oldTouchedWindow.targetFlags |
6566 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6567 pointerIds, oldTouchedWindow.firstDownTimeInTarget, targets);
6568 state.removeTouchedPointerFromWindow(pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006569 }
6570
6571 if (newWallpaper != nullptr) {
6572 state.addOrUpdateWindow(newWallpaper,
6573 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6574 InputTarget::Flags::WINDOW_IS_OBSCURED |
6575 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6576 pointerIds);
6577 }
6578}
6579
6580void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6581 ftl::Flags<InputTarget::Flags> newTargetFlags,
6582 const sp<WindowInfoHandle> fromWindowHandle,
6583 const sp<WindowInfoHandle> toWindowHandle,
6584 TouchState& state, const BitSet32& pointerIds) {
6585 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6586 fromWindowHandle->getInfo()->inputConfig.test(
6587 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6588 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6589 toWindowHandle->getInfo()->inputConfig.test(
6590 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6591
6592 const sp<WindowInfoHandle> oldWallpaper =
6593 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6594 const sp<WindowInfoHandle> newWallpaper =
6595 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6596 if (oldWallpaper == newWallpaper) {
6597 return;
6598 }
6599
6600 if (oldWallpaper != nullptr) {
6601 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6602 "transferring touch focus to another window");
6603 state.removeWindowByToken(oldWallpaper->getToken());
6604 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6605 }
6606
6607 if (newWallpaper != nullptr) {
6608 nsecs_t downTimeInTarget = now();
6609 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6610 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6611 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6612 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6613 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
6614 sp<Connection> wallpaperConnection = getConnectionLocked(newWallpaper->getToken());
6615 if (wallpaperConnection != nullptr) {
6616 sp<Connection> toConnection = getConnectionLocked(toWindowHandle->getToken());
6617 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6618 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6619 wallpaperFlags);
6620 }
6621 }
6622}
6623
6624sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6625 const sp<WindowInfoHandle>& windowHandle) const {
6626 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6627 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6628 bool foundWindow = false;
6629 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6630 if (!foundWindow && otherHandle != windowHandle) {
6631 continue;
6632 }
6633 if (windowHandle == otherHandle) {
6634 foundWindow = true;
6635 continue;
6636 }
6637
6638 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6639 return otherHandle;
6640 }
6641 }
6642 return nullptr;
6643}
6644
Garfield Tane84e6f92019-08-29 17:28:41 -07006645} // namespace android::inputdispatcher