blob: a97fda0440c2ded920f331d046644ded3f574571 [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 Vishniakou719f5062022-12-07 12:25:26 -08002444 std::vector<TouchedWindow> hoveringWindows =
2445 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2446 for (const TouchedWindow& touchedWindow : hoveringWindows) {
2447 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2448 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2449 targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002450 }
Siarhei Vishniakou719f5062022-12-07 12:25:26 -08002451
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002452 // Ensure that we have at least one foreground window or at least one window that cannot be a
2453 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2454 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2455 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002456 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2457 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002458 return !canReceiveForegroundTouches(
2459 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002460 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002461 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002462 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2463 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002464 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002465 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466 }
2467
Prabir Pradhan5735a322022-04-11 17:23:34 +00002468 // Ensure that all touched windows are valid for injection.
2469 if (entry.injectionState != nullptr) {
2470 std::string errs;
2471 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002472 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002473 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2474 // dispatched to any uid, since the coords will be zeroed out later.
2475 continue;
2476 }
2477 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2478 if (err) errs += "\n - " + *err;
2479 }
2480 if (!errs.empty()) {
2481 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2482 "%d:%s",
2483 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002484 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002485 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002486 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002487 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002488
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002489 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2490 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002492 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002493 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002494 if (foregroundWindowHandle) {
2495 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002496 for (InputTarget& target : targets) {
2497 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2498 sp<WindowInfoHandle> targetWindow =
2499 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2500 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2501 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002502 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503 }
2504 }
2505 }
2506 }
2507
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002508 // Success! Output targets from the touch state.
2509 tempTouchState.clearWindowsWithoutPointers();
2510 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
2511 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2512 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2513 targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002514 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002515
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002516 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002517
Michael Wrightd02c5b62014-02-10 15:10:22 -08002518 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002519 if (switchedDevice) {
2520 if (DEBUG_FOCUS) {
2521 ALOGD("Conflicting pointer actions: Switched to a different device.");
2522 }
2523 *outConflictingPointerActions = true;
2524 }
2525
2526 if (isHoverAction) {
2527 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002528 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002529 ALOGD_IF(DEBUG_FOCUS,
2530 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002531 *outConflictingPointerActions = true;
2532 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002533 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2534 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2535 tempTouchState.deviceId = entry.deviceId;
2536 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002537 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002538 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2539 // Pointer went up.
2540 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
2541 tempTouchState.clearWindowsWithoutPointers();
2542 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002543 // All pointers up or canceled.
2544 tempTouchState.reset();
2545 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2546 // First pointer went down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002547 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002548 ALOGD("Conflicting pointer actions: Down received while already down.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002549 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002550 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002551 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2552 // One pointer went up.
2553 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2554 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002555
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002556 for (size_t i = 0; i < tempTouchState.windows.size();) {
2557 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2558 touchedWindow.pointerIds.clearBit(pointerId);
2559 if (touchedWindow.pointerIds.isEmpty()) {
2560 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2561 continue;
2562 }
2563 i += 1;
2564 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565 }
2566
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002567 // Save changes unless the action was scroll in which case the temporary touch
2568 // state was only valid for this one action.
2569 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002570 if (displayId >= 0) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002571 mTouchStatesByDisplay[displayId] = tempTouchState;
2572 } else {
2573 mTouchStatesByDisplay.erase(displayId);
2574 }
2575 }
2576
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002577 if (tempTouchState.windows.empty()) {
2578 mTouchStatesByDisplay.erase(displayId);
2579 }
2580
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002581 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582}
2583
arthurhung6d4bed92021-03-17 11:59:33 +08002584void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002585 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2586 // have an explicit reason to support it.
2587 constexpr bool isStylus = false;
2588
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002589 auto [dropWindow, _] =
2590 findTouchedWindowAtLocked(displayId, x, y, isStylus, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002591 if (dropWindow) {
2592 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002593 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002594 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002595 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002596 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002597 }
2598 mDragState.reset();
2599}
2600
2601void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002602 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002603 return;
2604 }
2605
arthurhung6d4bed92021-03-17 11:59:33 +08002606 if (!mDragState->isStartDrag) {
2607 mDragState->isStartDrag = true;
2608 mDragState->isStylusButtonDownAtStart =
2609 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2610 }
2611
Arthur Hung54745652022-04-20 07:17:41 +00002612 // Find the pointer index by id.
2613 int32_t pointerIndex = 0;
2614 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2615 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2616 if (pointerProperties.id == mDragState->pointerId) {
2617 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002618 }
Arthur Hung54745652022-04-20 07:17:41 +00002619 }
arthurhung6d4bed92021-03-17 11:59:33 +08002620
Arthur Hung54745652022-04-20 07:17:41 +00002621 if (uint32_t(pointerIndex) == entry.pointerCount) {
2622 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002623 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002624 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002625 return;
2626 }
2627
2628 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2629 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2630 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2631
2632 switch (maskedAction) {
2633 case AMOTION_EVENT_ACTION_MOVE: {
2634 // Handle the special case : stylus button no longer pressed.
2635 bool isStylusButtonDown =
2636 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2637 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2638 finishDragAndDrop(entry.displayId, x, y);
2639 return;
2640 }
2641
2642 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2643 // until we have an explicit reason to support it.
2644 constexpr bool isStylus = false;
2645
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002646 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2647 true /*ignoreDragWindow*/);
Arthur Hung54745652022-04-20 07:17:41 +00002648 // enqueue drag exit if needed.
2649 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2650 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2651 if (mDragState->dragHoverWindowHandle != nullptr) {
2652 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2653 y);
2654 }
2655 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2656 }
2657 // enqueue drag location if needed.
2658 if (hoverWindowHandle != nullptr) {
2659 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2660 }
2661 break;
2662 }
2663
2664 case AMOTION_EVENT_ACTION_POINTER_UP:
2665 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2666 break;
2667 }
2668 // The drag pointer is up.
2669 [[fallthrough]];
2670 case AMOTION_EVENT_ACTION_UP:
2671 finishDragAndDrop(entry.displayId, x, y);
2672 break;
2673 case AMOTION_EVENT_ACTION_CANCEL: {
2674 ALOGD("Receiving cancel when drag and drop.");
2675 sendDropWindowCommandLocked(nullptr, 0, 0);
2676 mDragState.reset();
2677 break;
2678 }
arthurhungb89ccb02020-12-30 16:19:01 +08002679 }
2680}
2681
chaviw98318de2021-05-19 16:45:23 -05002682void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002683 ftl::Flags<InputTarget::Flags> targetFlags,
2684 BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002685 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002686 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002687 std::vector<InputTarget>::iterator it =
2688 std::find_if(inputTargets.begin(), inputTargets.end(),
2689 [&windowHandle](const InputTarget& inputTarget) {
2690 return inputTarget.inputChannel->getConnectionToken() ==
2691 windowHandle->getToken();
2692 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002693
chaviw98318de2021-05-19 16:45:23 -05002694 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002695
2696 if (it == inputTargets.end()) {
2697 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002698 std::shared_ptr<InputChannel> inputChannel =
2699 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002700 if (inputChannel == nullptr) {
2701 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2702 return;
2703 }
2704 inputTarget.inputChannel = inputChannel;
2705 inputTarget.flags = targetFlags;
2706 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002707 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002708 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2709 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002710 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002711 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002712 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002713 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002714 inputTargets.push_back(inputTarget);
2715 it = inputTargets.end() - 1;
2716 }
2717
2718 ALOG_ASSERT(it->flags == targetFlags);
2719 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2720
chaviw1ff3d1e2020-07-01 15:53:47 -07002721 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002722}
2723
Michael Wright3dd60e22019-03-27 22:06:44 +00002724void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002725 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002726 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2727 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002728
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002729 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2730 InputTarget target;
2731 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002732 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002733 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2734 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002735 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2736 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002737 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002738 target.setDefaultPointerTransform(target.displayTransform);
2739 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002740 }
2741}
2742
Robert Carrc9bf1d32020-04-13 17:21:08 -07002743/**
2744 * Indicate whether one window handle should be considered as obscuring
2745 * another window handle. We only check a few preconditions. Actually
2746 * checking the bounds is left to the caller.
2747 */
chaviw98318de2021-05-19 16:45:23 -05002748static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2749 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002750 // Compare by token so cloned layers aren't counted
2751 if (haveSameToken(windowHandle, otherHandle)) {
2752 return false;
2753 }
2754 auto info = windowHandle->getInfo();
2755 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002756 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002757 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002758 } else if (otherInfo->alpha == 0 &&
2759 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002760 // Those act as if they were invisible, so we don't need to flag them.
2761 // We do want to potentially flag touchable windows even if they have 0
2762 // opacity, since they can consume touches and alter the effects of the
2763 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002764 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002765 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2766 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002767 } else if (info->ownerUid == otherInfo->ownerUid) {
2768 // If ownerUid is the same we don't generate occlusion events as there
2769 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002770 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002771 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002772 return false;
2773 } else if (otherInfo->displayId != info->displayId) {
2774 return false;
2775 }
2776 return true;
2777}
2778
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002779/**
2780 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2781 * untrusted, one should check:
2782 *
2783 * 1. If result.hasBlockingOcclusion is true.
2784 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2785 * BLOCK_UNTRUSTED.
2786 *
2787 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2788 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2789 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2790 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2791 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2792 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2793 *
2794 * If neither of those is true, then it means the touch can be allowed.
2795 */
2796InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002797 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2798 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002799 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002800 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002801 TouchOcclusionInfo info;
2802 info.hasBlockingOcclusion = false;
2803 info.obscuringOpacity = 0;
2804 info.obscuringUid = -1;
2805 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002806 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002807 if (windowHandle == otherHandle) {
2808 break; // All future windows are below us. Exit early.
2809 }
chaviw98318de2021-05-19 16:45:23 -05002810 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002811 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2812 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002813 if (DEBUG_TOUCH_OCCLUSION) {
2814 info.debugInfo.push_back(
2815 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2816 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002817 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2818 // we perform the checks below to see if the touch can be propagated or not based on the
2819 // window's touch occlusion mode
2820 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2821 info.hasBlockingOcclusion = true;
2822 info.obscuringUid = otherInfo->ownerUid;
2823 info.obscuringPackage = otherInfo->packageName;
2824 break;
2825 }
2826 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2827 uint32_t uid = otherInfo->ownerUid;
2828 float opacity =
2829 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2830 // Given windows A and B:
2831 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2832 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2833 opacityByUid[uid] = opacity;
2834 if (opacity > info.obscuringOpacity) {
2835 info.obscuringOpacity = opacity;
2836 info.obscuringUid = uid;
2837 info.obscuringPackage = otherInfo->packageName;
2838 }
2839 }
2840 }
2841 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002842 if (DEBUG_TOUCH_OCCLUSION) {
2843 info.debugInfo.push_back(
2844 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2845 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002846 return info;
2847}
2848
chaviw98318de2021-05-19 16:45:23 -05002849std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002850 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002851 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2852 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2853 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2854 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002855 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2856 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2857 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2858 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2859 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002860 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002861 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002862}
2863
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002864bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2865 if (occlusionInfo.hasBlockingOcclusion) {
2866 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2867 occlusionInfo.obscuringUid);
2868 return false;
2869 }
2870 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2871 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2872 "%.2f, maximum allowed = %.2f)",
2873 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2874 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2875 return false;
2876 }
2877 return true;
2878}
2879
chaviw98318de2021-05-19 16:45:23 -05002880bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002881 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002883 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2884 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002885 if (windowHandle == otherHandle) {
2886 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002887 }
chaviw98318de2021-05-19 16:45:23 -05002888 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002889 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002890 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891 return true;
2892 }
2893 }
2894 return false;
2895}
2896
chaviw98318de2021-05-19 16:45:23 -05002897bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002898 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002899 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2900 const WindowInfo* windowInfo = windowHandle->getInfo();
2901 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002902 if (windowHandle == otherHandle) {
2903 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002904 }
chaviw98318de2021-05-19 16:45:23 -05002905 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002906 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002907 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002908 return true;
2909 }
2910 }
2911 return false;
2912}
2913
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002914std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002915 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002916 if (applicationHandle != nullptr) {
2917 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002918 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919 } else {
2920 return applicationHandle->getName();
2921 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002922 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002923 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002924 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002925 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002926 }
2927}
2928
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002929void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002930 if (!isUserActivityEvent(eventEntry)) {
2931 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002932 return;
2933 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002934 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002935 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002936 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002937 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002938 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002939 if (DEBUG_DISPATCH_CYCLE) {
2940 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2941 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942 return;
2943 }
2944 }
2945
2946 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002947 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002948 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002949 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2950 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002951 return;
2952 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002953
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002954 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002955 eventType = USER_ACTIVITY_EVENT_TOUCH;
2956 }
2957 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002958 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002959 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002960 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2961 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002962 return;
2963 }
2964 eventType = USER_ACTIVITY_EVENT_BUTTON;
2965 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002966 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002967 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002968 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002969 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002970 break;
2971 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972 }
2973
Prabir Pradhancef936d2021-07-21 16:17:52 +00002974 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2975 REQUIRES(mLock) {
2976 scoped_unlock unlock(mLock);
2977 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2978 };
2979 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002980}
2981
2982void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002983 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002984 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002985 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002986 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002987 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002988 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002989 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002990 ATRACE_NAME(message.c_str());
2991 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002992 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002993 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002994 "globalScaleFactor=%f, pointerIds=0x%x %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002995 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002996 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2997 inputTarget.getPointerInfoString().c_str());
2998 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002999
3000 // Skip this event if the connection status is not normal.
3001 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003002 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003003 if (DEBUG_DISPATCH_CYCLE) {
3004 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003005 connection->getInputChannelName().c_str(),
3006 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003007 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003008 return;
3009 }
3010
3011 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003012 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003013 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003014 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003015 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003016
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003017 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003018 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003019 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
3020 "Splitting motion events requires a down time to be set for the "
3021 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003022 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003023 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3024 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003025 if (!splitMotionEntry) {
3026 return; // split event was dropped
3027 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003028 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3029 std::string reason = std::string("reason=pointer cancel on split window");
3030 android_log_event_list(LOGTAG_INPUT_CANCEL)
3031 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3032 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003033 if (DEBUG_FOCUS) {
3034 ALOGD("channel '%s' ~ Split motion event.",
3035 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003036 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003037 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003038 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3039 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003040 return;
3041 }
3042 }
3043
3044 // Not splitting. Enqueue dispatch entries for the event as is.
3045 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3046}
3047
3048void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003049 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003050 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003051 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003052 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003053 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003054 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003055 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003056 ATRACE_NAME(message.c_str());
3057 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003058 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3059 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003060
hongzuo liu95785e22022-09-06 02:51:35 +00003061 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062
3063 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003064 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003065 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003066 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003067 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003068 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003069 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003070 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003071 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003072 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003073 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003074 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003075 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003076
3077 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003078 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003079 startDispatchCycleLocked(currentTime, connection);
3080 }
3081}
3082
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003083void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003084 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003085 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003086 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003087 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003088 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3089 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003090 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003091 ATRACE_NAME(message.c_str());
3092 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003093 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3094 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003095 return;
3096 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003097
3098 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3099 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100
3101 // This is a new event.
3102 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003103 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003104 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003106 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3107 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003108 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003109 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003110 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003111 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003112 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003113 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003114 dispatchEntry->resolvedAction = keyEntry.action;
3115 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003116
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003117 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3118 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003119 if (DEBUG_DISPATCH_CYCLE) {
3120 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3121 "event",
3122 connection->getInputChannelName().c_str());
3123 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003124 return; // skip the inconsistent event
3125 }
3126 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003129 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003130 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003131 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3132 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3133 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3134 static_cast<int32_t>(IdGenerator::Source::OTHER);
3135 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003136 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003137 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003138 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003139 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003140 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003141 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003142 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003143 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003144 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003145 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3146 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003147 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003148 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003149 }
3150 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003151 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3152 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003153 if (DEBUG_DISPATCH_CYCLE) {
3154 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3155 "enter event",
3156 connection->getInputChannelName().c_str());
3157 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003158 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3159 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003160 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3161 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003163 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003164 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003165 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3166 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003167 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003168 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3169 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003171 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3172 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003173 if (DEBUG_DISPATCH_CYCLE) {
3174 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3175 "event",
3176 connection->getInputChannelName().c_str());
3177 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003178 return; // skip the inconsistent event
3179 }
3180
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003181 dispatchEntry->resolvedEventId =
3182 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3183 ? mIdGenerator.nextId()
3184 : motionEntry.id;
3185 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3186 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3187 ") to MotionEvent(id=0x%" PRIx32 ").",
3188 motionEntry.id, dispatchEntry->resolvedEventId);
3189 ATRACE_NAME(message.c_str());
3190 }
3191
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003192 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3193 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3194 // Skip reporting pointer down outside focus to the policy.
3195 break;
3196 }
3197
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003198 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003199 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003200
3201 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003202 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003203 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003204 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003205 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3206 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003207 break;
3208 }
Chris Yef59a2f42020-10-16 12:55:26 -07003209 case EventEntry::Type::SENSOR: {
3210 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3211 break;
3212 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003213 case EventEntry::Type::CONFIGURATION_CHANGED:
3214 case EventEntry::Type::DEVICE_RESET: {
3215 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003216 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003217 break;
3218 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219 }
3220
3221 // Remember that we are waiting for this dispatch to complete.
3222 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003223 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224 }
3225
3226 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003227 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003228 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003229}
3230
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003231/**
3232 * This function is purely for debugging. It helps us understand where the user interaction
3233 * was taking place. For example, if user is touching launcher, we will see a log that user
3234 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3235 * We will see both launcher and wallpaper in that list.
3236 * Once the interaction with a particular set of connections starts, no new logs will be printed
3237 * until the set of interacted connections changes.
3238 *
3239 * The following items are skipped, to reduce the logspam:
3240 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3241 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3242 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3243 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3244 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003245 */
3246void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3247 const std::vector<InputTarget>& targets) {
3248 // Skip ACTION_UP events, and all events other than keys and motions
3249 if (entry.type == EventEntry::Type::KEY) {
3250 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3251 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3252 return;
3253 }
3254 } else if (entry.type == EventEntry::Type::MOTION) {
3255 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3256 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3257 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3258 return;
3259 }
3260 } else {
3261 return; // Not a key or a motion
3262 }
3263
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003264 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003265 std::vector<sp<Connection>> newConnections;
3266 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003267 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003268 continue; // Skip windows that receive ACTION_OUTSIDE
3269 }
3270
3271 sp<IBinder> token = target.inputChannel->getConnectionToken();
3272 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003273 if (connection == nullptr) {
3274 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003275 }
3276 newConnectionTokens.insert(std::move(token));
3277 newConnections.emplace_back(connection);
3278 }
3279 if (newConnectionTokens == mInteractionConnectionTokens) {
3280 return; // no change
3281 }
3282 mInteractionConnectionTokens = newConnectionTokens;
3283
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003284 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003285 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003286 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003287 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003288 std::string message = "Interaction with: " + targetList;
3289 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003290 message += "<none>";
3291 }
3292 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3293}
3294
chaviwfd6d3512019-03-25 13:23:49 -07003295void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003296 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003297 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003298 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3299 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003300 return;
3301 }
3302
Vishnu Nairc519ff72021-01-21 08:23:08 -08003303 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003304 if (focusedToken == token) {
3305 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003306 return;
3307 }
3308
Prabir Pradhancef936d2021-07-21 16:17:52 +00003309 auto command = [this, token]() REQUIRES(mLock) {
3310 scoped_unlock unlock(mLock);
3311 mPolicy->onPointerDownOutsideFocus(token);
3312 };
3313 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003314}
3315
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003316status_t InputDispatcher::publishMotionEvent(Connection& connection,
3317 DispatchEntry& dispatchEntry) const {
3318 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3319 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3320
3321 PointerCoords scaledCoords[MAX_POINTERS];
3322 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3323
3324 // Set the X and Y offset and X and Y scale depending on the input source.
3325 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003326 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003327 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3328 if (globalScaleFactor != 1.0f) {
3329 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3330 scaledCoords[i] = motionEntry.pointerCoords[i];
3331 // Don't apply window scale here since we don't want scale to affect raw
3332 // coordinates. The scale will be sent back to the client and applied
3333 // later when requesting relative coordinates.
3334 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3335 1 /* windowYScale */);
3336 }
3337 usingCoords = scaledCoords;
3338 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003339 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003340 // We don't want the dispatch target to know the coordinates
3341 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3342 scaledCoords[i].clear();
3343 }
3344 usingCoords = scaledCoords;
3345 }
3346
3347 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3348
3349 // Publish the motion event.
3350 return connection.inputPublisher
3351 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3352 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3353 std::move(hmac), dispatchEntry.resolvedAction,
3354 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3355 motionEntry.edgeFlags, motionEntry.metaState,
3356 motionEntry.buttonState, motionEntry.classification,
3357 dispatchEntry.transform, motionEntry.xPrecision,
3358 motionEntry.yPrecision, motionEntry.xCursorPosition,
3359 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3360 motionEntry.downTime, motionEntry.eventTime,
3361 motionEntry.pointerCount, motionEntry.pointerProperties,
3362 usingCoords);
3363}
3364
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003366 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003367 if (ATRACE_ENABLED()) {
3368 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003369 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003370 ATRACE_NAME(message.c_str());
3371 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003372 if (DEBUG_DISPATCH_CYCLE) {
3373 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3374 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003376 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003377 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003378 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003379 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003380 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381
3382 // Publish the event.
3383 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003384 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3385 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003386 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003387 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3388 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003389 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3390 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3391 << connection->getInputChannelName();
3392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003394 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003395 status = connection->inputPublisher
3396 .publishKeyEvent(dispatchEntry->seq,
3397 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3398 keyEntry.source, keyEntry.displayId,
3399 std::move(hmac), dispatchEntry->resolvedAction,
3400 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3401 keyEntry.scanCode, keyEntry.metaState,
3402 keyEntry.repeatCount, keyEntry.downTime,
3403 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003404 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405 }
3406
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003407 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003408 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3409 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3410 << connection->getInputChannelName();
3411 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003412 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003413 break;
3414 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003415
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003416 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003417 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003418 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003419 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003420 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003421 break;
3422 }
3423
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003424 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3425 const TouchModeEntry& touchModeEntry =
3426 static_cast<const TouchModeEntry&>(eventEntry);
3427 status = connection->inputPublisher
3428 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3429 touchModeEntry.inTouchMode);
3430
3431 break;
3432 }
3433
Prabir Pradhan99987712020-11-10 18:43:05 -08003434 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3435 const auto& captureEntry =
3436 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3437 status = connection->inputPublisher
3438 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003439 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003440 break;
3441 }
3442
arthurhungb89ccb02020-12-30 16:19:01 +08003443 case EventEntry::Type::DRAG: {
3444 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3445 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3446 dragEntry.id, dragEntry.x,
3447 dragEntry.y,
3448 dragEntry.isExiting);
3449 break;
3450 }
3451
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003452 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003453 case EventEntry::Type::DEVICE_RESET:
3454 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003455 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003456 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003457 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003458 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459 }
3460
3461 // Check the result.
3462 if (status) {
3463 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003464 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003466 "This is unexpected because the wait queue is empty, so the pipe "
3467 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003468 "event to it, status=%s(%d)",
3469 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3470 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3472 } else {
3473 // Pipe is full and we are waiting for the app to finish process some events
3474 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003475 if (DEBUG_DISPATCH_CYCLE) {
3476 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3477 "waiting for the application to catch up",
3478 connection->getInputChannelName().c_str());
3479 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003480 }
3481 } else {
3482 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003483 "status=%s(%d)",
3484 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3485 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3487 }
3488 return;
3489 }
3490
3491 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003492 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3493 connection->outboundQueue.end(),
3494 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003495 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003496 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003497 if (connection->responsive) {
3498 mAnrTracker.insert(dispatchEntry->timeoutTime,
3499 connection->inputChannel->getConnectionToken());
3500 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003501 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502 }
3503}
3504
chaviw09c8d2d2020-08-24 15:48:26 -07003505std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3506 size_t size;
3507 switch (event.type) {
3508 case VerifiedInputEvent::Type::KEY: {
3509 size = sizeof(VerifiedKeyEvent);
3510 break;
3511 }
3512 case VerifiedInputEvent::Type::MOTION: {
3513 size = sizeof(VerifiedMotionEvent);
3514 break;
3515 }
3516 }
3517 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3518 return mHmacKeyManager.sign(start, size);
3519}
3520
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003521const std::array<uint8_t, 32> InputDispatcher::getSignature(
3522 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003523 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3524 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003525 // Only sign events up and down events as the purely move events
3526 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003527 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003528 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003529
3530 VerifiedMotionEvent verifiedEvent =
3531 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3532 verifiedEvent.actionMasked = actionMasked;
3533 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3534 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003535}
3536
3537const std::array<uint8_t, 32> InputDispatcher::getSignature(
3538 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3539 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3540 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3541 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003542 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003543}
3544
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003546 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003547 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003548 if (DEBUG_DISPATCH_CYCLE) {
3549 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3550 connection->getInputChannelName().c_str(), seq, toString(handled));
3551 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003552
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003553 if (connection->status == Connection::Status::BROKEN ||
3554 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003555 return;
3556 }
3557
3558 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003559 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3560 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3561 };
3562 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003563}
3564
3565void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003566 const sp<Connection>& connection,
3567 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003568 if (DEBUG_DISPATCH_CYCLE) {
3569 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3570 connection->getInputChannelName().c_str(), toString(notify));
3571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572
3573 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003574 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003575 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003576 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003577 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003578
3579 // The connection appears to be unrecoverably broken.
3580 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003581 if (connection->status == Connection::Status::NORMAL) {
3582 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003583
3584 if (notify) {
3585 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003586 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3587 connection->getInputChannelName().c_str());
3588
3589 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003590 scoped_unlock unlock(mLock);
3591 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3592 };
3593 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594 }
3595 }
3596}
3597
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003598void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3599 while (!queue.empty()) {
3600 DispatchEntry* dispatchEntry = queue.front();
3601 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003602 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603 }
3604}
3605
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003606void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003607 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003608 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 }
3610 delete dispatchEntry;
3611}
3612
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003613int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3614 std::scoped_lock _l(mLock);
3615 sp<Connection> connection = getConnectionLocked(connectionToken);
3616 if (connection == nullptr) {
3617 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3618 connectionToken.get(), events);
3619 return 0; // remove the callback
3620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003622 bool notify;
3623 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3624 if (!(events & ALOOPER_EVENT_INPUT)) {
3625 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3626 "events=0x%x",
3627 connection->getInputChannelName().c_str(), events);
3628 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 }
3630
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003631 nsecs_t currentTime = now();
3632 bool gotOne = false;
3633 status_t status = OK;
3634 for (;;) {
3635 Result<InputPublisher::ConsumerResponse> result =
3636 connection->inputPublisher.receiveConsumerResponse();
3637 if (!result.ok()) {
3638 status = result.error().code();
3639 break;
3640 }
3641
3642 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3643 const InputPublisher::Finished& finish =
3644 std::get<InputPublisher::Finished>(*result);
3645 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3646 finish.consumeTime);
3647 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003648 if (shouldReportMetricsForConnection(*connection)) {
3649 const InputPublisher::Timeline& timeline =
3650 std::get<InputPublisher::Timeline>(*result);
3651 mLatencyTracker
3652 .trackGraphicsLatency(timeline.inputEventId,
3653 connection->inputChannel->getConnectionToken(),
3654 std::move(timeline.graphicsTimeline));
3655 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003656 }
3657 gotOne = true;
3658 }
3659 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003660 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003661 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662 return 1;
3663 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664 }
3665
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003666 notify = status != DEAD_OBJECT || !connection->monitor;
3667 if (notify) {
3668 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3669 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3670 status);
3671 }
3672 } else {
3673 // Monitor channels are never explicitly unregistered.
3674 // We do it automatically when the remote endpoint is closed so don't warn about them.
3675 const bool stillHaveWindowHandle =
3676 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3677 notify = !connection->monitor && stillHaveWindowHandle;
3678 if (notify) {
3679 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3680 connection->getInputChannelName().c_str(), events);
3681 }
3682 }
3683
3684 // Remove the channel.
3685 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3686 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687}
3688
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003689void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003691 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003692 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693 }
3694}
3695
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003696void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003697 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003698 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003699 for (const Monitor& monitor : monitors) {
3700 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003701 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003702 }
3703}
3704
Michael Wrightd02c5b62014-02-10 15:10:22 -08003705void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003706 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003707 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003708 if (connection == nullptr) {
3709 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003711
3712 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713}
3714
3715void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3716 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003717 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003718 return;
3719 }
3720
3721 nsecs_t currentTime = now();
3722
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003723 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003724 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003725
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003726 if (cancelationEvents.empty()) {
3727 return;
3728 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003729 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3730 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3731 "with reality: %s, mode=%d.",
3732 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3733 options.mode);
3734 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003735
Arthur Hungb3307ee2021-10-14 10:57:37 +00003736 std::string reason = std::string("reason=").append(options.reason);
3737 android_log_event_list(LOGTAG_INPUT_CANCEL)
3738 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3739
Svet Ganov5d3bc372020-01-26 23:11:07 -08003740 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003741 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003742 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3743 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003744 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003745 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003746 target.globalScaleFactor = windowInfo->globalScaleFactor;
3747 }
3748 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003749 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003750
hongzuo liu95785e22022-09-06 02:51:35 +00003751 const bool wasEmpty = connection->outboundQueue.empty();
3752
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003753 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003754 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003755 switch (cancelationEventEntry->type) {
3756 case EventEntry::Type::KEY: {
3757 logOutboundKeyDetails("cancel - ",
3758 static_cast<const KeyEntry&>(*cancelationEventEntry));
3759 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003761 case EventEntry::Type::MOTION: {
3762 logOutboundMotionDetails("cancel - ",
3763 static_cast<const MotionEntry&>(*cancelationEventEntry));
3764 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003766 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003767 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003768 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3769 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003770 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003771 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003772 break;
3773 }
3774 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003775 case EventEntry::Type::DEVICE_RESET:
3776 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003777 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003778 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003779 break;
3780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781 }
3782
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003783 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003784 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003786
hongzuo liu95785e22022-09-06 02:51:35 +00003787 // If the outbound queue was previously empty, start the dispatch cycle going.
3788 if (wasEmpty && !connection->outboundQueue.empty()) {
3789 startDispatchCycleLocked(currentTime, connection);
3790 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791}
3792
Svet Ganov5d3bc372020-01-26 23:11:07 -08003793void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Arthur Hungc539dbb2022-12-08 07:45:36 +00003794 const nsecs_t downTime, const sp<Connection>& connection,
3795 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003796 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003797 return;
3798 }
3799
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003800 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003801 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003802
3803 if (downEvents.empty()) {
3804 return;
3805 }
3806
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003807 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003808 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3809 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003810 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003811
3812 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003813 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003814 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3815 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003816 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003817 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003818 target.globalScaleFactor = windowInfo->globalScaleFactor;
3819 }
3820 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00003821 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003822
hongzuo liu95785e22022-09-06 02:51:35 +00003823 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003824 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003825 switch (downEventEntry->type) {
3826 case EventEntry::Type::MOTION: {
3827 logOutboundMotionDetails("down - ",
3828 static_cast<const MotionEntry&>(*downEventEntry));
3829 break;
3830 }
3831
3832 case EventEntry::Type::KEY:
3833 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003834 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003835 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003836 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003837 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003838 case EventEntry::Type::SENSOR:
3839 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003840 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003841 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003842 break;
3843 }
3844 }
3845
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003846 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003847 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003848 }
3849
hongzuo liu95785e22022-09-06 02:51:35 +00003850 // If the outbound queue was previously empty, start the dispatch cycle going.
3851 if (wasEmpty && !connection->outboundQueue.empty()) {
3852 startDispatchCycleLocked(downTime, connection);
3853 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003854}
3855
Arthur Hungc539dbb2022-12-08 07:45:36 +00003856void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
3857 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
3858 if (windowHandle != nullptr) {
3859 sp<Connection> wallpaperConnection = getConnectionLocked(windowHandle->getToken());
3860 if (wallpaperConnection != nullptr) {
3861 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
3862 }
3863 }
3864}
3865
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003866std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003867 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003868 ALOG_ASSERT(pointerIds.value != 0);
3869
3870 uint32_t splitPointerIndexMap[MAX_POINTERS];
3871 PointerProperties splitPointerProperties[MAX_POINTERS];
3872 PointerCoords splitPointerCoords[MAX_POINTERS];
3873
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003874 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875 uint32_t splitPointerCount = 0;
3876
3877 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003878 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003880 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881 uint32_t pointerId = uint32_t(pointerProperties.id);
3882 if (pointerIds.hasBit(pointerId)) {
3883 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3884 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3885 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003886 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887 splitPointerCount += 1;
3888 }
3889 }
3890
3891 if (splitPointerCount != pointerIds.count()) {
3892 // This is bad. We are missing some of the pointers that we expected to deliver.
3893 // Most likely this indicates that we received an ACTION_MOVE events that has
3894 // different pointer ids than we expected based on the previous ACTION_DOWN
3895 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3896 // in this way.
3897 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003898 "we expected there to be %d pointers. This probably means we received "
3899 "a broken sequence of pointer ids from the input device.",
3900 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003901 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902 }
3903
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003904 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003906 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3907 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3909 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003910 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003911 uint32_t pointerId = uint32_t(pointerProperties.id);
3912 if (pointerIds.hasBit(pointerId)) {
3913 if (pointerIds.count() == 1) {
3914 // The first/last pointer went down/up.
3915 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003916 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003917 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3918 ? AMOTION_EVENT_ACTION_CANCEL
3919 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920 } else {
3921 // A secondary pointer went down/up.
3922 uint32_t splitPointerIndex = 0;
3923 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3924 splitPointerIndex += 1;
3925 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003926 action = maskedAction |
3927 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928 }
3929 } else {
3930 // An unrelated pointer changed.
3931 action = AMOTION_EVENT_ACTION_MOVE;
3932 }
3933 }
3934
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003935 if (action == AMOTION_EVENT_ACTION_DOWN) {
3936 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3937 "Split motion event has mismatching downTime and eventTime for "
3938 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3939 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3940 }
3941
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003942 int32_t newId = mIdGenerator.nextId();
3943 if (ATRACE_ENABLED()) {
3944 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3945 ") to MotionEvent(id=0x%" PRIx32 ").",
3946 originalMotionEntry.id, newId);
3947 ATRACE_NAME(message.c_str());
3948 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003949 std::unique_ptr<MotionEntry> splitMotionEntry =
3950 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3951 originalMotionEntry.deviceId, originalMotionEntry.source,
3952 originalMotionEntry.displayId,
3953 originalMotionEntry.policyFlags, action,
3954 originalMotionEntry.actionButton,
3955 originalMotionEntry.flags, originalMotionEntry.metaState,
3956 originalMotionEntry.buttonState,
3957 originalMotionEntry.classification,
3958 originalMotionEntry.edgeFlags,
3959 originalMotionEntry.xPrecision,
3960 originalMotionEntry.yPrecision,
3961 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003962 originalMotionEntry.yCursorPosition, splitDownTime,
3963 splitPointerCount, splitPointerProperties,
3964 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003966 if (originalMotionEntry.injectionState) {
3967 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968 splitMotionEntry->injectionState->refCount += 1;
3969 }
3970
3971 return splitMotionEntry;
3972}
3973
3974void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003975 if (DEBUG_INBOUND_EVENT_DETAILS) {
3976 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978
Antonio Kantekf16f2832021-09-28 04:39:20 +00003979 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003981 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003982
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003983 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3984 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3985 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986 } // release lock
3987
3988 if (needWake) {
3989 mLooper->wake();
3990 }
3991}
3992
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003993/**
3994 * If one of the meta shortcuts is detected, process them here:
3995 * Meta + Backspace -> generate BACK
3996 * Meta + Enter -> generate HOME
3997 * This will potentially overwrite keyCode and metaState.
3998 */
3999void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004000 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004001 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4002 int32_t newKeyCode = AKEYCODE_UNKNOWN;
4003 if (keyCode == AKEYCODE_DEL) {
4004 newKeyCode = AKEYCODE_BACK;
4005 } else if (keyCode == AKEYCODE_ENTER) {
4006 newKeyCode = AKEYCODE_HOME;
4007 }
4008 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004009 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004010 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004011 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004012 keyCode = newKeyCode;
4013 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4014 }
4015 } else if (action == AKEY_EVENT_ACTION_UP) {
4016 // In order to maintain a consistent stream of up and down events, check to see if the key
4017 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4018 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004019 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004020 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004021 auto replacementIt = mReplacedKeys.find(replacement);
4022 if (replacementIt != mReplacedKeys.end()) {
4023 keyCode = replacementIt->second;
4024 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004025 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4026 }
4027 }
4028}
4029
Michael Wrightd02c5b62014-02-10 15:10:22 -08004030void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004031 if (DEBUG_INBOUND_EVENT_DETAILS) {
4032 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
4033 "policyFlags=0x%x, action=0x%x, "
4034 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
4035 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
4036 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
4037 args->downTime);
4038 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004039 if (!validateKeyEvent(args->action)) {
4040 return;
4041 }
4042
4043 uint32_t policyFlags = args->policyFlags;
4044 int32_t flags = args->flags;
4045 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004046 // InputDispatcher tracks and generates key repeats on behalf of
4047 // whatever notifies it, so repeatCount should always be set to 0
4048 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004049 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4050 policyFlags |= POLICY_FLAG_VIRTUAL;
4051 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4052 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004053 if (policyFlags & POLICY_FLAG_FUNCTION) {
4054 metaState |= AMETA_FUNCTION_ON;
4055 }
4056
4057 policyFlags |= POLICY_FLAG_TRUSTED;
4058
Michael Wright78f24442014-08-06 15:55:28 -07004059 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004060 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004061
Michael Wrightd02c5b62014-02-10 15:10:22 -08004062 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004063 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08004064 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
4065 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004066
Michael Wright2b3c3302018-03-02 17:19:13 +00004067 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004068 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004069 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4070 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004071 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004072 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073
Antonio Kantekf16f2832021-09-28 04:39:20 +00004074 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075 { // acquire lock
4076 mLock.lock();
4077
4078 if (shouldSendKeyToInputFilterLocked(args)) {
4079 mLock.unlock();
4080
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004081 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004082 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4083 return; // event was consumed by the filter
4084 }
4085
4086 mLock.lock();
4087 }
4088
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004089 std::unique_ptr<KeyEntry> newEntry =
4090 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4091 args->displayId, policyFlags, args->action, flags,
4092 keyCode, args->scanCode, metaState, repeatCount,
4093 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004095 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004096 mLock.unlock();
4097 } // release lock
4098
4099 if (needWake) {
4100 mLooper->wake();
4101 }
4102}
4103
4104bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4105 return mInputFilterEnabled;
4106}
4107
4108void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004109 if (DEBUG_INBOUND_EVENT_DETAILS) {
4110 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4111 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004112 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004113 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4114 "yCursorPosition=%f, downTime=%" PRId64,
4115 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004116 args->policyFlags, MotionEvent::actionToString(args->action).c_str(),
4117 args->actionButton, args->flags, args->metaState, args->buttonState, args->edgeFlags,
4118 args->xPrecision, args->yPrecision, args->xCursorPosition, args->yCursorPosition,
4119 args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004120 for (uint32_t i = 0; i < args->pointerCount; i++) {
4121 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4122 "x=%f, y=%f, pressure=%f, size=%f, "
4123 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4124 "orientation=%f",
4125 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4126 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4127 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4128 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4129 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4130 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4131 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4132 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4133 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4134 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4135 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -08004137 LOG_ALWAYS_FATAL_IF(!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4138 args->pointerProperties),
4139 "Invalid event: %s", args->dump().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140
4141 uint32_t policyFlags = args->policyFlags;
4142 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004143
4144 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004145 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004146 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4147 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004148 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004149 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004150
Antonio Kantekf16f2832021-09-28 04:39:20 +00004151 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152 { // acquire lock
4153 mLock.lock();
4154
4155 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004156 ui::Transform displayTransform;
4157 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4158 displayTransform = it->second.transform;
4159 }
4160
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 mLock.unlock();
4162
4163 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004164 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4165 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004166 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004167 displayTransform, args->xPrecision, args->yPrecision,
4168 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004169 args->downTime, args->eventTime, args->pointerCount,
4170 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171
4172 policyFlags |= POLICY_FLAG_FILTERED;
4173 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4174 return; // event was consumed by the filter
4175 }
4176
4177 mLock.lock();
4178 }
4179
4180 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004181 std::unique_ptr<MotionEntry> newEntry =
4182 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4183 args->source, args->displayId, policyFlags,
4184 args->action, args->actionButton, args->flags,
4185 args->metaState, args->buttonState,
4186 args->classification, args->edgeFlags,
4187 args->xPrecision, args->yPrecision,
4188 args->xCursorPosition, args->yCursorPosition,
4189 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004190 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004191
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004192 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4193 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4194 !mInputFilterEnabled) {
4195 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4196 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4197 }
4198
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004199 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 mLock.unlock();
4201 } // release lock
4202
4203 if (needWake) {
4204 mLooper->wake();
4205 }
4206}
4207
Chris Yef59a2f42020-10-16 12:55:26 -07004208void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004209 if (DEBUG_INBOUND_EVENT_DETAILS) {
4210 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4211 " sensorType=%s",
4212 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004213 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004214 }
Chris Yef59a2f42020-10-16 12:55:26 -07004215
Antonio Kantekf16f2832021-09-28 04:39:20 +00004216 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004217 { // acquire lock
4218 mLock.lock();
4219
4220 // Just enqueue a new sensor event.
4221 std::unique_ptr<SensorEntry> newEntry =
4222 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4223 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4224 args->sensorType, args->accuracy,
4225 args->accuracyChanged, args->values);
4226
4227 needWake = enqueueInboundEventLocked(std::move(newEntry));
4228 mLock.unlock();
4229 } // release lock
4230
4231 if (needWake) {
4232 mLooper->wake();
4233 }
4234}
4235
Chris Yefb552902021-02-03 17:18:37 -08004236void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004237 if (DEBUG_INBOUND_EVENT_DETAILS) {
4238 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4239 args->deviceId, args->isOn);
4240 }
Chris Yefb552902021-02-03 17:18:37 -08004241 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4242}
4243
Michael Wrightd02c5b62014-02-10 15:10:22 -08004244bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004245 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004246}
4247
4248void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004249 if (DEBUG_INBOUND_EVENT_DETAILS) {
4250 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4251 "switchMask=0x%08x",
4252 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4253 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004254
4255 uint32_t policyFlags = args->policyFlags;
4256 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004257 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258}
4259
4260void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004261 if (DEBUG_INBOUND_EVENT_DETAILS) {
4262 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4263 args->deviceId);
4264 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265
Antonio Kantekf16f2832021-09-28 04:39:20 +00004266 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004268 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004270 std::unique_ptr<DeviceResetEntry> newEntry =
4271 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4272 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 } // release lock
4274
4275 if (needWake) {
4276 mLooper->wake();
4277 }
4278}
4279
Prabir Pradhan7e186182020-11-10 13:56:45 -08004280void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004281 if (DEBUG_INBOUND_EVENT_DETAILS) {
4282 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004283 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004284 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004285
Antonio Kantekf16f2832021-09-28 04:39:20 +00004286 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004287 { // acquire lock
4288 std::scoped_lock _l(mLock);
4289 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004290 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004291 needWake = enqueueInboundEventLocked(std::move(entry));
4292 } // release lock
4293
4294 if (needWake) {
4295 mLooper->wake();
4296 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004297}
4298
Prabir Pradhan5735a322022-04-11 17:23:34 +00004299InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4300 std::optional<int32_t> targetUid,
4301 InputEventInjectionSync syncMode,
4302 std::chrono::milliseconds timeout,
4303 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004304 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004305 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4306 "policyFlags=0x%08x",
4307 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4308 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004309 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004310 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311
Prabir Pradhan5735a322022-04-11 17:23:34 +00004312 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004314 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004315 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4316 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4317 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4318 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4319 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004320 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004321 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004322 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004323 }
4324
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004325 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004327 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004328 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4329 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004330 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004331 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004332 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004334 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004335 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4336 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4337 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004338 int32_t keyCode = incomingKey.getKeyCode();
4339 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004340 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004341 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004342 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004343 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004344 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4345 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4346 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004348 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4349 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004350 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004351
4352 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4353 android::base::Timer t;
4354 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4355 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4356 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4357 std::to_string(t.duration().count()).c_str());
4358 }
4359 }
4360
4361 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004362 std::unique_ptr<KeyEntry> injectedEntry =
4363 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004364 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004365 incomingKey.getDisplayId(), policyFlags, action,
4366 flags, keyCode, incomingKey.getScanCode(), metaState,
4367 incomingKey.getRepeatCount(),
4368 incomingKey.getDownTime());
4369 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004370 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371 }
4372
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004373 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004374 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004375 const int32_t action = motionEvent.getAction();
4376 const bool isPointerEvent =
4377 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4378 // If a pointer event has no displayId specified, inject it to the default display.
4379 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4380 ? ADISPLAY_ID_DEFAULT
4381 : event->getDisplayId();
4382 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004383 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004384 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004385 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004386 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004387 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004388 }
4389
4390 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004391 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004392 android::base::Timer t;
4393 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4394 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4395 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4396 std::to_string(t.duration().count()).c_str());
4397 }
4398 }
4399
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004400 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4401 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4402 }
4403
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004404 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004405 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4406 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004407 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004408 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4409 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004410 displayId, policyFlags, action, actionButton,
4411 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004412 motionEvent.getButtonState(),
4413 motionEvent.getClassification(),
4414 motionEvent.getEdgeFlags(),
4415 motionEvent.getXPrecision(),
4416 motionEvent.getYPrecision(),
4417 motionEvent.getRawXCursorPosition(),
4418 motionEvent.getRawYCursorPosition(),
4419 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004420 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004421 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004422 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004423 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004424 sampleEventTimes += 1;
4425 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004426 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004427 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4428 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004429 displayId, policyFlags, action, actionButton,
4430 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004431 motionEvent.getButtonState(),
4432 motionEvent.getClassification(),
4433 motionEvent.getEdgeFlags(),
4434 motionEvent.getXPrecision(),
4435 motionEvent.getYPrecision(),
4436 motionEvent.getRawXCursorPosition(),
4437 motionEvent.getRawYCursorPosition(),
4438 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004439 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004440 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004441 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4442 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004443 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004444 }
4445 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004448 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004449 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004450 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004451 }
4452
Prabir Pradhan5735a322022-04-11 17:23:34 +00004453 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004454 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004455 injectionState->injectionIsAsync = true;
4456 }
4457
4458 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004459 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004460
4461 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004462 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004463 if (DEBUG_INJECTION) {
4464 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4465 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004466 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004467 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004468 }
4469
4470 mLock.unlock();
4471
4472 if (needWake) {
4473 mLooper->wake();
4474 }
4475
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004476 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004477 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004478 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004480 if (syncMode == InputEventInjectionSync::NONE) {
4481 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004482 } else {
4483 for (;;) {
4484 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004485 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004486 break;
4487 }
4488
4489 nsecs_t remainingTimeout = endTime - now();
4490 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004491 if (DEBUG_INJECTION) {
4492 ALOGD("injectInputEvent - Timed out waiting for injection result "
4493 "to become available.");
4494 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004495 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496 break;
4497 }
4498
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004499 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500 }
4501
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004502 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4503 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004505 if (DEBUG_INJECTION) {
4506 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4507 injectionState->pendingForegroundDispatches);
4508 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004509 nsecs_t remainingTimeout = endTime - now();
4510 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004511 if (DEBUG_INJECTION) {
4512 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4513 "dispatches to finish.");
4514 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004515 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004516 break;
4517 }
4518
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004519 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004520 }
4521 }
4522 }
4523
4524 injectionState->release();
4525 } // release lock
4526
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004527 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004528 LOG(DEBUG) << "injectInputEvent - Finished with result "
4529 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004530 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004531
4532 return injectionResult;
4533}
4534
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004535std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004536 std::array<uint8_t, 32> calculatedHmac;
4537 std::unique_ptr<VerifiedInputEvent> result;
4538 switch (event.getType()) {
4539 case AINPUT_EVENT_TYPE_KEY: {
4540 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4541 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4542 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004543 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004544 break;
4545 }
4546 case AINPUT_EVENT_TYPE_MOTION: {
4547 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4548 VerifiedMotionEvent verifiedMotionEvent =
4549 verifiedMotionEventFromMotionEvent(motionEvent);
4550 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004551 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004552 break;
4553 }
4554 default: {
4555 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4556 return nullptr;
4557 }
4558 }
4559 if (calculatedHmac == INVALID_HMAC) {
4560 return nullptr;
4561 }
4562 if (calculatedHmac != event.getHmac()) {
4563 return nullptr;
4564 }
4565 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004566}
4567
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004568void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004569 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004570 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004571 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004572 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004573 LOG(DEBUG) << "Setting input event injection result to "
4574 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004575 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004576
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004577 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004578 // Log the outcome since the injector did not wait for the injection result.
4579 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004580 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004581 ALOGV("Asynchronous input event injection succeeded.");
4582 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004583 case InputEventInjectionResult::TARGET_MISMATCH:
4584 ALOGV("Asynchronous input event injection target mismatch.");
4585 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004586 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004587 ALOGW("Asynchronous input event injection failed.");
4588 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004589 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004590 ALOGW("Asynchronous input event injection timed out.");
4591 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004592 case InputEventInjectionResult::PENDING:
4593 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4594 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004595 }
4596 }
4597
4598 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004599 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004600 }
4601}
4602
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004603void InputDispatcher::transformMotionEntryForInjectionLocked(
4604 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004605 // Input injection works in the logical display coordinate space, but the input pipeline works
4606 // display space, so we need to transform the injected events accordingly.
4607 const auto it = mDisplayInfos.find(entry.displayId);
4608 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004609 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004610
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004611 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4612 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4613 const vec2 cursor =
4614 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4615 {entry.xCursorPosition, entry.yCursorPosition});
4616 entry.xCursorPosition = cursor.x;
4617 entry.yCursorPosition = cursor.y;
4618 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004619 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004620 entry.pointerCoords[i] =
4621 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4622 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004623 }
4624}
4625
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004626void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4627 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628 if (injectionState) {
4629 injectionState->pendingForegroundDispatches += 1;
4630 }
4631}
4632
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004633void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4634 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004635 if (injectionState) {
4636 injectionState->pendingForegroundDispatches -= 1;
4637
4638 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004639 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004640 }
4641 }
4642}
4643
chaviw98318de2021-05-19 16:45:23 -05004644const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004645 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004646 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004647 auto it = mWindowHandlesByDisplay.find(displayId);
4648 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004649}
4650
chaviw98318de2021-05-19 16:45:23 -05004651sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004652 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004653 if (windowHandleToken == nullptr) {
4654 return nullptr;
4655 }
4656
Arthur Hungb92218b2018-08-14 12:00:21 +08004657 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004658 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4659 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004660 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004661 return windowHandle;
4662 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663 }
4664 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004665 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004666}
4667
chaviw98318de2021-05-19 16:45:23 -05004668sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4669 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004670 if (windowHandleToken == nullptr) {
4671 return nullptr;
4672 }
4673
chaviw98318de2021-05-19 16:45:23 -05004674 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004675 if (windowHandle->getToken() == windowHandleToken) {
4676 return windowHandle;
4677 }
4678 }
4679 return nullptr;
4680}
4681
chaviw98318de2021-05-19 16:45:23 -05004682sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4683 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004684 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004685 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4686 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004687 if (handle->getId() == windowHandle->getId() &&
4688 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004689 if (windowHandle->getInfo()->displayId != it.first) {
4690 ALOGE("Found window %s in display %" PRId32
4691 ", but it should belong to display %" PRId32,
4692 windowHandle->getName().c_str(), it.first,
4693 windowHandle->getInfo()->displayId);
4694 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004695 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004696 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004697 }
4698 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004699 return nullptr;
4700}
4701
chaviw98318de2021-05-19 16:45:23 -05004702sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004703 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4704 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004705}
4706
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004707bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4708 const MotionEntry& motionEntry) const {
4709 const WindowInfo& info = *window->getInfo();
4710
4711 // Skip spy window targets that are not valid for targeted injection.
4712 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004713 return false;
4714 }
4715
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004716 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4717 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4718 return false;
4719 }
4720
4721 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4722 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4723 window->getName().c_str());
4724 return false;
4725 }
4726
4727 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004728 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004729 ALOGW("Not sending touch to %s because there's no corresponding connection",
4730 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004731 return false;
4732 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004733
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004734 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004735 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004736 return false;
4737 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004738
4739 // Drop events that can't be trusted due to occlusion
4740 const auto [x, y] = resolveTouchedPosition(motionEntry);
4741 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4742 if (!isTouchTrustedLocked(occlusionInfo)) {
4743 if (DEBUG_TOUCH_OCCLUSION) {
4744 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4745 for (const auto& log : occlusionInfo.debugInfo) {
4746 ALOGD("%s", log.c_str());
4747 }
4748 }
4749 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4750 occlusionInfo.obscuringUid);
4751 return false;
4752 }
4753
4754 // Drop touch events if requested by input feature
4755 if (shouldDropInput(motionEntry, window)) {
4756 return false;
4757 }
4758
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004759 return true;
4760}
4761
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004762std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4763 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004764 auto connectionIt = mConnectionsByToken.find(token);
4765 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004766 return nullptr;
4767 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004768 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004769}
4770
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004771void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004772 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4773 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004774 // Remove all handles on a display if there are no windows left.
4775 mWindowHandlesByDisplay.erase(displayId);
4776 return;
4777 }
4778
4779 // Since we compare the pointer of input window handles across window updates, we need
4780 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004781 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4782 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4783 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004784 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004785 }
4786
chaviw98318de2021-05-19 16:45:23 -05004787 std::vector<sp<WindowInfoHandle>> newHandles;
4788 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004789 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004790 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004791 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004792 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004793 const bool canReceiveInput =
4794 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4795 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004796 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004797 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004798 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004799 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004800 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004801 }
4802
4803 if (info->displayId != displayId) {
4804 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4805 handle->getName().c_str(), displayId, info->displayId);
4806 continue;
4807 }
4808
Robert Carredd13602020-04-13 17:24:34 -07004809 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4810 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004811 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004812 oldHandle->updateFrom(handle);
4813 newHandles.push_back(oldHandle);
4814 } else {
4815 newHandles.push_back(handle);
4816 }
4817 }
4818
4819 // Insert or replace
4820 mWindowHandlesByDisplay[displayId] = newHandles;
4821}
4822
Arthur Hung72d8dc32020-03-28 00:48:39 +00004823void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004824 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004825 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004826 { // acquire lock
4827 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004828 for (const auto& [displayId, handles] : handlesPerDisplay) {
4829 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004830 }
4831 }
4832 // Wake up poll loop since it may need to make new input dispatching choices.
4833 mLooper->wake();
4834}
4835
Arthur Hungb92218b2018-08-14 12:00:21 +08004836/**
4837 * Called from InputManagerService, update window handle list by displayId that can receive input.
4838 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4839 * If set an empty list, remove all handles from the specific display.
4840 * For focused handle, check if need to change and send a cancel event to previous one.
4841 * For removed handle, check if need to send a cancel event if already in touch.
4842 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004843void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004844 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004845 if (DEBUG_FOCUS) {
4846 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004847 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004848 windowList += iwh->getName() + " ";
4849 }
4850 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4851 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004852
Prabir Pradhand65552b2021-10-07 11:23:50 -07004853 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004854 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004855 const WindowInfo& info = *window->getInfo();
4856
4857 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004858 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004859 if (noInputWindow && window->getToken() != nullptr) {
4860 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4861 window->getName().c_str());
4862 window->releaseChannel();
4863 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004864
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004865 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004866 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4867 !info.inputConfig.test(
4868 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004869 "%s has feature SPY, but is not a trusted overlay.",
4870 window->getName().c_str());
4871
Prabir Pradhand65552b2021-10-07 11:23:50 -07004872 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004873 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4874 !info.inputConfig.test(
4875 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004876 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4877 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004878 }
4879
Arthur Hung72d8dc32020-03-28 00:48:39 +00004880 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004881 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004883 // Save the old windows' orientation by ID before it gets updated.
4884 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004885 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004886 oldWindowOrientations.emplace(handle->getId(),
4887 handle->getInfo()->transform.getOrientation());
4888 }
4889
chaviw98318de2021-05-19 16:45:23 -05004890 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004891
chaviw98318de2021-05-19 16:45:23 -05004892 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004893
Vishnu Nairc519ff72021-01-21 08:23:08 -08004894 std::optional<FocusResolver::FocusChanges> changes =
4895 mFocusResolver.setInputWindows(displayId, windowHandles);
4896 if (changes) {
4897 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004898 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004900 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4901 mTouchStatesByDisplay.find(displayId);
4902 if (stateIt != mTouchStatesByDisplay.end()) {
4903 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004904 for (size_t i = 0; i < state.windows.size();) {
4905 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004906 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004907 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004908 ALOGD("Touched window was removed: %s in display %" PRId32,
4909 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004910 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004911 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004912 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4913 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004914 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00004915 "touched window was removed");
4916 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004917 // Since we are about to drop the touch, cancel the events for the wallpaper as
4918 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004919 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004920 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4921 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004922 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004923 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004924 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004925 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004926 state.windows.erase(state.windows.begin() + i);
4927 } else {
4928 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004929 }
4930 }
arthurhungb89ccb02020-12-30 16:19:01 +08004931
arthurhung6d4bed92021-03-17 11:59:33 +08004932 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004933 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004934 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004935 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004936 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004937 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4938 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004939 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004940 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004941 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004942
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004943 // Determine if the orientation of any of the input windows have changed, and cancel all
4944 // pointer events if necessary.
4945 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4946 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4947 if (newWindowHandle != nullptr &&
4948 newWindowHandle->getInfo()->transform.getOrientation() !=
4949 oldWindowOrientations[oldWindowHandle->getId()]) {
4950 std::shared_ptr<InputChannel> inputChannel =
4951 getInputChannelLocked(newWindowHandle->getToken());
4952 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004953 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004954 "touched window's orientation changed");
4955 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004956 }
4957 }
4958 }
4959
Arthur Hung72d8dc32020-03-28 00:48:39 +00004960 // Release information for windows that are no longer present.
4961 // This ensures that unused input channels are released promptly.
4962 // Otherwise, they might stick around until the window handle is destroyed
4963 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004964 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004965 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004966 if (DEBUG_FOCUS) {
4967 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004968 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004969 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004970 }
chaviw291d88a2019-02-14 10:33:58 -08004971 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004972}
4973
4974void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004975 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004976 if (DEBUG_FOCUS) {
4977 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4978 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4979 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004980 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004981 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004982 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004983 } // release lock
4984
4985 // Wake up poll loop since it may need to make new input dispatching choices.
4986 mLooper->wake();
4987}
4988
Vishnu Nair599f1412021-06-21 10:39:58 -07004989void InputDispatcher::setFocusedApplicationLocked(
4990 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4991 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4992 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4993
4994 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4995 return; // This application is already focused. No need to wake up or change anything.
4996 }
4997
4998 // Set the new application handle.
4999 if (inputApplicationHandle != nullptr) {
5000 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5001 } else {
5002 mFocusedApplicationHandlesByDisplay.erase(displayId);
5003 }
5004
5005 // No matter what the old focused application was, stop waiting on it because it is
5006 // no longer focused.
5007 resetNoFocusedWindowTimeoutLocked();
5008}
5009
Tiger Huang721e26f2018-07-24 22:26:19 +08005010/**
5011 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5012 * the display not specified.
5013 *
5014 * We track any unreleased events for each window. If a window loses the ability to receive the
5015 * released event, we will send a cancel event to it. So when the focused display is changed, we
5016 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5017 * display. The display-specified events won't be affected.
5018 */
5019void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005020 if (DEBUG_FOCUS) {
5021 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5022 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005023 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005024 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005025
5026 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005027 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005028 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005029 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005030 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005031 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005032 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005033 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005034 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005035 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005036 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005037 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5038 }
5039 }
5040 mFocusedDisplayId = displayId;
5041
Chris Ye3c2d6f52020-08-09 10:39:48 -07005042 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005043 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005044 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005045
Vishnu Nairad321cd2020-08-20 16:40:21 -07005046 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005047 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005048 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005049 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005050 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005051 }
5052 }
5053 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005054 } // release lock
5055
5056 // Wake up poll loop since it may need to make new input dispatching choices.
5057 mLooper->wake();
5058}
5059
Michael Wrightd02c5b62014-02-10 15:10:22 -08005060void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005061 if (DEBUG_FOCUS) {
5062 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5063 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005064
5065 bool changed;
5066 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005067 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005068
5069 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5070 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005071 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005072 }
5073
5074 if (mDispatchEnabled && !enabled) {
5075 resetAndDropEverythingLocked("dispatcher is being disabled");
5076 }
5077
5078 mDispatchEnabled = enabled;
5079 mDispatchFrozen = frozen;
5080 changed = true;
5081 } else {
5082 changed = false;
5083 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005084 } // release lock
5085
5086 if (changed) {
5087 // Wake up poll loop since it may need to make new input dispatching choices.
5088 mLooper->wake();
5089 }
5090}
5091
5092void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005093 if (DEBUG_FOCUS) {
5094 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5095 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005096
5097 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005098 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005099
5100 if (mInputFilterEnabled == enabled) {
5101 return;
5102 }
5103
5104 mInputFilterEnabled = enabled;
5105 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5106 } // release lock
5107
5108 // Wake up poll loop since there might be work to do to drop everything.
5109 mLooper->wake();
5110}
5111
Antonio Kanteka042c022022-07-06 16:51:07 -07005112bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5113 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005114 bool needWake = false;
5115 {
5116 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005117 ALOGD_IF(DEBUG_TOUCH_MODE,
5118 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5119 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5120 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5121 mTouchModePerDisplay.count(displayId) == 0
5122 ? "not set"
5123 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5124
Antonio Kantek15beb512022-06-13 22:35:41 +00005125 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5126 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005127 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005128 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005129 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005130 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5131 !recentWindowsAreOwnedByLocked(pid, uid)) {
5132 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5133 "window nor none of the previously interacted window",
5134 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005135 return false;
5136 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005137 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005138 mTouchModePerDisplay[displayId] = inTouchMode;
5139 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5140 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005141 needWake = enqueueInboundEventLocked(std::move(entry));
5142 } // release lock
5143
5144 if (needWake) {
5145 mLooper->wake();
5146 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005147 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005148}
5149
Antonio Kantek48710e42022-03-24 14:19:30 -07005150bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5151 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5152 if (focusedToken == nullptr) {
5153 return false;
5154 }
5155 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5156 return isWindowOwnedBy(windowHandle, pid, uid);
5157}
5158
5159bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5160 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5161 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5162 const sp<WindowInfoHandle> windowHandle =
5163 getWindowHandleLocked(connectionToken);
5164 return isWindowOwnedBy(windowHandle, pid, uid);
5165 }) != mInteractionConnectionTokens.end();
5166}
5167
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005168void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5169 if (opacity < 0 || opacity > 1) {
5170 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5171 return;
5172 }
5173
5174 std::scoped_lock lock(mLock);
5175 mMaximumObscuringOpacityForTouch = opacity;
5176}
5177
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005178std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5179InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005180 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5181 for (TouchedWindow& w : state.windows) {
5182 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005183 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005184 }
5185 }
5186 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005187 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005188}
5189
arthurhungb89ccb02020-12-30 16:19:01 +08005190bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5191 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005192 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005193 if (DEBUG_FOCUS) {
5194 ALOGD("Trivial transfer to same window.");
5195 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005196 return true;
5197 }
5198
Michael Wrightd02c5b62014-02-10 15:10:22 -08005199 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005200 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005201
Arthur Hungabbb9d82021-09-01 14:52:30 +00005202 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005203 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005204 if (state == nullptr || touchedWindow == nullptr) {
5205 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005206 return false;
5207 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005208
Arthur Hungabbb9d82021-09-01 14:52:30 +00005209 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5210 if (toWindowHandle == nullptr) {
5211 ALOGW("Cannot transfer focus because to window not found.");
5212 return false;
5213 }
5214
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005215 if (DEBUG_FOCUS) {
5216 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005217 touchedWindow->windowHandle->getName().c_str(),
5218 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005219 }
5220
Arthur Hungabbb9d82021-09-01 14:52:30 +00005221 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005222 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005223 BitSet32 pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005224 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005225 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005226
Arthur Hungabbb9d82021-09-01 14:52:30 +00005227 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005228 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005229 ftl::Flags<InputTarget::Flags> newTargetFlags =
5230 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005231 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005232 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005233 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005234 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005235
Arthur Hungabbb9d82021-09-01 14:52:30 +00005236 // Store the dragging window.
5237 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005238 if (pointerIds.count() != 1) {
5239 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5240 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005241 return false;
5242 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005243 // Track the pointer id for drag window and generate the drag state.
5244 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005245 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005246 }
5247
Arthur Hungabbb9d82021-09-01 14:52:30 +00005248 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005249 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5250 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005251 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005252 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005253 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005254 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005255 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005256 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005257 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5258 newTargetFlags);
5259
5260 // Check if the wallpaper window should deliver the corresponding event.
5261 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5262 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005263 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005264 } // release lock
5265
5266 // Wake up poll loop since it may need to make new input dispatching choices.
5267 mLooper->wake();
5268 return true;
5269}
5270
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005271/**
5272 * Get the touched foreground window on the given display.
5273 * Return null if there are no windows touched on that display, or if more than one foreground
5274 * window is being touched.
5275 */
5276sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5277 auto stateIt = mTouchStatesByDisplay.find(displayId);
5278 if (stateIt == mTouchStatesByDisplay.end()) {
5279 ALOGI("No touch state on display %" PRId32, displayId);
5280 return nullptr;
5281 }
5282
5283 const TouchState& state = stateIt->second;
5284 sp<WindowInfoHandle> touchedForegroundWindow;
5285 // If multiple foreground windows are touched, return nullptr
5286 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005287 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005288 if (touchedForegroundWindow != nullptr) {
5289 ALOGI("Two or more foreground windows: %s and %s",
5290 touchedForegroundWindow->getName().c_str(),
5291 window.windowHandle->getName().c_str());
5292 return nullptr;
5293 }
5294 touchedForegroundWindow = window.windowHandle;
5295 }
5296 }
5297 return touchedForegroundWindow;
5298}
5299
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005300// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005301bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005302 sp<IBinder> fromToken;
5303 { // acquire lock
5304 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005305 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005306 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005307 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5308 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005309 return false;
5310 }
5311
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005312 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5313 if (from == nullptr) {
5314 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5315 return false;
5316 }
5317
5318 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005319 } // release lock
5320
5321 return transferTouchFocus(fromToken, destChannelToken);
5322}
5323
Michael Wrightd02c5b62014-02-10 15:10:22 -08005324void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005325 if (DEBUG_FOCUS) {
5326 ALOGD("Resetting and dropping all events (%s).", reason);
5327 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005328
Michael Wrightfb04fd52022-11-24 22:31:11 +00005329 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005330 synthesizeCancelationEventsForAllConnectionsLocked(options);
5331
5332 resetKeyRepeatLocked();
5333 releasePendingEventLocked();
5334 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005335 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005336
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005337 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005338 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005339 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005340}
5341
5342void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005343 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005344 dumpDispatchStateLocked(dump);
5345
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005346 std::istringstream stream(dump);
5347 std::string line;
5348
5349 while (std::getline(stream, line, '\n')) {
5350 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351 }
5352}
5353
Prabir Pradhan99987712020-11-10 18:43:05 -08005354std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5355 std::string dump;
5356
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005357 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5358 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005359
5360 std::string windowName = "None";
5361 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005362 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005363 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5364 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5365 : "token has capture without window";
5366 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005367 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005368
5369 return dump;
5370}
5371
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005372void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005373 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5374 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5375 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005376 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005377
Tiger Huang721e26f2018-07-24 22:26:19 +08005378 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5379 dump += StringPrintf(INDENT "FocusedApplications:\n");
5380 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5381 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005382 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005383 const std::chrono::duration timeout =
5384 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005385 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005386 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005387 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005389 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005390 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005391 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005392
Vishnu Nairc519ff72021-01-21 08:23:08 -08005393 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005394 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005395
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005396 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005397 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005398 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005399 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5400 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005401 }
5402 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005403 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005404 }
5405
arthurhung6d4bed92021-03-17 11:59:33 +08005406 if (mDragState) {
5407 dump += StringPrintf(INDENT "DragState:\n");
5408 mDragState->dump(dump, INDENT2);
5409 }
5410
Arthur Hungb92218b2018-08-14 12:00:21 +08005411 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005412 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5413 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5414 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5415 const auto& displayInfo = it->second;
5416 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5417 displayInfo.logicalHeight);
5418 displayInfo.transform.dump(dump, "transform", INDENT4);
5419 } else {
5420 dump += INDENT2 "No DisplayInfo found!\n";
5421 }
5422
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005423 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005424 dump += INDENT2 "Windows:\n";
5425 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005426 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5427 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005428
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005429 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005430 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005431 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005432 "applicationInfo.name=%s, "
5433 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005434 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005435 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005436 windowInfo->displayId,
5437 windowInfo->inputConfig.string().c_str(),
5438 windowInfo->alpha, windowInfo->frameLeft,
5439 windowInfo->frameTop, windowInfo->frameRight,
5440 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005441 windowInfo->applicationInfo.name.c_str(),
5442 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005443 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005444 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005445 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005446 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005447 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005448 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005449 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005450 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005451 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005452 }
5453 } else {
5454 dump += INDENT2 "Windows: <none>\n";
5455 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005456 }
5457 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005458 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005459 }
5460
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005461 if (!mGlobalMonitorsByDisplay.empty()) {
5462 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5463 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005464 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005465 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005466 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005467 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005468 }
5469
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005470 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005471
5472 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005473 if (!mRecentQueue.empty()) {
5474 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005475 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005476 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005477 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005478 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005479 }
5480 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005481 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482 }
5483
5484 // Dump event currently being dispatched.
5485 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005486 dump += INDENT "PendingEvent:\n";
5487 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005488 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005489 dump += StringPrintf(", age=%" PRId64 "ms\n",
5490 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005491 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005492 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005493 }
5494
5495 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005496 if (!mInboundQueue.empty()) {
5497 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005498 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005499 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005500 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005501 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005502 }
5503 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005504 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005505 }
5506
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005507 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005508 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005509 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005510 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005511 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005512 }
5513 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005514 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005515 }
5516
Prabir Pradhancef936d2021-07-21 16:17:52 +00005517 if (!mCommandQueue.empty()) {
5518 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5519 } else {
5520 dump += INDENT "CommandQueue: <empty>\n";
5521 }
5522
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005523 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005524 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005525 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005526 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005527 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005528 connection->inputChannel->getFd().get(),
5529 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005530 connection->getWindowName().c_str(),
5531 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005532 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005533
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005534 if (!connection->outboundQueue.empty()) {
5535 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5536 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005537 dump += dumpQueue(connection->outboundQueue, currentTime);
5538
Michael Wrightd02c5b62014-02-10 15:10:22 -08005539 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005540 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005541 }
5542
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005543 if (!connection->waitQueue.empty()) {
5544 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5545 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005546 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005547 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005548 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005549 }
5550 }
5551 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005552 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005553 }
5554
5555 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005556 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5557 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005558 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005559 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005560 }
5561
Antonio Kantek15beb512022-06-13 22:35:41 +00005562 if (!mTouchModePerDisplay.empty()) {
5563 dump += INDENT "TouchModePerDisplay:\n";
5564 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5565 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5566 std::to_string(touchMode).c_str());
5567 }
5568 } else {
5569 dump += INDENT "TouchModePerDisplay: <none>\n";
5570 }
5571
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005572 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005573 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5574 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5575 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005576 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005577 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005578}
5579
Michael Wright3dd60e22019-03-27 22:06:44 +00005580void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5581 const size_t numMonitors = monitors.size();
5582 for (size_t i = 0; i < numMonitors; i++) {
5583 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005584 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005585 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5586 dump += "\n";
5587 }
5588}
5589
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005590class LooperEventCallback : public LooperCallback {
5591public:
5592 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5593 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5594
5595private:
5596 std::function<int(int events)> mCallback;
5597};
5598
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005599Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005600 if (DEBUG_CHANNEL_CREATION) {
5601 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005603
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005604 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005605 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005606 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005607
5608 if (result) {
5609 return base::Error(result) << "Failed to open input channel pair with name " << name;
5610 }
5611
Michael Wrightd02c5b62014-02-10 15:10:22 -08005612 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005613 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005614 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005615 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005616 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005617 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005618
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005619 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5620 ALOGE("Created a new connection, but the token %p is already known", token.get());
5621 }
5622 mConnectionsByToken.emplace(token, connection);
5623
5624 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5625 this, std::placeholders::_1, token);
5626
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005627 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5628 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005629 } // release lock
5630
5631 // Wake the looper because some connections have changed.
5632 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005633 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005634}
5635
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005636Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005637 const std::string& name,
5638 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005639 std::shared_ptr<InputChannel> serverChannel;
5640 std::unique_ptr<InputChannel> clientChannel;
5641 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5642 if (result) {
5643 return base::Error(result) << "Failed to open input channel pair with name " << name;
5644 }
5645
Michael Wright3dd60e22019-03-27 22:06:44 +00005646 { // acquire lock
5647 std::scoped_lock _l(mLock);
5648
5649 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005650 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5651 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005652 }
5653
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005654 sp<Connection> connection =
5655 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005656 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005657 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005658
5659 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5660 ALOGE("Created a new connection, but the token %p is already known", token.get());
5661 }
5662 mConnectionsByToken.emplace(token, connection);
5663 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5664 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005665
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005666 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005667
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005668 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5669 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005670 }
Garfield Tan15601662020-09-22 15:32:38 -07005671
Michael Wright3dd60e22019-03-27 22:06:44 +00005672 // Wake the looper because some connections have changed.
5673 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005674 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005675}
5676
Garfield Tan15601662020-09-22 15:32:38 -07005677status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005678 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005679 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005680
Garfield Tan15601662020-09-22 15:32:38 -07005681 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005682 if (status) {
5683 return status;
5684 }
5685 } // release lock
5686
5687 // Wake the poll loop because removing the connection may have changed the current
5688 // synchronization state.
5689 mLooper->wake();
5690 return OK;
5691}
5692
Garfield Tan15601662020-09-22 15:32:38 -07005693status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5694 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005695 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005696 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005697 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005698 return BAD_VALUE;
5699 }
5700
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005701 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005702
Michael Wrightd02c5b62014-02-10 15:10:22 -08005703 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005704 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005705 }
5706
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005707 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005708
5709 nsecs_t currentTime = now();
5710 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5711
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005712 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005713 return OK;
5714}
5715
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005716void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005717 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5718 auto& [displayId, monitors] = *it;
5719 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5720 return monitor.inputChannel->getConnectionToken() == connectionToken;
5721 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005722
Michael Wright3dd60e22019-03-27 22:06:44 +00005723 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005724 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005725 } else {
5726 ++it;
5727 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005728 }
5729}
5730
Michael Wright3dd60e22019-03-27 22:06:44 +00005731status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005732 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005733 return pilferPointersLocked(token);
5734}
Michael Wright3dd60e22019-03-27 22:06:44 +00005735
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005736status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005737 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5738 if (!requestingChannel) {
5739 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5740 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005741 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005742
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005743 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07005744 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.isEmpty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005745 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5746 " Ignoring.");
5747 return BAD_VALUE;
5748 }
5749
5750 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005751 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005752 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005753 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005754 "input channel stole pointer stream");
5755 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005756 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005757 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005758 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005759 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005760 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005761 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005762 if (channel != nullptr && channel->getConnectionToken() != token) {
5763 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5764 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5765 canceledWindows += channel->getName();
5766 }
5767 }
5768 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5769 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5770 canceledWindows.c_str());
5771
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005772 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005773 // This only blocks relevant pointers to be sent to other windows
5774 window.isPilferingPointers = true;
5775
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005776 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005777 return OK;
5778}
5779
Prabir Pradhan99987712020-11-10 18:43:05 -08005780void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5781 { // acquire lock
5782 std::scoped_lock _l(mLock);
5783 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005784 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005785 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5786 windowHandle != nullptr ? windowHandle->getName().c_str()
5787 : "token without window");
5788 }
5789
Vishnu Nairc519ff72021-01-21 08:23:08 -08005790 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005791 if (focusedToken != windowToken) {
5792 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5793 enabled ? "enable" : "disable");
5794 return;
5795 }
5796
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005797 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005798 ALOGW("Ignoring request to %s Pointer Capture: "
5799 "window has %s requested pointer capture.",
5800 enabled ? "enable" : "disable", enabled ? "already" : "not");
5801 return;
5802 }
5803
Christine Franksb768bb42021-11-29 12:11:31 -08005804 if (enabled) {
5805 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5806 mIneligibleDisplaysForPointerCapture.end(),
5807 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5808 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5809 return;
5810 }
5811 }
5812
Prabir Pradhan99987712020-11-10 18:43:05 -08005813 setPointerCaptureLocked(enabled);
5814 } // release lock
5815
5816 // Wake the thread to process command entries.
5817 mLooper->wake();
5818}
5819
Christine Franksb768bb42021-11-29 12:11:31 -08005820void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5821 { // acquire lock
5822 std::scoped_lock _l(mLock);
5823 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5824 if (!isEligible) {
5825 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5826 }
5827 } // release lock
5828}
5829
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005830std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5831 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005832 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005833 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005834 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005835 }
5836 }
5837 }
5838 return std::nullopt;
5839}
5840
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005841sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005842 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005843 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005844 }
5845
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005846 for (const auto& [token, connection] : mConnectionsByToken) {
5847 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005848 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005849 }
5850 }
Robert Carr4e670e52018-08-15 13:26:12 -07005851
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005852 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005853}
5854
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005855std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5856 sp<Connection> connection = getConnectionLocked(connectionToken);
5857 if (connection == nullptr) {
5858 return "<nullptr>";
5859 }
5860 return connection->getInputChannelName();
5861}
5862
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005863void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005864 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005865 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005866}
5867
Prabir Pradhancef936d2021-07-21 16:17:52 +00005868void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5869 const sp<Connection>& connection, uint32_t seq,
5870 bool handled, nsecs_t consumeTime) {
5871 // Handle post-event policy actions.
5872 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5873 if (dispatchEntryIt == connection->waitQueue.end()) {
5874 return;
5875 }
5876 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5877 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5878 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5879 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5880 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5881 }
5882 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5883 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5884 connection->inputChannel->getConnectionToken(),
5885 dispatchEntry->deliveryTime, consumeTime, finishTime);
5886 }
5887
5888 bool restartEvent;
5889 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5890 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5891 restartEvent =
5892 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5893 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5894 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5895 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5896 handled);
5897 } else {
5898 restartEvent = false;
5899 }
5900
5901 // Dequeue the event and start the next cycle.
5902 // Because the lock might have been released, it is possible that the
5903 // contents of the wait queue to have been drained, so we need to double-check
5904 // a few things.
5905 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5906 if (dispatchEntryIt != connection->waitQueue.end()) {
5907 dispatchEntry = *dispatchEntryIt;
5908 connection->waitQueue.erase(dispatchEntryIt);
5909 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5910 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5911 if (!connection->responsive) {
5912 connection->responsive = isConnectionResponsive(*connection);
5913 if (connection->responsive) {
5914 // The connection was unresponsive, and now it's responsive.
5915 processConnectionResponsiveLocked(*connection);
5916 }
5917 }
5918 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005919 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005920 connection->outboundQueue.push_front(dispatchEntry);
5921 traceOutboundQueueLength(*connection);
5922 } else {
5923 releaseDispatchEntry(dispatchEntry);
5924 }
5925 }
5926
5927 // Start the next dispatch cycle for this connection.
5928 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005929}
5930
Prabir Pradhancef936d2021-07-21 16:17:52 +00005931void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5932 const sp<IBinder>& newToken) {
5933 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5934 scoped_unlock unlock(mLock);
5935 mPolicy->notifyFocusChanged(oldToken, newToken);
5936 };
5937 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005938}
5939
Prabir Pradhancef936d2021-07-21 16:17:52 +00005940void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5941 auto command = [this, token, x, y]() REQUIRES(mLock) {
5942 scoped_unlock unlock(mLock);
5943 mPolicy->notifyDropWindow(token, x, y);
5944 };
5945 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005946}
5947
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005948void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5949 if (connection == nullptr) {
5950 LOG_ALWAYS_FATAL("Caller must check for nullness");
5951 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005952 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5953 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005954 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005955 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005956 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005957 return;
5958 }
5959 /**
5960 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5961 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5962 * has changed. This could cause newer entries to time out before the already dispatched
5963 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5964 * processes the events linearly. So providing information about the oldest entry seems to be
5965 * most useful.
5966 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005967 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005968 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5969 std::string reason =
5970 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005971 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005972 ns2ms(currentWait),
5973 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005974 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005975 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005976
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005977 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5978
5979 // Stop waking up for events on this connection, it is already unresponsive
5980 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005981}
5982
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005983void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5984 std::string reason =
5985 StringPrintf("%s does not have a focused window", application->getName().c_str());
5986 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005987
Prabir Pradhancef936d2021-07-21 16:17:52 +00005988 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5989 scoped_unlock unlock(mLock);
5990 mPolicy->notifyNoFocusedWindowAnr(application);
5991 };
5992 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005993}
5994
chaviw98318de2021-05-19 16:45:23 -05005995void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005996 const std::string& reason) {
5997 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5998 updateLastAnrStateLocked(windowLabel, reason);
5999}
6000
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006001void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6002 const std::string& reason) {
6003 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006004 updateLastAnrStateLocked(windowLabel, reason);
6005}
6006
6007void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6008 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006009 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006010 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006011 struct tm tm;
6012 localtime_r(&t, &tm);
6013 char timestr[64];
6014 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006015 mLastAnrState.clear();
6016 mLastAnrState += INDENT "ANR:\n";
6017 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006018 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6019 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006020 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006021}
6022
Prabir Pradhancef936d2021-07-21 16:17:52 +00006023void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6024 KeyEntry& entry) {
6025 const KeyEvent event = createKeyEvent(entry);
6026 nsecs_t delay = 0;
6027 { // release lock
6028 scoped_unlock unlock(mLock);
6029 android::base::Timer t;
6030 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
6031 entry.policyFlags);
6032 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6033 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6034 std::to_string(t.duration().count()).c_str());
6035 }
6036 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006037
6038 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006039 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006040 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006041 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006042 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006043 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006044 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006045 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006046}
6047
Prabir Pradhancef936d2021-07-21 16:17:52 +00006048void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006049 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006050 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006051 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006052 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006053 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006054 };
6055 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006056}
6057
Prabir Pradhanedd96402022-02-15 01:46:16 -08006058void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6059 std::optional<int32_t> pid) {
6060 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006061 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006062 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006063 };
6064 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006065}
6066
6067/**
6068 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6069 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6070 * command entry to the command queue.
6071 */
6072void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6073 std::string reason) {
6074 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006075 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006076 if (connection.monitor) {
6077 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6078 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006079 pid = findMonitorPidByTokenLocked(connectionToken);
6080 } else {
6081 // The connection is a window
6082 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6083 reason.c_str());
6084 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6085 if (handle != nullptr) {
6086 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006087 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006088 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006089 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006090}
6091
6092/**
6093 * Tell the policy that a connection has become responsive so that it can stop ANR.
6094 */
6095void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6096 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006097 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006098 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006099 pid = findMonitorPidByTokenLocked(connectionToken);
6100 } else {
6101 // The connection is a window
6102 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6103 if (handle != nullptr) {
6104 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006105 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006106 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006107 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006108}
6109
Prabir Pradhancef936d2021-07-21 16:17:52 +00006110bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006111 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006112 KeyEntry& keyEntry, bool handled) {
6113 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006114 if (!handled) {
6115 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006116 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006117 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006118 return false;
6119 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006120
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006121 // Get the fallback key state.
6122 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006123 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006124 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006125 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006126 connection->inputState.removeFallbackKey(originalKeyCode);
6127 }
6128
6129 if (handled || !dispatchEntry->hasForegroundTarget()) {
6130 // If the application handles the original key for which we previously
6131 // generated a fallback or if the window is not a foreground window,
6132 // then cancel the associated fallback key, if any.
6133 if (fallbackKeyCode != -1) {
6134 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006135 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6136 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6137 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6138 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6139 keyEntry.policyFlags);
6140 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006141 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006142 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006143
6144 mLock.unlock();
6145
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006146 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006147 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006148
6149 mLock.lock();
6150
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006151 // Cancel the fallback key.
6152 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006153 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006154 "application handled the original non-fallback key "
6155 "or is no longer a foreground target, "
6156 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006157 options.keyCode = fallbackKeyCode;
6158 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006159 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006160 connection->inputState.removeFallbackKey(originalKeyCode);
6161 }
6162 } else {
6163 // If the application did not handle a non-fallback key, first check
6164 // that we are in a good state to perform unhandled key event processing
6165 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006166 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006167 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006168 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6169 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6170 "since this is not an initial down. "
6171 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6172 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6173 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006174 return false;
6175 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006176
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006177 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006178 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6179 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6180 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6181 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6182 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006183 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006184
6185 mLock.unlock();
6186
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006187 bool fallback =
6188 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006189 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006190
6191 mLock.lock();
6192
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006193 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006194 connection->inputState.removeFallbackKey(originalKeyCode);
6195 return false;
6196 }
6197
6198 // Latch the fallback keycode for this key on an initial down.
6199 // The fallback keycode cannot change at any other point in the lifecycle.
6200 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006201 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006202 fallbackKeyCode = event.getKeyCode();
6203 } else {
6204 fallbackKeyCode = AKEYCODE_UNKNOWN;
6205 }
6206 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6207 }
6208
6209 ALOG_ASSERT(fallbackKeyCode != -1);
6210
6211 // Cancel the fallback key if the policy decides not to send it anymore.
6212 // We will continue to dispatch the key to the policy but we will no
6213 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006214 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6215 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006216 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6217 if (fallback) {
6218 ALOGD("Unhandled key event: Policy requested to send key %d"
6219 "as a fallback for %d, but on the DOWN it had requested "
6220 "to send %d instead. Fallback canceled.",
6221 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6222 } else {
6223 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6224 "but on the DOWN it had requested to send %d. "
6225 "Fallback canceled.",
6226 originalKeyCode, fallbackKeyCode);
6227 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006228 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006229
Michael Wrightfb04fd52022-11-24 22:31:11 +00006230 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006231 "canceling fallback, policy no longer desires it");
6232 options.keyCode = fallbackKeyCode;
6233 synthesizeCancelationEventsForConnectionLocked(connection, options);
6234
6235 fallback = false;
6236 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006237 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006238 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006239 }
6240 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006241
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006242 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6243 {
6244 std::string msg;
6245 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6246 connection->inputState.getFallbackKeys();
6247 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6248 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6249 }
6250 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6251 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006252 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006253 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006254
6255 if (fallback) {
6256 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006257 keyEntry.eventTime = event.getEventTime();
6258 keyEntry.deviceId = event.getDeviceId();
6259 keyEntry.source = event.getSource();
6260 keyEntry.displayId = event.getDisplayId();
6261 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6262 keyEntry.keyCode = fallbackKeyCode;
6263 keyEntry.scanCode = event.getScanCode();
6264 keyEntry.metaState = event.getMetaState();
6265 keyEntry.repeatCount = event.getRepeatCount();
6266 keyEntry.downTime = event.getDownTime();
6267 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006268
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006269 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6270 ALOGD("Unhandled key event: Dispatching fallback key. "
6271 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6272 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6273 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006274 return true; // restart the event
6275 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006276 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6277 ALOGD("Unhandled key event: No fallback key.");
6278 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006279
6280 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006281 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006282 }
6283 }
6284 return false;
6285}
6286
Prabir Pradhancef936d2021-07-21 16:17:52 +00006287bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006288 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006289 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006290 return false;
6291}
6292
Michael Wrightd02c5b62014-02-10 15:10:22 -08006293void InputDispatcher::traceInboundQueueLengthLocked() {
6294 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006295 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006296 }
6297}
6298
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006299void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006300 if (ATRACE_ENABLED()) {
6301 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006302 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6303 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006304 }
6305}
6306
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006307void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006308 if (ATRACE_ENABLED()) {
6309 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006310 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6311 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006312 }
6313}
6314
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006315void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006316 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006317
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006318 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006319 dumpDispatchStateLocked(dump);
6320
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006321 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006322 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006323 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006324 }
6325}
6326
6327void InputDispatcher::monitor() {
6328 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006329 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006330 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006331 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006332}
6333
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006334/**
6335 * Wake up the dispatcher and wait until it processes all events and commands.
6336 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6337 * this method can be safely called from any thread, as long as you've ensured that
6338 * the work you are interested in completing has already been queued.
6339 */
6340bool InputDispatcher::waitForIdle() {
6341 /**
6342 * Timeout should represent the longest possible time that a device might spend processing
6343 * events and commands.
6344 */
6345 constexpr std::chrono::duration TIMEOUT = 100ms;
6346 std::unique_lock lock(mLock);
6347 mLooper->wake();
6348 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6349 return result == std::cv_status::no_timeout;
6350}
6351
Vishnu Naire798b472020-07-23 13:52:21 -07006352/**
6353 * Sets focus to the window identified by the token. This must be called
6354 * after updating any input window handles.
6355 *
6356 * Params:
6357 * request.token - input channel token used to identify the window that should gain focus.
6358 * request.focusedToken - the token that the caller expects currently to be focused. If the
6359 * specified token does not match the currently focused window, this request will be dropped.
6360 * If the specified focused token matches the currently focused window, the call will succeed.
6361 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6362 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6363 * when requesting the focus change. This determines which request gets
6364 * precedence if there is a focus change request from another source such as pointer down.
6365 */
Vishnu Nair958da932020-08-21 17:12:37 -07006366void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6367 { // acquire lock
6368 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006369 std::optional<FocusResolver::FocusChanges> changes =
6370 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6371 if (changes) {
6372 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006373 }
6374 } // release lock
6375 // Wake up poll loop since it may need to make new input dispatching choices.
6376 mLooper->wake();
6377}
6378
Vishnu Nairc519ff72021-01-21 08:23:08 -08006379void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6380 if (changes.oldFocus) {
6381 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006382 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006383 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006384 "focus left window");
6385 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006386 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006387 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006388 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006389 if (changes.newFocus) {
6390 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006391 }
6392
Prabir Pradhan99987712020-11-10 18:43:05 -08006393 // If a window has pointer capture, then it must have focus. We need to ensure that this
6394 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6395 // If the window loses focus before it loses pointer capture, then the window can be in a state
6396 // where it has pointer capture but not focus, violating the contract. Therefore we must
6397 // dispatch the pointer capture event before the focus event. Since focus events are added to
6398 // the front of the queue (above), we add the pointer capture event to the front of the queue
6399 // after the focus events are added. This ensures the pointer capture event ends up at the
6400 // front.
6401 disablePointerCaptureForcedLocked();
6402
Vishnu Nairc519ff72021-01-21 08:23:08 -08006403 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006404 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006405 }
6406}
Vishnu Nair958da932020-08-21 17:12:37 -07006407
Prabir Pradhan99987712020-11-10 18:43:05 -08006408void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006409 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006410 return;
6411 }
6412
6413 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6414
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006415 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006416 setPointerCaptureLocked(false);
6417 }
6418
6419 if (!mWindowTokenWithPointerCapture) {
6420 // No need to send capture changes because no window has capture.
6421 return;
6422 }
6423
6424 if (mPendingEvent != nullptr) {
6425 // Move the pending event to the front of the queue. This will give the chance
6426 // for the pending event to be dropped if it is a captured event.
6427 mInboundQueue.push_front(mPendingEvent);
6428 mPendingEvent = nullptr;
6429 }
6430
6431 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006432 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006433 mInboundQueue.push_front(std::move(entry));
6434}
6435
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006436void InputDispatcher::setPointerCaptureLocked(bool enable) {
6437 mCurrentPointerCaptureRequest.enable = enable;
6438 mCurrentPointerCaptureRequest.seq++;
6439 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006440 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006441 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006442 };
6443 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006444}
6445
Vishnu Nair599f1412021-06-21 10:39:58 -07006446void InputDispatcher::displayRemoved(int32_t displayId) {
6447 { // acquire lock
6448 std::scoped_lock _l(mLock);
6449 // Set an empty list to remove all handles from the specific display.
6450 setInputWindowsLocked(/* window handles */ {}, displayId);
6451 setFocusedApplicationLocked(displayId, nullptr);
6452 // Call focus resolver to clean up stale requests. This must be called after input windows
6453 // have been removed for the removed display.
6454 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006455 // Reset pointer capture eligibility, regardless of previous state.
6456 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006457 // Remove the associated touch mode state.
6458 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006459 } // release lock
6460
6461 // Wake up poll loop since it may need to make new input dispatching choices.
6462 mLooper->wake();
6463}
6464
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006465void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6466 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006467 // The listener sends the windows as a flattened array. Separate the windows by display for
6468 // more convenient parsing.
6469 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006470 for (const auto& info : windowInfos) {
6471 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006472 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006473 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006474
6475 { // acquire lock
6476 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006477
6478 // Ensure that we have an entry created for all existing displays so that if a displayId has
6479 // no windows, we can tell that the windows were removed from the display.
6480 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6481 handlesPerDisplay[displayId];
6482 }
6483
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006484 mDisplayInfos.clear();
6485 for (const auto& displayInfo : displayInfos) {
6486 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6487 }
6488
6489 for (const auto& [displayId, handles] : handlesPerDisplay) {
6490 setInputWindowsLocked(handles, displayId);
6491 }
6492 }
6493 // Wake up poll loop since it may need to make new input dispatching choices.
6494 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006495}
6496
Vishnu Nair062a8672021-09-03 16:07:44 -07006497bool InputDispatcher::shouldDropInput(
6498 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006499 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6500 (windowHandle->getInfo()->inputConfig.test(
6501 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006502 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006503 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6504 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006505 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006506 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006507 windowHandle->getInfo()->displayId);
6508 return true;
6509 }
6510 return false;
6511}
6512
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006513void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6514 const std::vector<gui::WindowInfo>& windowInfos,
6515 const std::vector<DisplayInfo>& displayInfos) {
6516 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6517}
6518
Arthur Hungdfd528e2021-12-08 13:23:04 +00006519void InputDispatcher::cancelCurrentTouch() {
6520 {
6521 std::scoped_lock _l(mLock);
6522 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006523 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006524 "cancel current touch");
6525 synthesizeCancelationEventsForAllConnectionsLocked(options);
6526
6527 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006528 }
6529 // Wake up poll loop since there might be work to do.
6530 mLooper->wake();
6531}
6532
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006533void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6534 std::scoped_lock _l(mLock);
6535 mMonitorDispatchingTimeout = timeout;
6536}
6537
Arthur Hungc539dbb2022-12-08 07:45:36 +00006538void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6539 const sp<WindowInfoHandle>& oldWindowHandle,
6540 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006541 TouchState& state, int32_t pointerId,
6542 std::vector<InputTarget>& targets) {
6543 BitSet32 pointerIds;
6544 pointerIds.markBit(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006545 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6546 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6547 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6548 newWindowHandle->getInfo()->inputConfig.test(
6549 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6550 const sp<WindowInfoHandle> oldWallpaper =
6551 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6552 const sp<WindowInfoHandle> newWallpaper =
6553 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6554 if (oldWallpaper == newWallpaper) {
6555 return;
6556 }
6557
6558 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006559 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6560 addWindowTargetLocked(oldWallpaper,
6561 oldTouchedWindow.targetFlags |
6562 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6563 pointerIds, oldTouchedWindow.firstDownTimeInTarget, targets);
6564 state.removeTouchedPointerFromWindow(pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006565 }
6566
6567 if (newWallpaper != nullptr) {
6568 state.addOrUpdateWindow(newWallpaper,
6569 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6570 InputTarget::Flags::WINDOW_IS_OBSCURED |
6571 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6572 pointerIds);
6573 }
6574}
6575
6576void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6577 ftl::Flags<InputTarget::Flags> newTargetFlags,
6578 const sp<WindowInfoHandle> fromWindowHandle,
6579 const sp<WindowInfoHandle> toWindowHandle,
6580 TouchState& state, const BitSet32& pointerIds) {
6581 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6582 fromWindowHandle->getInfo()->inputConfig.test(
6583 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6584 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6585 toWindowHandle->getInfo()->inputConfig.test(
6586 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6587
6588 const sp<WindowInfoHandle> oldWallpaper =
6589 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6590 const sp<WindowInfoHandle> newWallpaper =
6591 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6592 if (oldWallpaper == newWallpaper) {
6593 return;
6594 }
6595
6596 if (oldWallpaper != nullptr) {
6597 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6598 "transferring touch focus to another window");
6599 state.removeWindowByToken(oldWallpaper->getToken());
6600 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6601 }
6602
6603 if (newWallpaper != nullptr) {
6604 nsecs_t downTimeInTarget = now();
6605 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6606 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6607 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6608 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6609 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
6610 sp<Connection> wallpaperConnection = getConnectionLocked(newWallpaper->getToken());
6611 if (wallpaperConnection != nullptr) {
6612 sp<Connection> toConnection = getConnectionLocked(toWindowHandle->getToken());
6613 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6614 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6615 wallpaperFlags);
6616 }
6617 }
6618}
6619
6620sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6621 const sp<WindowInfoHandle>& windowHandle) const {
6622 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6623 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6624 bool foundWindow = false;
6625 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6626 if (!foundWindow && otherHandle != windowHandle) {
6627 continue;
6628 }
6629 if (windowHandle == otherHandle) {
6630 foundWindow = true;
6631 continue;
6632 }
6633
6634 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6635 return otherHandle;
6636 }
6637 }
6638 return nullptr;
6639}
6640
Garfield Tane84e6f92019-08-29 17:28:41 -07006641} // namespace android::inputdispatcher