blob: 143d25ce4418da99ccc66b3df0423e63fbb5d7ed [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;
Harry Cutts33476232023-01-30 19:57:29 +0000673 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674 }
675}
676
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700677status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700678 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700679 return ALREADY_EXISTS;
680 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700681 mThread = std::make_unique<InputThread>(
682 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
683 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700684}
685
686status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700687 if (mThread && mThread->isCallingThread()) {
688 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700689 return INVALID_OPERATION;
690 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700691 mThread.reset();
692 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700693}
694
Michael Wrightd02c5b62014-02-10 15:10:22 -0800695void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700696 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800697 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800698 std::scoped_lock _l(mLock);
699 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800700
701 // Run a dispatch loop if there are no pending commands.
702 // The dispatch loop might enqueue commands to run afterwards.
703 if (!haveCommandsLocked()) {
704 dispatchOnceInnerLocked(&nextWakeupTime);
705 }
706
707 // Run all pending commands if there are any.
708 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000709 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700710 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800711 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800712
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700713 // If we are still waiting for ack on some events,
714 // we might have to wake up earlier to check if an app is anr'ing.
715 const nsecs_t nextAnrCheck = processAnrsLocked();
716 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
717
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800718 // We are about to enter an infinitely long sleep, because we have no commands or
719 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700720 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800721 mDispatcherEnteredIdle.notify_all();
722 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800723 } // release lock
724
725 // Wait for callback or timeout or wake. (make sure we round up, not down)
726 nsecs_t currentTime = now();
727 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
728 mLooper->pollOnce(timeoutMillis);
729}
730
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700731/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500732 * Raise ANR if there is no focused window.
733 * Before the ANR is raised, do a final state check:
734 * 1. The currently focused application must be the same one we are waiting for.
735 * 2. Ensure we still don't have a focused window.
736 */
737void InputDispatcher::processNoFocusedWindowAnrLocked() {
738 // Check if the application that we are waiting for is still focused.
739 std::shared_ptr<InputApplicationHandle> focusedApplication =
740 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
741 if (focusedApplication == nullptr ||
742 focusedApplication->getApplicationToken() !=
743 mAwaitedFocusedApplication->getApplicationToken()) {
744 // Unexpected because we should have reset the ANR timer when focused application changed
745 ALOGE("Waited for a focused window, but focused application has already changed to %s",
746 focusedApplication->getName().c_str());
747 return; // The focused application has changed.
748 }
749
chaviw98318de2021-05-19 16:45:23 -0500750 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500751 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
752 if (focusedWindowHandle != nullptr) {
753 return; // We now have a focused window. No need for ANR.
754 }
755 onAnrLocked(mAwaitedFocusedApplication);
756}
757
758/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700759 * Check if any of the connections' wait queues have events that are too old.
760 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
761 * Return the time at which we should wake up next.
762 */
763nsecs_t InputDispatcher::processAnrsLocked() {
764 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700765 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700766 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
767 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
768 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500769 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700770 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500771 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700772 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700773 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500774 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700775 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
776 }
777 }
778
779 // Check if any connection ANRs are due
780 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
781 if (currentTime < nextAnrCheck) { // most likely scenario
782 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
783 }
784
785 // If we reached here, we have an unresponsive connection.
786 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
787 if (connection == nullptr) {
788 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
789 return nextAnrCheck;
790 }
791 connection->responsive = false;
792 // Stop waking up for this unresponsive connection
793 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000794 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700795 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700796}
797
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800798std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
799 const sp<Connection>& connection) {
800 if (connection->monitor) {
801 return mMonitorDispatchingTimeout;
802 }
803 const sp<WindowInfoHandle> window =
804 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700805 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500806 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700807 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500808 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700809}
810
Michael Wrightd02c5b62014-02-10 15:10:22 -0800811void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
812 nsecs_t currentTime = now();
813
Jeff Browndc5992e2014-04-11 01:27:26 -0700814 // Reset the key repeat timer whenever normal dispatch is suspended while the
815 // device is in a non-interactive state. This is to ensure that we abort a key
816 // repeat if the device is just coming out of sleep.
817 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818 resetKeyRepeatLocked();
819 }
820
821 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
822 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100823 if (DEBUG_FOCUS) {
824 ALOGD("Dispatch frozen. Waiting some more.");
825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800826 return;
827 }
828
829 // Optimize latency of app switches.
830 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
831 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
832 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
833 if (mAppSwitchDueTime < *nextWakeupTime) {
834 *nextWakeupTime = mAppSwitchDueTime;
835 }
836
837 // Ready to start a new event.
838 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700839 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700840 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841 if (isAppSwitchDue) {
842 // The inbound queue is empty so the app switch key we were waiting
843 // for will never arrive. Stop waiting for it.
844 resetPendingAppSwitchLocked(false);
845 isAppSwitchDue = false;
846 }
847
848 // Synthesize a key repeat if appropriate.
849 if (mKeyRepeatState.lastKeyEntry) {
850 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
851 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
852 } else {
853 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
854 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
855 }
856 }
857 }
858
859 // Nothing to do if there is no pending event.
860 if (!mPendingEvent) {
861 return;
862 }
863 } else {
864 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700865 mPendingEvent = mInboundQueue.front();
866 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 traceInboundQueueLengthLocked();
868 }
869
870 // Poke user activity for this event.
871 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700872 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 }
875
876 // Now we have an event to dispatch.
877 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700878 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800879 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700880 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700882 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700884 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800885 }
886
887 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700888 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889 }
890
891 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700892 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700893 const ConfigurationChangedEntry& typedEntry =
894 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700895 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700896 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700897 break;
898 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700900 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700901 const DeviceResetEntry& typedEntry =
902 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700903 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700904 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700905 break;
906 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100908 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700909 std::shared_ptr<FocusEntry> typedEntry =
910 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100911 dispatchFocusLocked(currentTime, typedEntry);
912 done = true;
913 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
914 break;
915 }
916
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700917 case EventEntry::Type::TOUCH_MODE_CHANGED: {
918 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
919 dispatchTouchModeChangeLocked(currentTime, typedEntry);
920 done = true;
921 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
922 break;
923 }
924
Prabir Pradhan99987712020-11-10 18:43:05 -0800925 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
926 const auto typedEntry =
927 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
928 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
929 done = true;
930 break;
931 }
932
arthurhungb89ccb02020-12-30 16:19:01 +0800933 case EventEntry::Type::DRAG: {
934 std::shared_ptr<DragEntry> typedEntry =
935 std::static_pointer_cast<DragEntry>(mPendingEvent);
936 dispatchDragLocked(currentTime, typedEntry);
937 done = true;
938 break;
939 }
940
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700941 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700942 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700943 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700944 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700945 resetPendingAppSwitchLocked(true);
946 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700947 } else if (dropReason == DropReason::NOT_DROPPED) {
948 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700949 }
950 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700951 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700952 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700953 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700954 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
955 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700956 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700957 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700958 break;
959 }
960
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700961 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700962 std::shared_ptr<MotionEntry> motionEntry =
963 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700964 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
965 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700967 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700968 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700969 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700970 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
971 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700972 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700973 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700974 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800975 }
Chris Yef59a2f42020-10-16 12:55:26 -0700976
977 case EventEntry::Type::SENSOR: {
978 std::shared_ptr<SensorEntry> sensorEntry =
979 std::static_pointer_cast<SensorEntry>(mPendingEvent);
980 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
981 dropReason = DropReason::APP_SWITCH;
982 }
983 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
984 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
985 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
986 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
987 dropReason = DropReason::STALE;
988 }
989 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
990 done = true;
991 break;
992 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993 }
994
995 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700996 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700997 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998 }
Michael Wright3a981722015-06-10 15:26:13 +0100999 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000
1001 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001002 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 }
1004}
1005
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001006bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1007 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1008}
1009
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001010/**
1011 * Return true if the events preceding this incoming motion event should be dropped
1012 * Return false otherwise (the default behaviour)
1013 */
1014bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001015 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001016 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001017
1018 // Optimize case where the current application is unresponsive and the user
1019 // decides to touch a window in a different application.
1020 // If the application takes too long to catch up then we drop all events preceding
1021 // the touch into the other window.
1022 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001023 const int32_t displayId = motionEntry.displayId;
1024 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001025 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001026
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001027 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001028 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001029 touchedWindowHandle->getApplicationToken() !=
1030 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001031 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001032 ALOGI("Pruning input queue because user touched a different application while waiting "
1033 "for %s",
1034 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001035 return true;
1036 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001037
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001038 // Alternatively, maybe there's a spy window that could handle this event.
1039 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1040 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1041 for (const auto& windowHandle : touchedSpies) {
1042 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001043 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001044 // This spy window could take more input. Drop all events preceding this
1045 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001046 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001047 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001048 mAwaitedFocusedApplication->getName().c_str());
1049 return true;
1050 }
1051 }
1052 }
1053
1054 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1055 // yet been processed by some connections, the dispatcher will wait for these motion
1056 // events to be processed before dispatching the key event. This is because these motion events
1057 // may cause a new window to be launched, which the user might expect to receive focus.
1058 // To prevent waiting forever for such events, just send the key to the currently focused window
1059 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1060 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1061 "just send the pending key event to the focused window.");
1062 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001063 }
1064 return false;
1065}
1066
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001067bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001068 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001069 mInboundQueue.push_back(std::move(newEntry));
1070 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071 traceInboundQueueLengthLocked();
1072
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001073 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001074 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001075 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1076 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001077 // Optimize app switch latency.
1078 // If the application takes too long to catch up then we drop all events preceding
1079 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001080 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001081 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001082 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001083 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001084 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001085 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001086 if (DEBUG_APP_SWITCH) {
1087 ALOGD("App switch is pending!");
1088 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001089 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001090 mAppSwitchSawKeyDown = false;
1091 needWake = true;
1092 }
1093 }
1094 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001095
1096 // If a new up event comes in, and the pending event with same key code has been asked
1097 // to try again later because of the policy. We have to reset the intercept key wake up
1098 // time for it may have been handled in the policy and could be dropped.
1099 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1100 mPendingEvent->type == EventEntry::Type::KEY) {
1101 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1102 if (pendingKey.keyCode == keyEntry.keyCode &&
1103 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001104 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1105 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001106 pendingKey.interceptKeyWakeupTime = 0;
1107 needWake = true;
1108 }
1109 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001110 break;
1111 }
1112
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001113 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001114 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1115 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001116 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1117 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001118 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001119 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001120 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001121 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001122 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001123 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1124 break;
1125 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001126 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001127 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001128 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001129 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001130 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1131 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001132 // nothing to do
1133 break;
1134 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001135 }
1136
1137 return needWake;
1138}
1139
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001140void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001141 // Do not store sensor event in recent queue to avoid flooding the queue.
1142 if (entry->type != EventEntry::Type::SENSOR) {
1143 mRecentQueue.push_back(entry);
1144 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001145 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001146 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 }
1148}
1149
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001150std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
1151InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x, int32_t y, bool isStylus,
1152 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001154 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001155 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001156 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001157 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001158 continue;
1159 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001161 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001162 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001163 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001164 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001165
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001166 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1167 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
1168 BitSet32(0), /*firstDownTimeInTarget=*/std::nullopt,
1169 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170 }
1171 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001172 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173}
1174
Prabir Pradhand65552b2021-10-07 11:23:50 -07001175std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1176 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001177 // Traverse windows from front to back and gather the touched spy windows.
1178 std::vector<sp<WindowInfoHandle>> spyWindows;
1179 const auto& windowHandles = getWindowHandlesLocked(displayId);
1180 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1181 const WindowInfo& info = *windowHandle->getInfo();
1182
Prabir Pradhand65552b2021-10-07 11:23:50 -07001183 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001184 continue;
1185 }
1186 if (!info.isSpy()) {
1187 // The first touched non-spy window was found, so return the spy windows touched so far.
1188 return spyWindows;
1189 }
1190 spyWindows.push_back(windowHandle);
1191 }
1192 return spyWindows;
1193}
1194
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001195void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 const char* reason;
1197 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001198 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001199 if (DEBUG_INBOUND_EVENT_DETAILS) {
1200 ALOGD("Dropped event because policy consumed it.");
1201 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001202 reason = "inbound event was dropped because the policy consumed it";
1203 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001204 case DropReason::DISABLED:
1205 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001206 ALOGI("Dropped event because input dispatch is disabled.");
1207 }
1208 reason = "inbound event was dropped because input dispatch is disabled";
1209 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001210 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001211 ALOGI("Dropped event because of pending overdue app switch.");
1212 reason = "inbound event was dropped because of pending overdue app switch";
1213 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001214 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001215 ALOGI("Dropped event because the current application is not responding and the user "
1216 "has started interacting with a different application.");
1217 reason = "inbound event was dropped because the current application is not responding "
1218 "and the user has started interacting with a different application";
1219 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001220 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001221 ALOGI("Dropped event because it is stale.");
1222 reason = "inbound event was dropped because it is stale";
1223 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001224 case DropReason::NO_POINTER_CAPTURE:
1225 ALOGI("Dropped event because there is no window with Pointer Capture.");
1226 reason = "inbound event was dropped because there is no window with Pointer Capture";
1227 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001228 case DropReason::NOT_DROPPED: {
1229 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001230 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001231 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 }
1233
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001234 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001235 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001236 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001238 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001240 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001241 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1242 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001243 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001244 synthesizeCancelationEventsForAllConnectionsLocked(options);
1245 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001246 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1247 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001248 synthesizeCancelationEventsForAllConnectionsLocked(options);
1249 }
1250 break;
1251 }
Chris Yef59a2f42020-10-16 12:55:26 -07001252 case EventEntry::Type::SENSOR: {
1253 break;
1254 }
arthurhungb89ccb02020-12-30 16:19:01 +08001255 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1256 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001257 break;
1258 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001259 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001260 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001261 case EventEntry::Type::CONFIGURATION_CHANGED:
1262 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001263 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001264 break;
1265 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266 }
1267}
1268
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001269static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001270 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1271 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272}
1273
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001274bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1275 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1276 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1277 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278}
1279
1280bool InputDispatcher::isAppSwitchPendingLocked() {
Colin Cross5b799302022-10-18 21:52:41 -07001281 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282}
1283
1284void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001285 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001287 if (DEBUG_APP_SWITCH) {
1288 if (handled) {
1289 ALOGD("App switch has arrived.");
1290 } else {
1291 ALOGD("App switch was abandoned.");
1292 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294}
1295
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001297 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298}
1299
Prabir Pradhancef936d2021-07-21 16:17:52 +00001300bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001301 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 return false;
1303 }
1304
1305 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001306 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001307 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001308 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1309 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001310 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001311 return true;
1312}
1313
Prabir Pradhancef936d2021-07-21 16:17:52 +00001314void InputDispatcher::postCommandLocked(Command&& command) {
1315 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316}
1317
1318void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001319 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001320 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001321 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 releaseInboundEventLocked(entry);
1323 }
1324 traceInboundQueueLengthLocked();
1325}
1326
1327void InputDispatcher::releasePendingEventLocked() {
1328 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001330 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331 }
1332}
1333
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001334void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001336 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001337 if (DEBUG_DISPATCH_CYCLE) {
1338 ALOGD("Injected inbound event was dropped.");
1339 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001340 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341 }
1342 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001343 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344 }
1345 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001346}
1347
1348void InputDispatcher::resetKeyRepeatLocked() {
1349 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001350 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001351 }
1352}
1353
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001354std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1355 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356
Michael Wright2e732952014-09-24 13:26:59 -07001357 uint32_t policyFlags = entry->policyFlags &
1358 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001359
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001360 std::shared_ptr<KeyEntry> newEntry =
1361 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1362 entry->source, entry->displayId, policyFlags, entry->action,
1363 entry->flags, entry->keyCode, entry->scanCode,
1364 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001366 newEntry->syntheticRepeat = true;
1367 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001368 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001369 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370}
1371
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001372bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001373 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001374 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1375 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1376 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377
1378 // Reset key repeating in case a keyboard device was added or removed or something.
1379 resetKeyRepeatLocked();
1380
1381 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001382 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1383 scoped_unlock unlock(mLock);
1384 mPolicy->notifyConfigurationChanged(eventTime);
1385 };
1386 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387 return true;
1388}
1389
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001390bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1391 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001392 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1393 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1394 entry.deviceId);
1395 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396
liushenxiang42232912021-05-21 20:24:09 +08001397 // Reset key repeating in case a keyboard device was disabled or enabled.
1398 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1399 resetKeyRepeatLocked();
1400 }
1401
Michael Wrightfb04fd52022-11-24 22:31:11 +00001402 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001403 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001404 synthesizeCancelationEventsForAllConnectionsLocked(options);
1405 return true;
1406}
1407
Vishnu Nairad321cd2020-08-20 16:40:21 -07001408void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001409 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001410 if (mPendingEvent != nullptr) {
1411 // Move the pending event to the front of the queue. This will give the chance
1412 // for the pending event to get dispatched to the newly focused window
1413 mInboundQueue.push_front(mPendingEvent);
1414 mPendingEvent = nullptr;
1415 }
1416
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001417 std::unique_ptr<FocusEntry> focusEntry =
1418 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1419 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001420
1421 // This event should go to the front of the queue, but behind all other focus events
1422 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001423 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001424 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001425 [](const std::shared_ptr<EventEntry>& event) {
1426 return event->type == EventEntry::Type::FOCUS;
1427 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001428
1429 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001430 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001431}
1432
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001433void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001434 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001435 if (channel == nullptr) {
1436 return; // Window has gone away
1437 }
1438 InputTarget target;
1439 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001440 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001441 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001442 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1443 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001444 std::string reason = std::string("reason=").append(entry->reason);
1445 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001446 dispatchEventLocked(currentTime, entry, {target});
1447}
1448
Prabir Pradhan99987712020-11-10 18:43:05 -08001449void InputDispatcher::dispatchPointerCaptureChangedLocked(
1450 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1451 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001452 dropReason = DropReason::NOT_DROPPED;
1453
Prabir Pradhan99987712020-11-10 18:43:05 -08001454 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001455 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001456
1457 if (entry->pointerCaptureRequest.enable) {
1458 // Enable Pointer Capture.
1459 if (haveWindowWithPointerCapture &&
1460 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001461 // This can happen if pointer capture is disabled and re-enabled before we notify the
1462 // app of the state change, so there is no need to notify the app.
1463 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1464 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001465 }
1466 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001467 // This can happen if a window requests capture and immediately releases capture.
1468 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001469 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001470 return;
1471 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001472 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1473 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1474 return;
1475 }
1476
Vishnu Nairc519ff72021-01-21 08:23:08 -08001477 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001478 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1479 mWindowTokenWithPointerCapture = token;
1480 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001481 // Disable Pointer Capture.
1482 // We do not check if the sequence number matches for requests to disable Pointer Capture
1483 // for two reasons:
1484 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1485 // to disable capture with the same sequence number: one generated by
1486 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1487 // Capture being disabled in InputReader.
1488 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1489 // actual Pointer Capture state that affects events being generated by input devices is
1490 // in InputReader.
1491 if (!haveWindowWithPointerCapture) {
1492 // Pointer capture was already forcefully disabled because of focus change.
1493 dropReason = DropReason::NOT_DROPPED;
1494 return;
1495 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001496 token = mWindowTokenWithPointerCapture;
1497 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001498 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001499 setPointerCaptureLocked(false);
1500 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001501 }
1502
1503 auto channel = getInputChannelLocked(token);
1504 if (channel == nullptr) {
1505 // Window has gone away, clean up Pointer Capture state.
1506 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001507 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001508 setPointerCaptureLocked(false);
1509 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001510 return;
1511 }
1512 InputTarget target;
1513 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001514 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001515 entry->dispatchInProgress = true;
1516 dispatchEventLocked(currentTime, entry, {target});
1517
1518 dropReason = DropReason::NOT_DROPPED;
1519}
1520
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001521void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1522 const std::shared_ptr<TouchModeEntry>& entry) {
1523 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001524 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001525 if (windowHandles.empty()) {
1526 return;
1527 }
1528 const std::vector<InputTarget> inputTargets =
1529 getInputTargetsFromWindowHandlesLocked(windowHandles);
1530 if (inputTargets.empty()) {
1531 return;
1532 }
1533 entry->dispatchInProgress = true;
1534 dispatchEventLocked(currentTime, entry, inputTargets);
1535}
1536
1537std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1538 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1539 std::vector<InputTarget> inputTargets;
1540 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001541 const sp<IBinder>& token = handle->getToken();
1542 if (token == nullptr) {
1543 continue;
1544 }
1545 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1546 if (channel == nullptr) {
1547 continue; // Window has gone away
1548 }
1549 InputTarget target;
1550 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001551 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001552 inputTargets.push_back(target);
1553 }
1554 return inputTargets;
1555}
1556
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001557bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001558 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001560 if (!entry->dispatchInProgress) {
1561 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1562 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1563 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1564 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001565 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001566 // We have seen two identical key downs in a row which indicates that the device
1567 // driver is automatically generating key repeats itself. We take note of the
1568 // repeat here, but we disable our own next key repeat timer since it is clear that
1569 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001570 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1571 // Make sure we don't get key down from a different device. If a different
1572 // device Id has same key pressed down, the new device Id will replace the
1573 // current one to hold the key repeat with repeat count reset.
1574 // In the future when got a KEY_UP on the device id, drop it and do not
1575 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1577 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001578 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579 } else {
1580 // Not a repeat. Save key down state in case we do see a repeat later.
1581 resetKeyRepeatLocked();
1582 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1583 }
1584 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001585 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1586 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001587 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001588 if (DEBUG_INBOUND_EVENT_DETAILS) {
1589 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1590 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001591 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 resetKeyRepeatLocked();
1593 }
1594
1595 if (entry->repeatCount == 1) {
1596 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1597 } else {
1598 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1599 }
1600
1601 entry->dispatchInProgress = true;
1602
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001603 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604 }
1605
1606 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001607 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608 if (currentTime < entry->interceptKeyWakeupTime) {
1609 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1610 *nextWakeupTime = entry->interceptKeyWakeupTime;
1611 }
1612 return false; // wait until next wakeup
1613 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001614 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 entry->interceptKeyWakeupTime = 0;
1616 }
1617
1618 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001619 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001620 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001621 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001622 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001623
1624 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1625 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1626 };
1627 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628 return false; // wait for the command to run
1629 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001630 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001631 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001632 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001633 if (*dropReason == DropReason::NOT_DROPPED) {
1634 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635 }
1636 }
1637
1638 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001639 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001640 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001641 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1642 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001643 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644 return true;
1645 }
1646
1647 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001648 InputEventInjectionResult injectionResult;
1649 sp<WindowInfoHandle> focusedWindow =
1650 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1651 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001652 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001653 return false;
1654 }
1655
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001656 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001657 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658 return true;
1659 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001660 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1661
1662 std::vector<InputTarget> inputTargets;
1663 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001664 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001665 BitSet32(0), getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001667 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001668 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669
1670 // Dispatch the key.
1671 dispatchEventLocked(currentTime, entry, inputTargets);
1672 return true;
1673}
1674
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001675void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001676 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1677 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1678 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1679 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1680 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1681 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1682 entry.metaState, entry.repeatCount, entry.downTime);
1683 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684}
1685
Prabir Pradhancef936d2021-07-21 16:17:52 +00001686void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1687 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001688 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001689 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1690 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1691 "source=0x%x, sensorType=%s",
1692 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001693 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001694 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001695 auto command = [this, entry]() REQUIRES(mLock) {
1696 scoped_unlock unlock(mLock);
1697
1698 if (entry->accuracyChanged) {
1699 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1700 }
1701 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1702 entry->hwTimestamp, entry->values);
1703 };
1704 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001705}
1706
1707bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001708 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1709 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001710 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001711 }
Chris Yef59a2f42020-10-16 12:55:26 -07001712 { // acquire lock
1713 std::scoped_lock _l(mLock);
1714
1715 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1716 std::shared_ptr<EventEntry> entry = *it;
1717 if (entry->type == EventEntry::Type::SENSOR) {
1718 it = mInboundQueue.erase(it);
1719 releaseInboundEventLocked(entry);
1720 }
1721 }
1722 }
1723 return true;
1724}
1725
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001726bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001727 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001728 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001730 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001731 entry->dispatchInProgress = true;
1732
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001733 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734 }
1735
1736 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001737 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001738 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001739 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1740 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741 return true;
1742 }
1743
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001744 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745
1746 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001747 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748
1749 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001750 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 if (isPointerEvent) {
1752 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001753
1754 if (mDragState &&
1755 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1756 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1757 pilferPointersLocked(mDragState->dragWindow->getToken());
1758 }
1759
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001760 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001761 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001762 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001763 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1764 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765 } else {
1766 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001767 sp<WindowInfoHandle> focusedWindow =
1768 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1769 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1770 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1771 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001772 InputTarget::Flags::FOREGROUND |
1773 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001774 BitSet32(0), getDownTime(*entry), inputTargets);
1775 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001777 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778 return false;
1779 }
1780
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001781 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001782 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001783 return true;
1784 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001785 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001786 CancelationOptions::Mode mode(
1787 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1788 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001789 CancelationOptions options(mode, "input event injection failed");
1790 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791 return true;
1792 }
1793
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001794 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001795 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796
1797 // Dispatch the motion.
1798 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001799 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001800 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001801 synthesizeCancelationEventsForAllConnectionsLocked(options);
1802 }
1803 dispatchEventLocked(currentTime, entry, inputTargets);
1804 return true;
1805}
1806
chaviw98318de2021-05-19 16:45:23 -05001807void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001808 bool isExiting, const int32_t rawX,
1809 const int32_t rawY) {
1810 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001811 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001812 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1813 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001814
1815 enqueueInboundEventLocked(std::move(dragEntry));
1816}
1817
1818void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1819 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1820 if (channel == nullptr) {
1821 return; // Window has gone away
1822 }
1823 InputTarget target;
1824 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001825 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001826 entry->dispatchInProgress = true;
1827 dispatchEventLocked(currentTime, entry, {target});
1828}
1829
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001830void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001831 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001832 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001833 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001834 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001835 "metaState=0x%x, buttonState=0x%x,"
1836 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001837 prefix, entry.eventTime, entry.deviceId,
1838 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1839 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1840 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1841 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001843 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1844 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1845 "x=%f, y=%f, pressure=%f, size=%f, "
1846 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1847 "orientation=%f",
1848 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1849 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1850 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1851 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1852 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1853 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1854 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1855 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1856 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1857 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1858 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860}
1861
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001862void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1863 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001864 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001865 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001866 if (DEBUG_DISPATCH_CYCLE) {
1867 ALOGD("dispatchEventToCurrentInputTargets");
1868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001870 updateInteractionTokensLocked(*eventEntry, inputTargets);
1871
Michael Wrightd02c5b62014-02-10 15:10:22 -08001872 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1873
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001874 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001876 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001877 sp<Connection> connection =
1878 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001879 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001880 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001882 if (DEBUG_FOCUS) {
1883 ALOGD("Dropping event delivery to target with channel '%s' because it "
1884 "is no longer registered with the input dispatcher.",
1885 inputTarget.inputChannel->getName().c_str());
1886 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887 }
1888 }
1889}
1890
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001891void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1892 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1893 // If the policy decides to close the app, we will get a channel removal event via
1894 // unregisterInputChannel, and will clean up the connection that way. We are already not
1895 // sending new pointers to the connection when it blocked, but focused events will continue to
1896 // pile up.
1897 ALOGW("Canceling events for %s because it is unresponsive",
1898 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001899 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001900 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001901 "application not responding");
1902 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903 }
1904}
1905
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001906void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001907 if (DEBUG_FOCUS) {
1908 ALOGD("Resetting ANR timeouts.");
1909 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910
1911 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001912 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001913 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914}
1915
Tiger Huang721e26f2018-07-24 22:26:19 +08001916/**
1917 * Get the display id that the given event should go to. If this event specifies a valid display id,
1918 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1919 * Focused display is the display that the user most recently interacted with.
1920 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001921int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001922 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001923 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001924 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001925 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1926 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001927 break;
1928 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001929 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001930 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1931 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001932 break;
1933 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001934 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001935 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001936 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001937 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001938 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001939 case EventEntry::Type::SENSOR:
1940 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001941 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001942 return ADISPLAY_ID_NONE;
1943 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001944 }
1945 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1946}
1947
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001948bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1949 const char* focusedWindowName) {
1950 if (mAnrTracker.empty()) {
1951 // already processed all events that we waited for
1952 mKeyIsWaitingForEventsTimeout = std::nullopt;
1953 return false;
1954 }
1955
1956 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1957 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001958 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001959 mKeyIsWaitingForEventsTimeout = currentTime +
1960 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1961 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001962 return true;
1963 }
1964
1965 // We still have pending events, and already started the timer
1966 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1967 return true; // Still waiting
1968 }
1969
1970 // Waited too long, and some connection still hasn't processed all motions
1971 // Just send the key to the focused window
1972 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1973 focusedWindowName);
1974 mKeyIsWaitingForEventsTimeout = std::nullopt;
1975 return false;
1976}
1977
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001978sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
1979 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
1980 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001981 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001982 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983
Tiger Huang721e26f2018-07-24 22:26:19 +08001984 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001985 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001986 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001987 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1988
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989 // If there is no currently focused window and no focused application
1990 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001991 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1992 ALOGI("Dropping %s event because there is no focused window or focused application in "
1993 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001994 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001995 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001996 }
1997
Vishnu Nair062a8672021-09-03 16:07:44 -07001998 // Drop key events if requested by input feature
1999 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002000 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002001 }
2002
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002003 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2004 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2005 // start interacting with another application via touch (app switch). This code can be removed
2006 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2007 // an app is expected to have a focused window.
2008 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2009 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2010 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002011 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2012 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2013 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002014 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002015 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002016 ALOGW("Waiting because no window has focus but %s may eventually add a "
2017 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002018 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002019 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002020 outInjectionResult = InputEventInjectionResult::PENDING;
2021 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002022 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2023 // Already raised ANR. Drop the event
2024 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002025 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002026 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002027 } else {
2028 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002029 outInjectionResult = InputEventInjectionResult::PENDING;
2030 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002031 }
2032 }
2033
2034 // we have a valid, non-null focused window
2035 resetNoFocusedWindowTimeoutLocked();
2036
Prabir Pradhan5735a322022-04-11 17:23:34 +00002037 // Verify targeted injection.
2038 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2039 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002040 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2041 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042 }
2043
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002044 if (focusedWindowHandle->getInfo()->inputConfig.test(
2045 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002046 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002047 outInjectionResult = InputEventInjectionResult::PENDING;
2048 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002049 }
2050
2051 // If the event is a key event, then we must wait for all previous events to
2052 // complete before delivering it because previous events may have the
2053 // side-effect of transferring focus to a different window and we want to
2054 // ensure that the following keys are sent to the new window.
2055 //
2056 // Suppose the user touches a button in a window then immediately presses "A".
2057 // If the button causes a pop-up window to appear then we want to ensure that
2058 // the "A" key is delivered to the new pop-up window. This is because users
2059 // often anticipate pending UI changes when typing on a keyboard.
2060 // To obtain this behavior, we must serialize key events with respect to all
2061 // prior input events.
2062 if (entry.type == EventEntry::Type::KEY) {
2063 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2064 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002065 outInjectionResult = InputEventInjectionResult::PENDING;
2066 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068 }
2069
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002070 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2071 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072}
2073
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002074/**
2075 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2076 * that are currently unresponsive.
2077 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002078std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2079 const std::vector<Monitor>& monitors) const {
2080 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002081 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002082 [this](const Monitor& monitor) REQUIRES(mLock) {
2083 sp<Connection> connection =
2084 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002085 if (connection == nullptr) {
2086 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002087 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002088 return false;
2089 }
2090 if (!connection->responsive) {
2091 ALOGW("Unresponsive monitor %s will not get the new gesture",
2092 connection->inputChannel->getName().c_str());
2093 return false;
2094 }
2095 return true;
2096 });
2097 return responsiveMonitors;
2098}
2099
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002100/**
2101 * In general, touch should be always split between windows. Some exceptions:
2102 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2103 * from the same device, *and* the window that's receiving the current pointer does not support
2104 * split touch.
2105 * 2. Don't split mouse events
2106 */
2107bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2108 const MotionEntry& entry) const {
2109 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2110 // We should never split mouse events
2111 return false;
2112 }
2113 for (const TouchedWindow& touchedWindow : touchState.windows) {
2114 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2115 // Spy windows should not affect whether or not touch is split.
2116 continue;
2117 }
2118 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2119 continue;
2120 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002121 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2122 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2123 // Wallpaper window should not affect whether or not touch is split
2124 continue;
2125 }
2126
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002127 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2128 // being sent there. For now, use deviceId from touch state.
2129 if (entry.deviceId == touchState.deviceId && !touchedWindow.pointerIds.isEmpty()) {
2130 return false;
2131 }
2132 }
2133 return true;
2134}
2135
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002136std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002137 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2138 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002139 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002141 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142 // For security reasons, we defer updating the touch state until we are sure that
2143 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002144 const int32_t displayId = entry.displayId;
2145 const int32_t action = entry.action;
2146 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147
2148 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002149 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002151 // Copy current touch state into tempTouchState.
2152 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2153 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002154 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002155 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002156 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2157 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002158 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002159 }
2160
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002161 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002162 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002163 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002164
2165 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2166 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2167 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002168 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2169 // touchable windows.
2170 const bool wasDown = oldState != nullptr && oldState->isDown();
2171 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2172 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
2173 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002174 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002175
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176 if (newGesture) {
2177 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002178 if (switchedDevice && tempTouchState.isDown() && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002179 ALOGI("Dropping event because a pointer for a different device is already down "
2180 "in display %" PRId32,
2181 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002182 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002183 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002184 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002185 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002186 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002187 tempTouchState.deviceId = entry.deviceId;
2188 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002189 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002190 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002191 ALOGI("Dropping move event because a pointer for a different device is already active "
2192 "in display %" PRId32,
2193 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002194 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002195 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002196 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197 }
2198
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002199 if (isHoverAction) {
2200 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2201 // all of the existing hovering pointers and recompute.
2202 tempTouchState.clearHoveringPointers();
2203 }
2204
Michael Wrightd02c5b62014-02-10 15:10:22 -08002205 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2206 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002207 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002208 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002209 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2210 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002211 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002212 auto [newTouchedWindowHandle, outsideTargets] =
2213 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002214
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002215 if (isDown) {
2216 targets += outsideTargets;
2217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002218 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002219 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002220 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2221 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002223 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002224 }
2225
Prabir Pradhan5735a322022-04-11 17:23:34 +00002226 // Verify targeted injection.
2227 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2228 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002229 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002230 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002231 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002232 }
2233
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002234 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002235 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002236 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2237 // New window supports splitting, but we should never split mouse events.
2238 isSplit = !isFromMouse;
2239 } else if (isSplit) {
2240 // New window does not support splitting but we have already split events.
2241 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002242 newTouchedWindowHandle = nullptr;
2243 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002244 } else {
2245 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002246 // be delivered to a new window which supports split touch. Pointers from a mouse device
2247 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002248 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002249 }
2250
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002251 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002252 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002253 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002254 // Process the foreground window first so that it is the first to receive the event.
2255 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002256 }
2257
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002258 if (newTouchedWindows.empty()) {
2259 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2260 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002261 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002262 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002263 }
2264
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002265 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002266 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002267 continue;
2268 }
2269
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002270 if (isHoverAction) {
2271 const int32_t pointerId = entry.pointerProperties[0].id;
2272 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2273 // Pointer left. Remove it
2274 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2275 } else {
2276 // The "windowHandle" is the target of this hovering pointer.
2277 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId,
2278 pointerId);
2279 }
2280 }
2281
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002282 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002283 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002284
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002285 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2286 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002287 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002288 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002289
2290 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002291 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002292 }
2293 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002294 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002295 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002296 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002297 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002298
2299 // Update the temporary touch state.
2300 BitSet32 pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002301 if (!isHoverAction) {
2302 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2303 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002304
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002305 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2306 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2307
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002308 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002309 isDownOrPointerDown
2310 ? std::make_optional(entry.eventTime)
2311 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002312
2313 // If this is the pointer going down and the touched window has a wallpaper
2314 // then also add the touched wallpaper windows so they are locked in for the duration
2315 // of the touch gesture.
2316 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2317 // engine only supports touch events. We would need to add a mechanism similar
2318 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002319 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002320 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2321 windowHandle->getInfo()->inputConfig.test(
2322 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2323 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2324 if (wallpaper != nullptr) {
2325 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2326 InputTarget::Flags::WINDOW_IS_OBSCURED |
2327 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2328 InputTarget::Flags::DISPATCH_AS_IS;
2329 if (isSplit) {
2330 wallpaperFlags |= InputTarget::Flags::SPLIT;
2331 }
2332 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2333 entry.eventTime);
2334 }
2335 }
2336 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002337 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002338
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002339 // If a window is already pilfering some pointers, give it this new pointer as well and
2340 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2341 // which is a specific behaviour that we want.
2342 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2343 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
2344 if (touchedWindow.pointerIds.hasBit(pointerId) &&
2345 touchedWindow.pilferedPointerIds.count() > 0) {
2346 // This window is already pilfering some pointers, and this new pointer is also
2347 // going to it. Therefore, take over this pointer and don't give it to anyone
2348 // else.
2349 touchedWindow.pilferedPointerIds.set(pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002350 }
2351 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002352
2353 // Restrict all pilfered pointers to the pilfering windows.
2354 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 } else {
2356 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2357
2358 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002359 if (!tempTouchState.isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002360 ALOGD_IF(DEBUG_FOCUS,
2361 "Dropping event because the pointer is not down or we previously "
2362 "dropped the pointer down event in display %" PRId32 ": %s",
2363 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002364 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002365 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366 }
2367
arthurhung6d4bed92021-03-17 11:59:33 +08002368 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002369
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002371 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002372 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002373 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002374 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002375 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002376 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002377 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002378
Prabir Pradhan5735a322022-04-11 17:23:34 +00002379 // Verify targeted injection.
2380 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2381 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002382 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002383 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002384 }
2385
Vishnu Nair062a8672021-09-03 16:07:44 -07002386 // Drop touch events if requested by input feature
2387 if (newTouchedWindowHandle != nullptr &&
2388 shouldDropInput(entry, newTouchedWindowHandle)) {
2389 newTouchedWindowHandle = nullptr;
2390 }
2391
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002392 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2393 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002394 if (DEBUG_FOCUS) {
2395 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2396 oldTouchedWindowHandle->getName().c_str(),
2397 newTouchedWindowHandle->getName().c_str(), displayId);
2398 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 // Make a slippery exit from the old window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002400 BitSet32 pointerIds;
2401 const int32_t pointerId = entry.pointerProperties[0].id;
2402 pointerIds.markBit(pointerId);
2403
2404 const TouchedWindow& touchedWindow =
2405 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2406 addWindowTargetLocked(oldTouchedWindowHandle,
2407 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
2408 touchedWindow.firstDownTimeInTarget, targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002409
2410 // Make a slippery entrance into the new window.
2411 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002412 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413 }
2414
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002415 ftl::Flags<InputTarget::Flags> targetFlags =
2416 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002417 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002418 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002419 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002421 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422 }
2423 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002424 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002425 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002426 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002427 }
2428
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002429 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2430 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002431
2432 // Check if the wallpaper window should deliver the corresponding event.
2433 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002434 tempTouchState, pointerId, targets);
2435 tempTouchState.removeTouchedPointerFromWindow(pointerId, oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436 }
2437 }
Arthur Hung96483742022-11-15 03:30:48 +00002438
2439 // Update the pointerIds for non-splittable when it received pointer down.
2440 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2441 // If no split, we suppose all touched windows should receive pointer down.
2442 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2443 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2444 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2445 // Ignore drag window for it should just track one pointer.
2446 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2447 continue;
2448 }
2449 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2450 }
2451 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452 }
2453
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002454 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002455 {
2456 std::vector<TouchedWindow> hoveringWindows =
2457 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2458 for (const TouchedWindow& touchedWindow : hoveringWindows) {
2459 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2460 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2461 targets);
2462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463 }
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002464 // Ensure that we have at least one foreground window or at least one window that cannot be a
2465 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2466 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2467 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002468 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2469 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002470 return !canReceiveForegroundTouches(
2471 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002472 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002473 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002474 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2475 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002476 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002477 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002478 }
2479
Prabir Pradhan5735a322022-04-11 17:23:34 +00002480 // Ensure that all touched windows are valid for injection.
2481 if (entry.injectionState != nullptr) {
2482 std::string errs;
2483 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002484 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002485 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2486 // dispatched to any uid, since the coords will be zeroed out later.
2487 continue;
2488 }
2489 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2490 if (err) errs += "\n - " + *err;
2491 }
2492 if (!errs.empty()) {
2493 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2494 "%d:%s",
2495 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002496 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002497 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002498 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002499 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002500
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002501 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2502 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002504 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002505 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002506 if (foregroundWindowHandle) {
2507 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002508 for (InputTarget& target : targets) {
2509 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2510 sp<WindowInfoHandle> targetWindow =
2511 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2512 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2513 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002514 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002515 }
2516 }
2517 }
2518 }
2519
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002520 // Success! Output targets from the touch state.
2521 tempTouchState.clearWindowsWithoutPointers();
2522 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002523 if (touchedWindow.pointerIds.isEmpty() &&
2524 !touchedWindow.hasHoveringPointers(entry.deviceId)) {
2525 // Windows with hovering pointers are getting persisted inside TouchState.
2526 // Do not send this event to those windows.
2527 continue;
2528 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002529 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2530 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2531 targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002532 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002533
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002534 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002535 // Drop the outside or hover touch windows since we will not care about them
2536 // in the next iteration.
2537 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002538
Michael Wrightd02c5b62014-02-10 15:10:22 -08002539 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002540 if (switchedDevice) {
2541 if (DEBUG_FOCUS) {
2542 ALOGD("Conflicting pointer actions: Switched to a different device.");
2543 }
2544 *outConflictingPointerActions = true;
2545 }
2546
2547 if (isHoverAction) {
2548 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002549 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002550 ALOGD_IF(DEBUG_FOCUS,
2551 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002552 *outConflictingPointerActions = true;
2553 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002554 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2555 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2556 tempTouchState.deviceId = entry.deviceId;
2557 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002558 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002559 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2560 // Pointer went up.
2561 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
2562 tempTouchState.clearWindowsWithoutPointers();
2563 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002564 // All pointers up or canceled.
2565 tempTouchState.reset();
2566 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2567 // First pointer went down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002568 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002569 ALOGD("Conflicting pointer actions: Down received while already down.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002570 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002571 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002572 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2573 // One pointer went up.
2574 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2575 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002576
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002577 for (size_t i = 0; i < tempTouchState.windows.size();) {
2578 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2579 touchedWindow.pointerIds.clearBit(pointerId);
2580 if (touchedWindow.pointerIds.isEmpty()) {
2581 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2582 continue;
2583 }
2584 i += 1;
2585 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586 }
2587
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002588 // Save changes unless the action was scroll in which case the temporary touch
2589 // state was only valid for this one action.
2590 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002591 if (displayId >= 0) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002592 mTouchStatesByDisplay[displayId] = tempTouchState;
2593 } else {
2594 mTouchStatesByDisplay.erase(displayId);
2595 }
2596 }
2597
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002598 if (tempTouchState.windows.empty()) {
2599 mTouchStatesByDisplay.erase(displayId);
2600 }
2601
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002602 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603}
2604
arthurhung6d4bed92021-03-17 11:59:33 +08002605void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002606 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2607 // have an explicit reason to support it.
2608 constexpr bool isStylus = false;
2609
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002610 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002611 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002612 if (dropWindow) {
2613 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002614 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002615 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002616 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002617 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002618 }
2619 mDragState.reset();
2620}
2621
2622void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002623 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002624 return;
2625 }
2626
arthurhung6d4bed92021-03-17 11:59:33 +08002627 if (!mDragState->isStartDrag) {
2628 mDragState->isStartDrag = true;
2629 mDragState->isStylusButtonDownAtStart =
2630 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2631 }
2632
Arthur Hung54745652022-04-20 07:17:41 +00002633 // Find the pointer index by id.
2634 int32_t pointerIndex = 0;
2635 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2636 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2637 if (pointerProperties.id == mDragState->pointerId) {
2638 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002639 }
Arthur Hung54745652022-04-20 07:17:41 +00002640 }
arthurhung6d4bed92021-03-17 11:59:33 +08002641
Arthur Hung54745652022-04-20 07:17:41 +00002642 if (uint32_t(pointerIndex) == entry.pointerCount) {
2643 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002644 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002645 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002646 return;
2647 }
2648
2649 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2650 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2651 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2652
2653 switch (maskedAction) {
2654 case AMOTION_EVENT_ACTION_MOVE: {
2655 // Handle the special case : stylus button no longer pressed.
2656 bool isStylusButtonDown =
2657 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2658 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2659 finishDragAndDrop(entry.displayId, x, y);
2660 return;
2661 }
2662
2663 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2664 // until we have an explicit reason to support it.
2665 constexpr bool isStylus = false;
2666
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002667 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002668 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002669 // enqueue drag exit if needed.
2670 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2671 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2672 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002673 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002674 y);
2675 }
2676 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2677 }
2678 // enqueue drag location if needed.
2679 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002680 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002681 }
2682 break;
2683 }
2684
2685 case AMOTION_EVENT_ACTION_POINTER_UP:
2686 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2687 break;
2688 }
2689 // The drag pointer is up.
2690 [[fallthrough]];
2691 case AMOTION_EVENT_ACTION_UP:
2692 finishDragAndDrop(entry.displayId, x, y);
2693 break;
2694 case AMOTION_EVENT_ACTION_CANCEL: {
2695 ALOGD("Receiving cancel when drag and drop.");
2696 sendDropWindowCommandLocked(nullptr, 0, 0);
2697 mDragState.reset();
2698 break;
2699 }
arthurhungb89ccb02020-12-30 16:19:01 +08002700 }
2701}
2702
chaviw98318de2021-05-19 16:45:23 -05002703void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002704 ftl::Flags<InputTarget::Flags> targetFlags,
2705 BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002706 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002707 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002708 std::vector<InputTarget>::iterator it =
2709 std::find_if(inputTargets.begin(), inputTargets.end(),
2710 [&windowHandle](const InputTarget& inputTarget) {
2711 return inputTarget.inputChannel->getConnectionToken() ==
2712 windowHandle->getToken();
2713 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002714
chaviw98318de2021-05-19 16:45:23 -05002715 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002716
2717 if (it == inputTargets.end()) {
2718 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002719 std::shared_ptr<InputChannel> inputChannel =
2720 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002721 if (inputChannel == nullptr) {
2722 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2723 return;
2724 }
2725 inputTarget.inputChannel = inputChannel;
2726 inputTarget.flags = targetFlags;
2727 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002728 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002729 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2730 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002731 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002732 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002733 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002734 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002735 inputTargets.push_back(inputTarget);
2736 it = inputTargets.end() - 1;
2737 }
2738
2739 ALOG_ASSERT(it->flags == targetFlags);
2740 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2741
chaviw1ff3d1e2020-07-01 15:53:47 -07002742 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743}
2744
Michael Wright3dd60e22019-03-27 22:06:44 +00002745void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002746 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002747 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2748 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002749
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002750 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2751 InputTarget target;
2752 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002753 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002754 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2755 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002756 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2757 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002758 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002759 target.setDefaultPointerTransform(target.displayTransform);
2760 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761 }
2762}
2763
Robert Carrc9bf1d32020-04-13 17:21:08 -07002764/**
2765 * Indicate whether one window handle should be considered as obscuring
2766 * another window handle. We only check a few preconditions. Actually
2767 * checking the bounds is left to the caller.
2768 */
chaviw98318de2021-05-19 16:45:23 -05002769static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2770 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002771 // Compare by token so cloned layers aren't counted
2772 if (haveSameToken(windowHandle, otherHandle)) {
2773 return false;
2774 }
2775 auto info = windowHandle->getInfo();
2776 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002777 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002778 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002779 } else if (otherInfo->alpha == 0 &&
2780 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002781 // Those act as if they were invisible, so we don't need to flag them.
2782 // We do want to potentially flag touchable windows even if they have 0
2783 // opacity, since they can consume touches and alter the effects of the
2784 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002785 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002786 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2787 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002788 } else if (info->ownerUid == otherInfo->ownerUid) {
2789 // If ownerUid is the same we don't generate occlusion events as there
2790 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002791 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002792 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002793 return false;
2794 } else if (otherInfo->displayId != info->displayId) {
2795 return false;
2796 }
2797 return true;
2798}
2799
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002800/**
2801 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2802 * untrusted, one should check:
2803 *
2804 * 1. If result.hasBlockingOcclusion is true.
2805 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2806 * BLOCK_UNTRUSTED.
2807 *
2808 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2809 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2810 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2811 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2812 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2813 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2814 *
2815 * If neither of those is true, then it means the touch can be allowed.
2816 */
2817InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002818 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2819 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002820 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002821 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002822 TouchOcclusionInfo info;
2823 info.hasBlockingOcclusion = false;
2824 info.obscuringOpacity = 0;
2825 info.obscuringUid = -1;
2826 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002827 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002828 if (windowHandle == otherHandle) {
2829 break; // All future windows are below us. Exit early.
2830 }
chaviw98318de2021-05-19 16:45:23 -05002831 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002832 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2833 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002834 if (DEBUG_TOUCH_OCCLUSION) {
2835 info.debugInfo.push_back(
2836 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2837 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002838 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2839 // we perform the checks below to see if the touch can be propagated or not based on the
2840 // window's touch occlusion mode
2841 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2842 info.hasBlockingOcclusion = true;
2843 info.obscuringUid = otherInfo->ownerUid;
2844 info.obscuringPackage = otherInfo->packageName;
2845 break;
2846 }
2847 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2848 uint32_t uid = otherInfo->ownerUid;
2849 float opacity =
2850 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2851 // Given windows A and B:
2852 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2853 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2854 opacityByUid[uid] = opacity;
2855 if (opacity > info.obscuringOpacity) {
2856 info.obscuringOpacity = opacity;
2857 info.obscuringUid = uid;
2858 info.obscuringPackage = otherInfo->packageName;
2859 }
2860 }
2861 }
2862 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002863 if (DEBUG_TOUCH_OCCLUSION) {
2864 info.debugInfo.push_back(
2865 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2866 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002867 return info;
2868}
2869
chaviw98318de2021-05-19 16:45:23 -05002870std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002871 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002872 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2873 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2874 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2875 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002876 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2877 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2878 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2879 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2880 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002881 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002882 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002883}
2884
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002885bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2886 if (occlusionInfo.hasBlockingOcclusion) {
2887 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2888 occlusionInfo.obscuringUid);
2889 return false;
2890 }
2891 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2892 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2893 "%.2f, maximum allowed = %.2f)",
2894 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2895 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2896 return false;
2897 }
2898 return true;
2899}
2900
chaviw98318de2021-05-19 16:45:23 -05002901bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002902 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002903 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002904 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2905 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002906 if (windowHandle == otherHandle) {
2907 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002908 }
chaviw98318de2021-05-19 16:45:23 -05002909 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002910 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002911 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002912 return true;
2913 }
2914 }
2915 return false;
2916}
2917
chaviw98318de2021-05-19 16:45:23 -05002918bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002919 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002920 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2921 const WindowInfo* windowInfo = windowHandle->getInfo();
2922 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002923 if (windowHandle == otherHandle) {
2924 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002925 }
chaviw98318de2021-05-19 16:45:23 -05002926 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002927 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002928 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002929 return true;
2930 }
2931 }
2932 return false;
2933}
2934
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002935std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002936 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002937 if (applicationHandle != nullptr) {
2938 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002939 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940 } else {
2941 return applicationHandle->getName();
2942 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002943 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002944 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002945 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002946 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002947 }
2948}
2949
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002950void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002951 if (!isUserActivityEvent(eventEntry)) {
2952 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002953 return;
2954 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002955 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002956 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002957 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002958 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002959 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002960 if (DEBUG_DISPATCH_CYCLE) {
2961 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2962 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002963 return;
2964 }
2965 }
2966
2967 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002968 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002969 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002970 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2971 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002972 return;
2973 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002974
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002975 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002976 eventType = USER_ACTIVITY_EVENT_TOUCH;
2977 }
2978 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002979 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002980 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002981 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2982 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002983 return;
2984 }
2985 eventType = USER_ACTIVITY_EVENT_BUTTON;
2986 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002987 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002988 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002989 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002990 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002991 break;
2992 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002993 }
2994
Prabir Pradhancef936d2021-07-21 16:17:52 +00002995 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2996 REQUIRES(mLock) {
2997 scoped_unlock unlock(mLock);
2998 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2999 };
3000 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003001}
3002
3003void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003004 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003005 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003006 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003007 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003008 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003009 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003010 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003011 ATRACE_NAME(message.c_str());
3012 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003013 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003014 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003015 "globalScaleFactor=%f, pointerIds=0x%x %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003016 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003017 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
3018 inputTarget.getPointerInfoString().c_str());
3019 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003020
3021 // Skip this event if the connection status is not normal.
3022 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003023 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003024 if (DEBUG_DISPATCH_CYCLE) {
3025 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003026 connection->getInputChannelName().c_str(),
3027 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029 return;
3030 }
3031
3032 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003033 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003034 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003035 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003036 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003037
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003038 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003039 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003040 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
3041 "Splitting motion events requires a down time to be set for the "
3042 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003043 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003044 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3045 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003046 if (!splitMotionEntry) {
3047 return; // split event was dropped
3048 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003049 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3050 std::string reason = std::string("reason=pointer cancel on split window");
3051 android_log_event_list(LOGTAG_INPUT_CANCEL)
3052 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3053 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003054 if (DEBUG_FOCUS) {
3055 ALOGD("channel '%s' ~ Split motion event.",
3056 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003057 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003058 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003059 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3060 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003061 return;
3062 }
3063 }
3064
3065 // Not splitting. Enqueue dispatch entries for the event as is.
3066 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3067}
3068
3069void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003070 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003071 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003072 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003073 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003074 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003075 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003076 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003077 ATRACE_NAME(message.c_str());
3078 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003079 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3080 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003081
hongzuo liu95785e22022-09-06 02:51:35 +00003082 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003083
3084 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003085 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003086 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003087 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003088 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003089 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003090 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003091 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003092 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003093 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003094 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003095 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003096 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097
3098 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003099 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100 startDispatchCycleLocked(currentTime, connection);
3101 }
3102}
3103
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003104void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003105 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003106 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003107 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003108 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003109 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3110 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003111 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003112 ATRACE_NAME(message.c_str());
3113 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003114 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3115 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003116 return;
3117 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003118
3119 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3120 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003121
3122 // This is a new event.
3123 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003124 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003125 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003126
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003127 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3128 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003129 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003130 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003131 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003132 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003133 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003134 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003135 dispatchEntry->resolvedAction = keyEntry.action;
3136 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003137
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003138 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3139 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003140 if (DEBUG_DISPATCH_CYCLE) {
3141 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3142 "event",
3143 connection->getInputChannelName().c_str());
3144 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003145 return; // skip the inconsistent event
3146 }
3147 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003149
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003150 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003151 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003152 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3153 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3154 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3155 static_cast<int32_t>(IdGenerator::Source::OTHER);
3156 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003157 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003158 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003159 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003160 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003161 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003162 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003163 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003164 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003165 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003166 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3167 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003168 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003169 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003170 }
3171 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003172 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3173 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003174 if (DEBUG_DISPATCH_CYCLE) {
3175 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3176 "enter event",
3177 connection->getInputChannelName().c_str());
3178 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003179 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3180 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003181 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3182 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003184 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003185 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3186 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3187 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003188 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003189 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3190 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003191 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003192 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3193 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003195 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3196 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003197 if (DEBUG_DISPATCH_CYCLE) {
3198 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3199 "event",
3200 connection->getInputChannelName().c_str());
3201 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003202 return; // skip the inconsistent event
3203 }
3204
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003205 dispatchEntry->resolvedEventId =
3206 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3207 ? mIdGenerator.nextId()
3208 : motionEntry.id;
3209 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3210 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3211 ") to MotionEvent(id=0x%" PRIx32 ").",
3212 motionEntry.id, dispatchEntry->resolvedEventId);
3213 ATRACE_NAME(message.c_str());
3214 }
3215
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003216 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3217 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3218 // Skip reporting pointer down outside focus to the policy.
3219 break;
3220 }
3221
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003222 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003223 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003224
3225 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003226 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003227 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003228 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003229 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3230 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003231 break;
3232 }
Chris Yef59a2f42020-10-16 12:55:26 -07003233 case EventEntry::Type::SENSOR: {
3234 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3235 break;
3236 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003237 case EventEntry::Type::CONFIGURATION_CHANGED:
3238 case EventEntry::Type::DEVICE_RESET: {
3239 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003240 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003241 break;
3242 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243 }
3244
3245 // Remember that we are waiting for this dispatch to complete.
3246 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003247 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003248 }
3249
3250 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003251 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003252 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003253}
3254
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003255/**
3256 * This function is purely for debugging. It helps us understand where the user interaction
3257 * was taking place. For example, if user is touching launcher, we will see a log that user
3258 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3259 * We will see both launcher and wallpaper in that list.
3260 * Once the interaction with a particular set of connections starts, no new logs will be printed
3261 * until the set of interacted connections changes.
3262 *
3263 * The following items are skipped, to reduce the logspam:
3264 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3265 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3266 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3267 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3268 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003269 */
3270void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3271 const std::vector<InputTarget>& targets) {
3272 // Skip ACTION_UP events, and all events other than keys and motions
3273 if (entry.type == EventEntry::Type::KEY) {
3274 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3275 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3276 return;
3277 }
3278 } else if (entry.type == EventEntry::Type::MOTION) {
3279 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3280 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3281 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3282 return;
3283 }
3284 } else {
3285 return; // Not a key or a motion
3286 }
3287
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003288 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003289 std::vector<sp<Connection>> newConnections;
3290 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003291 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003292 continue; // Skip windows that receive ACTION_OUTSIDE
3293 }
3294
3295 sp<IBinder> token = target.inputChannel->getConnectionToken();
3296 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003297 if (connection == nullptr) {
3298 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003299 }
3300 newConnectionTokens.insert(std::move(token));
3301 newConnections.emplace_back(connection);
3302 }
3303 if (newConnectionTokens == mInteractionConnectionTokens) {
3304 return; // no change
3305 }
3306 mInteractionConnectionTokens = newConnectionTokens;
3307
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003308 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003309 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003310 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003311 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003312 std::string message = "Interaction with: " + targetList;
3313 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003314 message += "<none>";
3315 }
3316 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3317}
3318
chaviwfd6d3512019-03-25 13:23:49 -07003319void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003320 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003321 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003322 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3323 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003324 return;
3325 }
3326
Vishnu Nairc519ff72021-01-21 08:23:08 -08003327 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003328 if (focusedToken == token) {
3329 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003330 return;
3331 }
3332
Prabir Pradhancef936d2021-07-21 16:17:52 +00003333 auto command = [this, token]() REQUIRES(mLock) {
3334 scoped_unlock unlock(mLock);
3335 mPolicy->onPointerDownOutsideFocus(token);
3336 };
3337 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003338}
3339
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003340status_t InputDispatcher::publishMotionEvent(Connection& connection,
3341 DispatchEntry& dispatchEntry) const {
3342 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3343 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3344
3345 PointerCoords scaledCoords[MAX_POINTERS];
3346 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3347
3348 // Set the X and Y offset and X and Y scale depending on the input source.
3349 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003350 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003351 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3352 if (globalScaleFactor != 1.0f) {
3353 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3354 scaledCoords[i] = motionEntry.pointerCoords[i];
3355 // Don't apply window scale here since we don't want scale to affect raw
3356 // coordinates. The scale will be sent back to the client and applied
3357 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003358 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003359 }
3360 usingCoords = scaledCoords;
3361 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003362 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003363 // We don't want the dispatch target to know the coordinates
3364 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3365 scaledCoords[i].clear();
3366 }
3367 usingCoords = scaledCoords;
3368 }
3369
3370 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3371
3372 // Publish the motion event.
3373 return connection.inputPublisher
3374 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3375 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3376 std::move(hmac), dispatchEntry.resolvedAction,
3377 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3378 motionEntry.edgeFlags, motionEntry.metaState,
3379 motionEntry.buttonState, motionEntry.classification,
3380 dispatchEntry.transform, motionEntry.xPrecision,
3381 motionEntry.yPrecision, motionEntry.xCursorPosition,
3382 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3383 motionEntry.downTime, motionEntry.eventTime,
3384 motionEntry.pointerCount, motionEntry.pointerProperties,
3385 usingCoords);
3386}
3387
Michael Wrightd02c5b62014-02-10 15:10:22 -08003388void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003389 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003390 if (ATRACE_ENABLED()) {
3391 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003392 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003393 ATRACE_NAME(message.c_str());
3394 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003395 if (DEBUG_DISPATCH_CYCLE) {
3396 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3397 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003398
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003399 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003400 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003402 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003403 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404
3405 // Publish the event.
3406 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003407 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3408 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003409 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003410 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3411 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003412 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3413 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3414 << connection->getInputChannelName();
3415 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003417 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003418 status = connection->inputPublisher
3419 .publishKeyEvent(dispatchEntry->seq,
3420 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3421 keyEntry.source, keyEntry.displayId,
3422 std::move(hmac), dispatchEntry->resolvedAction,
3423 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3424 keyEntry.scanCode, keyEntry.metaState,
3425 keyEntry.repeatCount, keyEntry.downTime,
3426 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003427 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003428 }
3429
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003430 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003431 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3432 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3433 << connection->getInputChannelName();
3434 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003435 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003436 break;
3437 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003438
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003439 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003440 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003441 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003442 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003443 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003444 break;
3445 }
3446
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003447 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3448 const TouchModeEntry& touchModeEntry =
3449 static_cast<const TouchModeEntry&>(eventEntry);
3450 status = connection->inputPublisher
3451 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3452 touchModeEntry.inTouchMode);
3453
3454 break;
3455 }
3456
Prabir Pradhan99987712020-11-10 18:43:05 -08003457 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3458 const auto& captureEntry =
3459 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3460 status = connection->inputPublisher
3461 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003462 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003463 break;
3464 }
3465
arthurhungb89ccb02020-12-30 16:19:01 +08003466 case EventEntry::Type::DRAG: {
3467 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3468 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3469 dragEntry.id, dragEntry.x,
3470 dragEntry.y,
3471 dragEntry.isExiting);
3472 break;
3473 }
3474
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003475 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003476 case EventEntry::Type::DEVICE_RESET:
3477 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003478 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003479 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003480 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003481 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482 }
3483
3484 // Check the result.
3485 if (status) {
3486 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003487 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003488 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003489 "This is unexpected because the wait queue is empty, so the pipe "
3490 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003491 "event to it, status=%s(%d)",
3492 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3493 status);
Harry Cutts33476232023-01-30 19:57:29 +00003494 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003495 } else {
3496 // Pipe is full and we are waiting for the app to finish process some events
3497 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003498 if (DEBUG_DISPATCH_CYCLE) {
3499 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3500 "waiting for the application to catch up",
3501 connection->getInputChannelName().c_str());
3502 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003503 }
3504 } else {
3505 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003506 "status=%s(%d)",
3507 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3508 status);
Harry Cutts33476232023-01-30 19:57:29 +00003509 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003510 }
3511 return;
3512 }
3513
3514 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003515 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3516 connection->outboundQueue.end(),
3517 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003518 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003519 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003520 if (connection->responsive) {
3521 mAnrTracker.insert(dispatchEntry->timeoutTime,
3522 connection->inputChannel->getConnectionToken());
3523 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003524 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525 }
3526}
3527
chaviw09c8d2d2020-08-24 15:48:26 -07003528std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3529 size_t size;
3530 switch (event.type) {
3531 case VerifiedInputEvent::Type::KEY: {
3532 size = sizeof(VerifiedKeyEvent);
3533 break;
3534 }
3535 case VerifiedInputEvent::Type::MOTION: {
3536 size = sizeof(VerifiedMotionEvent);
3537 break;
3538 }
3539 }
3540 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3541 return mHmacKeyManager.sign(start, size);
3542}
3543
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003544const std::array<uint8_t, 32> InputDispatcher::getSignature(
3545 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003546 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3547 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003548 // Only sign events up and down events as the purely move events
3549 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003550 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003551 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003552
3553 VerifiedMotionEvent verifiedEvent =
3554 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3555 verifiedEvent.actionMasked = actionMasked;
3556 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3557 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003558}
3559
3560const std::array<uint8_t, 32> InputDispatcher::getSignature(
3561 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3562 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3563 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3564 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003565 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003566}
3567
Michael Wrightd02c5b62014-02-10 15:10:22 -08003568void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003569 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003570 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003571 if (DEBUG_DISPATCH_CYCLE) {
3572 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3573 connection->getInputChannelName().c_str(), seq, toString(handled));
3574 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003575
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003576 if (connection->status == Connection::Status::BROKEN ||
3577 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003578 return;
3579 }
3580
3581 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003582 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3583 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3584 };
3585 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586}
3587
3588void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003589 const sp<Connection>& connection,
3590 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003591 if (DEBUG_DISPATCH_CYCLE) {
3592 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3593 connection->getInputChannelName().c_str(), toString(notify));
3594 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595
3596 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003597 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003598 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003599 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003600 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003601
3602 // The connection appears to be unrecoverably broken.
3603 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003604 if (connection->status == Connection::Status::NORMAL) {
3605 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606
3607 if (notify) {
3608 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003609 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3610 connection->getInputChannelName().c_str());
3611
3612 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003613 scoped_unlock unlock(mLock);
3614 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3615 };
3616 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 }
3618 }
3619}
3620
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003621void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3622 while (!queue.empty()) {
3623 DispatchEntry* dispatchEntry = queue.front();
3624 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003625 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 }
3627}
3628
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003629void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003631 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632 }
3633 delete dispatchEntry;
3634}
3635
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003636int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3637 std::scoped_lock _l(mLock);
3638 sp<Connection> connection = getConnectionLocked(connectionToken);
3639 if (connection == nullptr) {
3640 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3641 connectionToken.get(), events);
3642 return 0; // remove the callback
3643 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003645 bool notify;
3646 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3647 if (!(events & ALOOPER_EVENT_INPUT)) {
3648 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3649 "events=0x%x",
3650 connection->getInputChannelName().c_str(), events);
3651 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003652 }
3653
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003654 nsecs_t currentTime = now();
3655 bool gotOne = false;
3656 status_t status = OK;
3657 for (;;) {
3658 Result<InputPublisher::ConsumerResponse> result =
3659 connection->inputPublisher.receiveConsumerResponse();
3660 if (!result.ok()) {
3661 status = result.error().code();
3662 break;
3663 }
3664
3665 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3666 const InputPublisher::Finished& finish =
3667 std::get<InputPublisher::Finished>(*result);
3668 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3669 finish.consumeTime);
3670 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003671 if (shouldReportMetricsForConnection(*connection)) {
3672 const InputPublisher::Timeline& timeline =
3673 std::get<InputPublisher::Timeline>(*result);
3674 mLatencyTracker
3675 .trackGraphicsLatency(timeline.inputEventId,
3676 connection->inputChannel->getConnectionToken(),
3677 std::move(timeline.graphicsTimeline));
3678 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003679 }
3680 gotOne = true;
3681 }
3682 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003683 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003684 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003685 return 1;
3686 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687 }
3688
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003689 notify = status != DEAD_OBJECT || !connection->monitor;
3690 if (notify) {
3691 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3692 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3693 status);
3694 }
3695 } else {
3696 // Monitor channels are never explicitly unregistered.
3697 // We do it automatically when the remote endpoint is closed so don't warn about them.
3698 const bool stillHaveWindowHandle =
3699 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3700 notify = !connection->monitor && stillHaveWindowHandle;
3701 if (notify) {
3702 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3703 connection->getInputChannelName().c_str(), events);
3704 }
3705 }
3706
3707 // Remove the channel.
3708 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3709 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710}
3711
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003712void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003714 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003715 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716 }
3717}
3718
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003719void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003720 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003721 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003722 for (const Monitor& monitor : monitors) {
3723 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003724 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003725 }
3726}
3727
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003729 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003730 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003731 if (connection == nullptr) {
3732 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003734
3735 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736}
3737
3738void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3739 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003740 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003741 return;
3742 }
3743
3744 nsecs_t currentTime = now();
3745
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003746 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003747 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003748
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003749 if (cancelationEvents.empty()) {
3750 return;
3751 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003752 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3753 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3754 "with reality: %s, mode=%d.",
3755 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3756 options.mode);
3757 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003758
Arthur Hungb3307ee2021-10-14 10:57:37 +00003759 std::string reason = std::string("reason=").append(options.reason);
3760 android_log_event_list(LOGTAG_INPUT_CANCEL)
3761 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3762
Svet Ganov5d3bc372020-01-26 23:11:07 -08003763 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003764 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003765 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3766 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003767 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003768 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003769 target.globalScaleFactor = windowInfo->globalScaleFactor;
3770 }
3771 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003772 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003773
hongzuo liu95785e22022-09-06 02:51:35 +00003774 const bool wasEmpty = connection->outboundQueue.empty();
3775
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003776 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003777 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003778 switch (cancelationEventEntry->type) {
3779 case EventEntry::Type::KEY: {
3780 logOutboundKeyDetails("cancel - ",
3781 static_cast<const KeyEntry&>(*cancelationEventEntry));
3782 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003784 case EventEntry::Type::MOTION: {
3785 logOutboundMotionDetails("cancel - ",
3786 static_cast<const MotionEntry&>(*cancelationEventEntry));
3787 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003789 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003790 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003791 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3792 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003793 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003794 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003795 break;
3796 }
3797 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003798 case EventEntry::Type::DEVICE_RESET:
3799 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003800 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003801 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003802 break;
3803 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804 }
3805
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003806 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003807 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003808 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003809
hongzuo liu95785e22022-09-06 02:51:35 +00003810 // If the outbound queue was previously empty, start the dispatch cycle going.
3811 if (wasEmpty && !connection->outboundQueue.empty()) {
3812 startDispatchCycleLocked(currentTime, connection);
3813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814}
3815
Svet Ganov5d3bc372020-01-26 23:11:07 -08003816void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Arthur Hungc539dbb2022-12-08 07:45:36 +00003817 const nsecs_t downTime, const sp<Connection>& connection,
3818 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003819 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003820 return;
3821 }
3822
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003823 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003824 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003825
3826 if (downEvents.empty()) {
3827 return;
3828 }
3829
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003830 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003831 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3832 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003833 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003834
3835 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003836 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003837 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3838 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003839 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003840 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003841 target.globalScaleFactor = windowInfo->globalScaleFactor;
3842 }
3843 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00003844 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003845
hongzuo liu95785e22022-09-06 02:51:35 +00003846 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003847 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003848 switch (downEventEntry->type) {
3849 case EventEntry::Type::MOTION: {
3850 logOutboundMotionDetails("down - ",
3851 static_cast<const MotionEntry&>(*downEventEntry));
3852 break;
3853 }
3854
3855 case EventEntry::Type::KEY:
3856 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003857 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003858 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003859 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003860 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003861 case EventEntry::Type::SENSOR:
3862 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003863 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003864 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003865 break;
3866 }
3867 }
3868
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003869 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003870 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003871 }
3872
hongzuo liu95785e22022-09-06 02:51:35 +00003873 // If the outbound queue was previously empty, start the dispatch cycle going.
3874 if (wasEmpty && !connection->outboundQueue.empty()) {
3875 startDispatchCycleLocked(downTime, connection);
3876 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003877}
3878
Arthur Hungc539dbb2022-12-08 07:45:36 +00003879void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
3880 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
3881 if (windowHandle != nullptr) {
3882 sp<Connection> wallpaperConnection = getConnectionLocked(windowHandle->getToken());
3883 if (wallpaperConnection != nullptr) {
3884 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
3885 }
3886 }
3887}
3888
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003889std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003890 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891 ALOG_ASSERT(pointerIds.value != 0);
3892
3893 uint32_t splitPointerIndexMap[MAX_POINTERS];
3894 PointerProperties splitPointerProperties[MAX_POINTERS];
3895 PointerCoords splitPointerCoords[MAX_POINTERS];
3896
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003897 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898 uint32_t splitPointerCount = 0;
3899
3900 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003901 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003903 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904 uint32_t pointerId = uint32_t(pointerProperties.id);
3905 if (pointerIds.hasBit(pointerId)) {
3906 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3907 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3908 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003909 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910 splitPointerCount += 1;
3911 }
3912 }
3913
3914 if (splitPointerCount != pointerIds.count()) {
3915 // This is bad. We are missing some of the pointers that we expected to deliver.
3916 // Most likely this indicates that we received an ACTION_MOVE events that has
3917 // different pointer ids than we expected based on the previous ACTION_DOWN
3918 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3919 // in this way.
3920 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003921 "we expected there to be %d pointers. This probably means we received "
3922 "a broken sequence of pointer ids from the input device.",
3923 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003924 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925 }
3926
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003927 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003929 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3930 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3932 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003933 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003934 uint32_t pointerId = uint32_t(pointerProperties.id);
3935 if (pointerIds.hasBit(pointerId)) {
3936 if (pointerIds.count() == 1) {
3937 // The first/last pointer went down/up.
3938 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003939 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003940 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3941 ? AMOTION_EVENT_ACTION_CANCEL
3942 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943 } else {
3944 // A secondary pointer went down/up.
3945 uint32_t splitPointerIndex = 0;
3946 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3947 splitPointerIndex += 1;
3948 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003949 action = maskedAction |
3950 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951 }
3952 } else {
3953 // An unrelated pointer changed.
3954 action = AMOTION_EVENT_ACTION_MOVE;
3955 }
3956 }
3957
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003958 if (action == AMOTION_EVENT_ACTION_DOWN) {
3959 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3960 "Split motion event has mismatching downTime and eventTime for "
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08003961 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
3962 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003963 }
3964
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003965 int32_t newId = mIdGenerator.nextId();
3966 if (ATRACE_ENABLED()) {
3967 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3968 ") to MotionEvent(id=0x%" PRIx32 ").",
3969 originalMotionEntry.id, newId);
3970 ATRACE_NAME(message.c_str());
3971 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003972 std::unique_ptr<MotionEntry> splitMotionEntry =
3973 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3974 originalMotionEntry.deviceId, originalMotionEntry.source,
3975 originalMotionEntry.displayId,
3976 originalMotionEntry.policyFlags, action,
3977 originalMotionEntry.actionButton,
3978 originalMotionEntry.flags, originalMotionEntry.metaState,
3979 originalMotionEntry.buttonState,
3980 originalMotionEntry.classification,
3981 originalMotionEntry.edgeFlags,
3982 originalMotionEntry.xPrecision,
3983 originalMotionEntry.yPrecision,
3984 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003985 originalMotionEntry.yCursorPosition, splitDownTime,
3986 splitPointerCount, splitPointerProperties,
3987 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003989 if (originalMotionEntry.injectionState) {
3990 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003991 splitMotionEntry->injectionState->refCount += 1;
3992 }
3993
3994 return splitMotionEntry;
3995}
3996
3997void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003998 if (DEBUG_INBOUND_EVENT_DETAILS) {
3999 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
4000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004001
Antonio Kantekf16f2832021-09-28 04:39:20 +00004002 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004003 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004004 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004006 std::unique_ptr<ConfigurationChangedEntry> newEntry =
4007 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
4008 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009 } // release lock
4010
4011 if (needWake) {
4012 mLooper->wake();
4013 }
4014}
4015
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004016/**
4017 * If one of the meta shortcuts is detected, process them here:
4018 * Meta + Backspace -> generate BACK
4019 * Meta + Enter -> generate HOME
4020 * This will potentially overwrite keyCode and metaState.
4021 */
4022void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004023 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004024 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4025 int32_t newKeyCode = AKEYCODE_UNKNOWN;
4026 if (keyCode == AKEYCODE_DEL) {
4027 newKeyCode = AKEYCODE_BACK;
4028 } else if (keyCode == AKEYCODE_ENTER) {
4029 newKeyCode = AKEYCODE_HOME;
4030 }
4031 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004032 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004033 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004034 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004035 keyCode = newKeyCode;
4036 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4037 }
4038 } else if (action == AKEY_EVENT_ACTION_UP) {
4039 // In order to maintain a consistent stream of up and down events, check to see if the key
4040 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4041 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004042 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004043 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004044 auto replacementIt = mReplacedKeys.find(replacement);
4045 if (replacementIt != mReplacedKeys.end()) {
4046 keyCode = replacementIt->second;
4047 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004048 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4049 }
4050 }
4051}
4052
Michael Wrightd02c5b62014-02-10 15:10:22 -08004053void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004054 if (DEBUG_INBOUND_EVENT_DETAILS) {
4055 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
4056 "policyFlags=0x%x, action=0x%x, "
4057 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
4058 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
4059 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
4060 args->downTime);
4061 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004062 if (!validateKeyEvent(args->action)) {
4063 return;
4064 }
4065
4066 uint32_t policyFlags = args->policyFlags;
4067 int32_t flags = args->flags;
4068 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004069 // InputDispatcher tracks and generates key repeats on behalf of
4070 // whatever notifies it, so repeatCount should always be set to 0
4071 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4073 policyFlags |= POLICY_FLAG_VIRTUAL;
4074 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4075 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076 if (policyFlags & POLICY_FLAG_FUNCTION) {
4077 metaState |= AMETA_FUNCTION_ON;
4078 }
4079
4080 policyFlags |= POLICY_FLAG_TRUSTED;
4081
Michael Wright78f24442014-08-06 15:55:28 -07004082 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004083 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004084
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004086 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08004087 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
4088 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089
Michael Wright2b3c3302018-03-02 17:19:13 +00004090 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004092 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4093 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004094 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004095 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004096
Antonio Kantekf16f2832021-09-28 04:39:20 +00004097 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098 { // acquire lock
4099 mLock.lock();
4100
4101 if (shouldSendKeyToInputFilterLocked(args)) {
4102 mLock.unlock();
4103
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004104 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4106 return; // event was consumed by the filter
4107 }
4108
4109 mLock.lock();
4110 }
4111
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004112 std::unique_ptr<KeyEntry> newEntry =
4113 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4114 args->displayId, policyFlags, args->action, flags,
4115 keyCode, args->scanCode, metaState, repeatCount,
4116 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004118 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119 mLock.unlock();
4120 } // release lock
4121
4122 if (needWake) {
4123 mLooper->wake();
4124 }
4125}
4126
4127bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4128 return mInputFilterEnabled;
4129}
4130
4131void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004132 if (DEBUG_INBOUND_EVENT_DETAILS) {
4133 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4134 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004135 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004136 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4137 "yCursorPosition=%f, downTime=%" PRId64,
4138 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004139 args->policyFlags, MotionEvent::actionToString(args->action).c_str(),
4140 args->actionButton, args->flags, args->metaState, args->buttonState, args->edgeFlags,
4141 args->xPrecision, args->yPrecision, args->xCursorPosition, args->yCursorPosition,
4142 args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004143 for (uint32_t i = 0; i < args->pointerCount; i++) {
4144 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4145 "x=%f, y=%f, pressure=%f, size=%f, "
4146 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4147 "orientation=%f",
4148 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4149 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4150 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4151 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4152 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4153 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4154 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4155 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4156 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4157 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4158 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -08004160 LOG_ALWAYS_FATAL_IF(!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4161 args->pointerProperties),
4162 "Invalid event: %s", args->dump().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163
4164 uint32_t policyFlags = args->policyFlags;
4165 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004166
4167 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004168 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004169 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4170 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004171 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004172 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173
Antonio Kantekf16f2832021-09-28 04:39:20 +00004174 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 { // acquire lock
4176 mLock.lock();
4177
4178 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004179 ui::Transform displayTransform;
4180 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4181 displayTransform = it->second.transform;
4182 }
4183
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184 mLock.unlock();
4185
4186 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004187 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4188 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004189 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004190 displayTransform, args->xPrecision, args->yPrecision,
4191 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004192 args->downTime, args->eventTime, args->pointerCount,
4193 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194
4195 policyFlags |= POLICY_FLAG_FILTERED;
4196 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4197 return; // event was consumed by the filter
4198 }
4199
4200 mLock.lock();
4201 }
4202
4203 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004204 std::unique_ptr<MotionEntry> newEntry =
4205 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4206 args->source, args->displayId, policyFlags,
4207 args->action, args->actionButton, args->flags,
4208 args->metaState, args->buttonState,
4209 args->classification, args->edgeFlags,
4210 args->xPrecision, args->yPrecision,
4211 args->xCursorPosition, args->yCursorPosition,
4212 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004213 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004215 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4216 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4217 !mInputFilterEnabled) {
4218 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4219 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4220 }
4221
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004222 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223 mLock.unlock();
4224 } // release lock
4225
4226 if (needWake) {
4227 mLooper->wake();
4228 }
4229}
4230
Chris Yef59a2f42020-10-16 12:55:26 -07004231void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004232 if (DEBUG_INBOUND_EVENT_DETAILS) {
4233 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4234 " sensorType=%s",
4235 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004236 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004237 }
Chris Yef59a2f42020-10-16 12:55:26 -07004238
Antonio Kantekf16f2832021-09-28 04:39:20 +00004239 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004240 { // acquire lock
4241 mLock.lock();
4242
4243 // Just enqueue a new sensor event.
4244 std::unique_ptr<SensorEntry> newEntry =
4245 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
Harry Cutts33476232023-01-30 19:57:29 +00004246 args->source, /* policyFlags=*/0, args->hwTimestamp,
Chris Yef59a2f42020-10-16 12:55:26 -07004247 args->sensorType, args->accuracy,
4248 args->accuracyChanged, args->values);
4249
4250 needWake = enqueueInboundEventLocked(std::move(newEntry));
4251 mLock.unlock();
4252 } // release lock
4253
4254 if (needWake) {
4255 mLooper->wake();
4256 }
4257}
4258
Chris Yefb552902021-02-03 17:18:37 -08004259void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004260 if (DEBUG_INBOUND_EVENT_DETAILS) {
4261 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4262 args->deviceId, args->isOn);
4263 }
Chris Yefb552902021-02-03 17:18:37 -08004264 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4265}
4266
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004268 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269}
4270
4271void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004272 if (DEBUG_INBOUND_EVENT_DETAILS) {
4273 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4274 "switchMask=0x%08x",
4275 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4276 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277
4278 uint32_t policyFlags = args->policyFlags;
4279 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004280 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281}
4282
4283void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004284 if (DEBUG_INBOUND_EVENT_DETAILS) {
4285 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4286 args->deviceId);
4287 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288
Antonio Kantekf16f2832021-09-28 04:39:20 +00004289 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004291 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004292
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004293 std::unique_ptr<DeviceResetEntry> newEntry =
4294 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4295 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 } // release lock
4297
4298 if (needWake) {
4299 mLooper->wake();
4300 }
4301}
4302
Prabir Pradhan7e186182020-11-10 13:56:45 -08004303void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004304 if (DEBUG_INBOUND_EVENT_DETAILS) {
4305 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004306 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004307 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004308
Antonio Kantekf16f2832021-09-28 04:39:20 +00004309 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004310 { // acquire lock
4311 std::scoped_lock _l(mLock);
4312 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004313 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004314 needWake = enqueueInboundEventLocked(std::move(entry));
4315 } // release lock
4316
4317 if (needWake) {
4318 mLooper->wake();
4319 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004320}
4321
Prabir Pradhan5735a322022-04-11 17:23:34 +00004322InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4323 std::optional<int32_t> targetUid,
4324 InputEventInjectionSync syncMode,
4325 std::chrono::milliseconds timeout,
4326 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004327 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004328 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4329 "policyFlags=0x%08x",
4330 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4331 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004332 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004333 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334
Prabir Pradhan5735a322022-04-11 17:23:34 +00004335 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004337 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004338 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4339 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4340 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4341 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4342 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004343 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004344 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004345 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004346 }
4347
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004348 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004350 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004351 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4352 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004353 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004354 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004355 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004356
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004357 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004358 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4359 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4360 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004361 int32_t keyCode = incomingKey.getKeyCode();
4362 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004363 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004364 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004365 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004366 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004367 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4368 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4369 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004370
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004371 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4372 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004373 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004374
4375 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4376 android::base::Timer t;
4377 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4378 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4379 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4380 std::to_string(t.duration().count()).c_str());
4381 }
4382 }
4383
4384 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004385 std::unique_ptr<KeyEntry> injectedEntry =
4386 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004387 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004388 incomingKey.getDisplayId(), policyFlags, action,
4389 flags, keyCode, incomingKey.getScanCode(), metaState,
4390 incomingKey.getRepeatCount(),
4391 incomingKey.getDownTime());
4392 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004393 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004394 }
4395
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004396 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004397 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004398 const int32_t action = motionEvent.getAction();
4399 const bool isPointerEvent =
4400 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4401 // If a pointer event has no displayId specified, inject it to the default display.
4402 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4403 ? ADISPLAY_ID_DEFAULT
4404 : event->getDisplayId();
4405 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004406 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004407 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004408 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004409 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004410 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004411 }
4412
4413 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004414 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004415 android::base::Timer t;
4416 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4417 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4418 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4419 std::to_string(t.duration().count()).c_str());
4420 }
4421 }
4422
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004423 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4424 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4425 }
4426
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004427 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004428 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4429 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004430 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004431 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4432 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004433 displayId, policyFlags, action, actionButton,
4434 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004435 motionEvent.getButtonState(),
4436 motionEvent.getClassification(),
4437 motionEvent.getEdgeFlags(),
4438 motionEvent.getXPrecision(),
4439 motionEvent.getYPrecision(),
4440 motionEvent.getRawXCursorPosition(),
4441 motionEvent.getRawYCursorPosition(),
4442 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004443 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004444 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004445 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004446 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004447 sampleEventTimes += 1;
4448 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004449 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004450 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4451 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004452 displayId, policyFlags, action, actionButton,
4453 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004454 motionEvent.getButtonState(),
4455 motionEvent.getClassification(),
4456 motionEvent.getEdgeFlags(),
4457 motionEvent.getXPrecision(),
4458 motionEvent.getYPrecision(),
4459 motionEvent.getRawXCursorPosition(),
4460 motionEvent.getRawYCursorPosition(),
4461 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004462 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004463 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004464 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4465 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004466 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004467 }
4468 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004469 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004471 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004472 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004473 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004474 }
4475
Prabir Pradhan5735a322022-04-11 17:23:34 +00004476 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004477 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478 injectionState->injectionIsAsync = true;
4479 }
4480
4481 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004482 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004483
4484 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004485 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004486 if (DEBUG_INJECTION) {
4487 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4488 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004489 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004490 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004491 }
4492
4493 mLock.unlock();
4494
4495 if (needWake) {
4496 mLooper->wake();
4497 }
4498
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004499 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004501 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004502
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004503 if (syncMode == InputEventInjectionSync::NONE) {
4504 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505 } else {
4506 for (;;) {
4507 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004508 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004509 break;
4510 }
4511
4512 nsecs_t remainingTimeout = endTime - now();
4513 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004514 if (DEBUG_INJECTION) {
4515 ALOGD("injectInputEvent - Timed out waiting for injection result "
4516 "to become available.");
4517 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004518 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519 break;
4520 }
4521
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004522 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523 }
4524
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004525 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4526 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004527 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004528 if (DEBUG_INJECTION) {
4529 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4530 injectionState->pendingForegroundDispatches);
4531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004532 nsecs_t remainingTimeout = endTime - now();
4533 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004534 if (DEBUG_INJECTION) {
4535 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4536 "dispatches to finish.");
4537 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004538 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004539 break;
4540 }
4541
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004542 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543 }
4544 }
4545 }
4546
4547 injectionState->release();
4548 } // release lock
4549
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004550 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004551 LOG(DEBUG) << "injectInputEvent - Finished with result "
4552 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554
4555 return injectionResult;
4556}
4557
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004558std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004559 std::array<uint8_t, 32> calculatedHmac;
4560 std::unique_ptr<VerifiedInputEvent> result;
4561 switch (event.getType()) {
4562 case AINPUT_EVENT_TYPE_KEY: {
4563 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4564 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4565 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004566 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004567 break;
4568 }
4569 case AINPUT_EVENT_TYPE_MOTION: {
4570 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4571 VerifiedMotionEvent verifiedMotionEvent =
4572 verifiedMotionEventFromMotionEvent(motionEvent);
4573 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004574 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004575 break;
4576 }
4577 default: {
4578 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4579 return nullptr;
4580 }
4581 }
4582 if (calculatedHmac == INVALID_HMAC) {
4583 return nullptr;
4584 }
4585 if (calculatedHmac != event.getHmac()) {
4586 return nullptr;
4587 }
4588 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004589}
4590
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004591void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004592 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004593 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004594 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004595 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004596 LOG(DEBUG) << "Setting input event injection result to "
4597 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004598 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004599
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004600 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004601 // Log the outcome since the injector did not wait for the injection result.
4602 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004603 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004604 ALOGV("Asynchronous input event injection succeeded.");
4605 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004606 case InputEventInjectionResult::TARGET_MISMATCH:
4607 ALOGV("Asynchronous input event injection target mismatch.");
4608 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004609 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004610 ALOGW("Asynchronous input event injection failed.");
4611 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004612 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004613 ALOGW("Asynchronous input event injection timed out.");
4614 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004615 case InputEventInjectionResult::PENDING:
4616 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4617 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004618 }
4619 }
4620
4621 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004622 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004623 }
4624}
4625
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004626void InputDispatcher::transformMotionEntryForInjectionLocked(
4627 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004628 // Input injection works in the logical display coordinate space, but the input pipeline works
4629 // display space, so we need to transform the injected events accordingly.
4630 const auto it = mDisplayInfos.find(entry.displayId);
4631 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004632 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004633
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004634 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4635 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4636 const vec2 cursor =
4637 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4638 {entry.xCursorPosition, entry.yCursorPosition});
4639 entry.xCursorPosition = cursor.x;
4640 entry.yCursorPosition = cursor.y;
4641 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004642 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004643 entry.pointerCoords[i] =
4644 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4645 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004646 }
4647}
4648
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004649void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4650 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004651 if (injectionState) {
4652 injectionState->pendingForegroundDispatches += 1;
4653 }
4654}
4655
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004656void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4657 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004658 if (injectionState) {
4659 injectionState->pendingForegroundDispatches -= 1;
4660
4661 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004662 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663 }
4664 }
4665}
4666
chaviw98318de2021-05-19 16:45:23 -05004667const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004668 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004669 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004670 auto it = mWindowHandlesByDisplay.find(displayId);
4671 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004672}
4673
chaviw98318de2021-05-19 16:45:23 -05004674sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004675 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004676 if (windowHandleToken == nullptr) {
4677 return nullptr;
4678 }
4679
Arthur Hungb92218b2018-08-14 12:00:21 +08004680 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004681 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4682 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004683 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004684 return windowHandle;
4685 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686 }
4687 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004688 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004689}
4690
chaviw98318de2021-05-19 16:45:23 -05004691sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4692 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004693 if (windowHandleToken == nullptr) {
4694 return nullptr;
4695 }
4696
chaviw98318de2021-05-19 16:45:23 -05004697 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004698 if (windowHandle->getToken() == windowHandleToken) {
4699 return windowHandle;
4700 }
4701 }
4702 return nullptr;
4703}
4704
chaviw98318de2021-05-19 16:45:23 -05004705sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4706 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004707 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004708 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4709 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004710 if (handle->getId() == windowHandle->getId() &&
4711 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004712 if (windowHandle->getInfo()->displayId != it.first) {
4713 ALOGE("Found window %s in display %" PRId32
4714 ", but it should belong to display %" PRId32,
4715 windowHandle->getName().c_str(), it.first,
4716 windowHandle->getInfo()->displayId);
4717 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004718 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004719 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720 }
4721 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004722 return nullptr;
4723}
4724
chaviw98318de2021-05-19 16:45:23 -05004725sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004726 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4727 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728}
4729
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004730bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4731 const MotionEntry& motionEntry) const {
4732 const WindowInfo& info = *window->getInfo();
4733
4734 // Skip spy window targets that are not valid for targeted injection.
4735 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004736 return false;
4737 }
4738
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004739 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4740 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4741 return false;
4742 }
4743
4744 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4745 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4746 window->getName().c_str());
4747 return false;
4748 }
4749
4750 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004751 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004752 ALOGW("Not sending touch to %s because there's no corresponding connection",
4753 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004754 return false;
4755 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004756
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004757 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004758 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004759 return false;
4760 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004761
4762 // Drop events that can't be trusted due to occlusion
4763 const auto [x, y] = resolveTouchedPosition(motionEntry);
4764 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4765 if (!isTouchTrustedLocked(occlusionInfo)) {
4766 if (DEBUG_TOUCH_OCCLUSION) {
4767 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4768 for (const auto& log : occlusionInfo.debugInfo) {
4769 ALOGD("%s", log.c_str());
4770 }
4771 }
4772 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4773 occlusionInfo.obscuringUid);
4774 return false;
4775 }
4776
4777 // Drop touch events if requested by input feature
4778 if (shouldDropInput(motionEntry, window)) {
4779 return false;
4780 }
4781
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004782 return true;
4783}
4784
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004785std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4786 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004787 auto connectionIt = mConnectionsByToken.find(token);
4788 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004789 return nullptr;
4790 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004791 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004792}
4793
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004794void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004795 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4796 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004797 // Remove all handles on a display if there are no windows left.
4798 mWindowHandlesByDisplay.erase(displayId);
4799 return;
4800 }
4801
4802 // Since we compare the pointer of input window handles across window updates, we need
4803 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004804 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4805 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4806 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004807 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004808 }
4809
chaviw98318de2021-05-19 16:45:23 -05004810 std::vector<sp<WindowInfoHandle>> newHandles;
4811 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004812 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004813 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004814 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004815 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004816 const bool canReceiveInput =
4817 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4818 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004819 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004820 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004821 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004822 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004823 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004824 }
4825
4826 if (info->displayId != displayId) {
4827 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4828 handle->getName().c_str(), displayId, info->displayId);
4829 continue;
4830 }
4831
Robert Carredd13602020-04-13 17:24:34 -07004832 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4833 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004834 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004835 oldHandle->updateFrom(handle);
4836 newHandles.push_back(oldHandle);
4837 } else {
4838 newHandles.push_back(handle);
4839 }
4840 }
4841
4842 // Insert or replace
4843 mWindowHandlesByDisplay[displayId] = newHandles;
4844}
4845
Arthur Hung72d8dc32020-03-28 00:48:39 +00004846void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004847 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004848 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004849 { // acquire lock
4850 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004851 for (const auto& [displayId, handles] : handlesPerDisplay) {
4852 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004853 }
4854 }
4855 // Wake up poll loop since it may need to make new input dispatching choices.
4856 mLooper->wake();
4857}
4858
Arthur Hungb92218b2018-08-14 12:00:21 +08004859/**
4860 * Called from InputManagerService, update window handle list by displayId that can receive input.
4861 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4862 * If set an empty list, remove all handles from the specific display.
4863 * For focused handle, check if need to change and send a cancel event to previous one.
4864 * For removed handle, check if need to send a cancel event if already in touch.
4865 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004866void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004867 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004868 if (DEBUG_FOCUS) {
4869 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004870 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004871 windowList += iwh->getName() + " ";
4872 }
4873 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4874 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875
Prabir Pradhand65552b2021-10-07 11:23:50 -07004876 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004877 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004878 const WindowInfo& info = *window->getInfo();
4879
4880 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004881 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004882 if (noInputWindow && window->getToken() != nullptr) {
4883 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4884 window->getName().c_str());
4885 window->releaseChannel();
4886 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004887
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004888 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004889 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4890 !info.inputConfig.test(
4891 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004892 "%s has feature SPY, but is not a trusted overlay.",
4893 window->getName().c_str());
4894
Prabir Pradhand65552b2021-10-07 11:23:50 -07004895 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004896 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4897 !info.inputConfig.test(
4898 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004899 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4900 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004901 }
4902
Arthur Hung72d8dc32020-03-28 00:48:39 +00004903 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004904 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004905
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004906 // Save the old windows' orientation by ID before it gets updated.
4907 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004908 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004909 oldWindowOrientations.emplace(handle->getId(),
4910 handle->getInfo()->transform.getOrientation());
4911 }
4912
chaviw98318de2021-05-19 16:45:23 -05004913 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004914
chaviw98318de2021-05-19 16:45:23 -05004915 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004916
Vishnu Nairc519ff72021-01-21 08:23:08 -08004917 std::optional<FocusResolver::FocusChanges> changes =
4918 mFocusResolver.setInputWindows(displayId, windowHandles);
4919 if (changes) {
4920 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004921 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004923 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4924 mTouchStatesByDisplay.find(displayId);
4925 if (stateIt != mTouchStatesByDisplay.end()) {
4926 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004927 for (size_t i = 0; i < state.windows.size();) {
4928 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004929 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004930 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004931 ALOGD("Touched window was removed: %s in display %" PRId32,
4932 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004933 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004934 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004935 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4936 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004937 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00004938 "touched window was removed");
4939 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004940 // Since we are about to drop the touch, cancel the events for the wallpaper as
4941 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004942 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004943 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4944 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004945 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004946 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004948 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004949 state.windows.erase(state.windows.begin() + i);
4950 } else {
4951 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004952 }
4953 }
arthurhungb89ccb02020-12-30 16:19:01 +08004954
arthurhung6d4bed92021-03-17 11:59:33 +08004955 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004956 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004957 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004958 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004959 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004960 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4961 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004962 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004963 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004964 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004965
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004966 // Determine if the orientation of any of the input windows have changed, and cancel all
4967 // pointer events if necessary.
4968 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4969 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4970 if (newWindowHandle != nullptr &&
4971 newWindowHandle->getInfo()->transform.getOrientation() !=
4972 oldWindowOrientations[oldWindowHandle->getId()]) {
4973 std::shared_ptr<InputChannel> inputChannel =
4974 getInputChannelLocked(newWindowHandle->getToken());
4975 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004976 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004977 "touched window's orientation changed");
4978 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004979 }
4980 }
4981 }
4982
Arthur Hung72d8dc32020-03-28 00:48:39 +00004983 // Release information for windows that are no longer present.
4984 // This ensures that unused input channels are released promptly.
4985 // Otherwise, they might stick around until the window handle is destroyed
4986 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004987 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004988 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004989 if (DEBUG_FOCUS) {
4990 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004991 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004992 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004993 }
chaviw291d88a2019-02-14 10:33:58 -08004994 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004995}
4996
4997void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004998 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004999 if (DEBUG_FOCUS) {
5000 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5001 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5002 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005003 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005004 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005005 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005006 } // release lock
5007
5008 // Wake up poll loop since it may need to make new input dispatching choices.
5009 mLooper->wake();
5010}
5011
Vishnu Nair599f1412021-06-21 10:39:58 -07005012void InputDispatcher::setFocusedApplicationLocked(
5013 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5014 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5015 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5016
5017 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5018 return; // This application is already focused. No need to wake up or change anything.
5019 }
5020
5021 // Set the new application handle.
5022 if (inputApplicationHandle != nullptr) {
5023 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5024 } else {
5025 mFocusedApplicationHandlesByDisplay.erase(displayId);
5026 }
5027
5028 // No matter what the old focused application was, stop waiting on it because it is
5029 // no longer focused.
5030 resetNoFocusedWindowTimeoutLocked();
5031}
5032
Tiger Huang721e26f2018-07-24 22:26:19 +08005033/**
5034 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5035 * the display not specified.
5036 *
5037 * We track any unreleased events for each window. If a window loses the ability to receive the
5038 * released event, we will send a cancel event to it. So when the focused display is changed, we
5039 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5040 * display. The display-specified events won't be affected.
5041 */
5042void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005043 if (DEBUG_FOCUS) {
5044 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5045 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005046 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005047 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005048
5049 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005050 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005051 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005052 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005053 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005054 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005055 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005056 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005057 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005058 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005059 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005060 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5061 }
5062 }
5063 mFocusedDisplayId = displayId;
5064
Chris Ye3c2d6f52020-08-09 10:39:48 -07005065 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005066 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005067 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005068
Vishnu Nairad321cd2020-08-20 16:40:21 -07005069 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005070 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005071 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005072 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005073 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005074 }
5075 }
5076 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005077 } // release lock
5078
5079 // Wake up poll loop since it may need to make new input dispatching choices.
5080 mLooper->wake();
5081}
5082
Michael Wrightd02c5b62014-02-10 15:10:22 -08005083void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005084 if (DEBUG_FOCUS) {
5085 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5086 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005087
5088 bool changed;
5089 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005090 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005091
5092 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5093 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005094 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005095 }
5096
5097 if (mDispatchEnabled && !enabled) {
5098 resetAndDropEverythingLocked("dispatcher is being disabled");
5099 }
5100
5101 mDispatchEnabled = enabled;
5102 mDispatchFrozen = frozen;
5103 changed = true;
5104 } else {
5105 changed = false;
5106 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005107 } // release lock
5108
5109 if (changed) {
5110 // Wake up poll loop since it may need to make new input dispatching choices.
5111 mLooper->wake();
5112 }
5113}
5114
5115void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005116 if (DEBUG_FOCUS) {
5117 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5118 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005119
5120 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005121 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005122
5123 if (mInputFilterEnabled == enabled) {
5124 return;
5125 }
5126
5127 mInputFilterEnabled = enabled;
5128 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5129 } // release lock
5130
5131 // Wake up poll loop since there might be work to do to drop everything.
5132 mLooper->wake();
5133}
5134
Antonio Kanteka042c022022-07-06 16:51:07 -07005135bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5136 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005137 bool needWake = false;
5138 {
5139 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005140 ALOGD_IF(DEBUG_TOUCH_MODE,
5141 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5142 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5143 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5144 mTouchModePerDisplay.count(displayId) == 0
5145 ? "not set"
5146 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5147
Antonio Kantek15beb512022-06-13 22:35:41 +00005148 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5149 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005150 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005151 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005152 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005153 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5154 !recentWindowsAreOwnedByLocked(pid, uid)) {
5155 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5156 "window nor none of the previously interacted window",
5157 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005158 return false;
5159 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005160 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005161 mTouchModePerDisplay[displayId] = inTouchMode;
5162 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5163 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005164 needWake = enqueueInboundEventLocked(std::move(entry));
5165 } // release lock
5166
5167 if (needWake) {
5168 mLooper->wake();
5169 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005170 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005171}
5172
Antonio Kantek48710e42022-03-24 14:19:30 -07005173bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5174 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5175 if (focusedToken == nullptr) {
5176 return false;
5177 }
5178 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5179 return isWindowOwnedBy(windowHandle, pid, uid);
5180}
5181
5182bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5183 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5184 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5185 const sp<WindowInfoHandle> windowHandle =
5186 getWindowHandleLocked(connectionToken);
5187 return isWindowOwnedBy(windowHandle, pid, uid);
5188 }) != mInteractionConnectionTokens.end();
5189}
5190
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005191void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5192 if (opacity < 0 || opacity > 1) {
5193 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5194 return;
5195 }
5196
5197 std::scoped_lock lock(mLock);
5198 mMaximumObscuringOpacityForTouch = opacity;
5199}
5200
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005201std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5202InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005203 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5204 for (TouchedWindow& w : state.windows) {
5205 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005206 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005207 }
5208 }
5209 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005210 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005211}
5212
arthurhungb89ccb02020-12-30 16:19:01 +08005213bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5214 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005215 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005216 if (DEBUG_FOCUS) {
5217 ALOGD("Trivial transfer to same window.");
5218 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005219 return true;
5220 }
5221
Michael Wrightd02c5b62014-02-10 15:10:22 -08005222 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005223 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005224
Arthur Hungabbb9d82021-09-01 14:52:30 +00005225 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005226 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005227 if (state == nullptr || touchedWindow == nullptr) {
5228 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005229 return false;
5230 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005231
Arthur Hungabbb9d82021-09-01 14:52:30 +00005232 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5233 if (toWindowHandle == nullptr) {
5234 ALOGW("Cannot transfer focus because to window not found.");
5235 return false;
5236 }
5237
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005238 if (DEBUG_FOCUS) {
5239 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005240 touchedWindow->windowHandle->getName().c_str(),
5241 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005242 }
5243
Arthur Hungabbb9d82021-09-01 14:52:30 +00005244 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005245 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005246 BitSet32 pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005247 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005248 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005249
Arthur Hungabbb9d82021-09-01 14:52:30 +00005250 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005251 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005252 ftl::Flags<InputTarget::Flags> newTargetFlags =
5253 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005254 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005255 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005256 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005257 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005258
Arthur Hungabbb9d82021-09-01 14:52:30 +00005259 // Store the dragging window.
5260 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005261 if (pointerIds.count() != 1) {
5262 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5263 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005264 return false;
5265 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005266 // Track the pointer id for drag window and generate the drag state.
5267 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005268 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005269 }
5270
Arthur Hungabbb9d82021-09-01 14:52:30 +00005271 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005272 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5273 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005274 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005275 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005276 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005277 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005278 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005279 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005280 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5281 newTargetFlags);
5282
5283 // Check if the wallpaper window should deliver the corresponding event.
5284 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5285 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005286 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005287 } // release lock
5288
5289 // Wake up poll loop since it may need to make new input dispatching choices.
5290 mLooper->wake();
5291 return true;
5292}
5293
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005294/**
5295 * Get the touched foreground window on the given display.
5296 * Return null if there are no windows touched on that display, or if more than one foreground
5297 * window is being touched.
5298 */
5299sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5300 auto stateIt = mTouchStatesByDisplay.find(displayId);
5301 if (stateIt == mTouchStatesByDisplay.end()) {
5302 ALOGI("No touch state on display %" PRId32, displayId);
5303 return nullptr;
5304 }
5305
5306 const TouchState& state = stateIt->second;
5307 sp<WindowInfoHandle> touchedForegroundWindow;
5308 // If multiple foreground windows are touched, return nullptr
5309 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005310 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005311 if (touchedForegroundWindow != nullptr) {
5312 ALOGI("Two or more foreground windows: %s and %s",
5313 touchedForegroundWindow->getName().c_str(),
5314 window.windowHandle->getName().c_str());
5315 return nullptr;
5316 }
5317 touchedForegroundWindow = window.windowHandle;
5318 }
5319 }
5320 return touchedForegroundWindow;
5321}
5322
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005323// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005324bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005325 sp<IBinder> fromToken;
5326 { // acquire lock
5327 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005328 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005329 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005330 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5331 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005332 return false;
5333 }
5334
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005335 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5336 if (from == nullptr) {
5337 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5338 return false;
5339 }
5340
5341 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005342 } // release lock
5343
5344 return transferTouchFocus(fromToken, destChannelToken);
5345}
5346
Michael Wrightd02c5b62014-02-10 15:10:22 -08005347void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005348 if (DEBUG_FOCUS) {
5349 ALOGD("Resetting and dropping all events (%s).", reason);
5350 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351
Michael Wrightfb04fd52022-11-24 22:31:11 +00005352 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005353 synthesizeCancelationEventsForAllConnectionsLocked(options);
5354
5355 resetKeyRepeatLocked();
5356 releasePendingEventLocked();
5357 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005358 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005360 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005361 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005362 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005363}
5364
5365void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005366 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005367 dumpDispatchStateLocked(dump);
5368
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005369 std::istringstream stream(dump);
5370 std::string line;
5371
5372 while (std::getline(stream, line, '\n')) {
5373 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005374 }
5375}
5376
Prabir Pradhan99987712020-11-10 18:43:05 -08005377std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5378 std::string dump;
5379
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005380 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5381 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005382
5383 std::string windowName = "None";
5384 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005385 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005386 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5387 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5388 : "token has capture without window";
5389 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005390 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005391
5392 return dump;
5393}
5394
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005395void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005396 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5397 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5398 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005399 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005400
Tiger Huang721e26f2018-07-24 22:26:19 +08005401 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5402 dump += StringPrintf(INDENT "FocusedApplications:\n");
5403 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5404 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005405 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005406 const std::chrono::duration timeout =
5407 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005408 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005409 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005410 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005411 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005412 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005413 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005414 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005415
Vishnu Nairc519ff72021-01-21 08:23:08 -08005416 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005417 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005418
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005419 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005420 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005421 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005422 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5423 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005424 }
5425 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005426 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005427 }
5428
arthurhung6d4bed92021-03-17 11:59:33 +08005429 if (mDragState) {
5430 dump += StringPrintf(INDENT "DragState:\n");
5431 mDragState->dump(dump, INDENT2);
5432 }
5433
Arthur Hungb92218b2018-08-14 12:00:21 +08005434 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005435 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5436 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5437 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5438 const auto& displayInfo = it->second;
5439 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5440 displayInfo.logicalHeight);
5441 displayInfo.transform.dump(dump, "transform", INDENT4);
5442 } else {
5443 dump += INDENT2 "No DisplayInfo found!\n";
5444 }
5445
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005446 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005447 dump += INDENT2 "Windows:\n";
5448 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005449 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5450 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005451
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005452 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005453 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005454 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005455 "applicationInfo.name=%s, "
5456 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005457 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005458 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005459 windowInfo->displayId,
5460 windowInfo->inputConfig.string().c_str(),
5461 windowInfo->alpha, windowInfo->frameLeft,
5462 windowInfo->frameTop, windowInfo->frameRight,
5463 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005464 windowInfo->applicationInfo.name.c_str(),
5465 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005466 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005467 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005468 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005469 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005470 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005471 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005472 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005473 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005474 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005475 }
5476 } else {
5477 dump += INDENT2 "Windows: <none>\n";
5478 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005479 }
5480 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005481 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482 }
5483
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005484 if (!mGlobalMonitorsByDisplay.empty()) {
5485 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5486 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005487 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005488 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005489 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005490 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005491 }
5492
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005493 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005494
5495 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005496 if (!mRecentQueue.empty()) {
5497 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005498 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
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 "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005505 }
5506
5507 // Dump event currently being dispatched.
5508 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005509 dump += INDENT "PendingEvent:\n";
5510 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005511 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005512 dump += StringPrintf(", age=%" PRId64 "ms\n",
5513 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005514 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005515 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005516 }
5517
5518 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005519 if (!mInboundQueue.empty()) {
5520 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005521 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005522 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005523 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005524 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005525 }
5526 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005527 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005528 }
5529
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005530 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005531 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005532 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005533 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005534 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005535 }
5536 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005537 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005538 }
5539
Prabir Pradhancef936d2021-07-21 16:17:52 +00005540 if (!mCommandQueue.empty()) {
5541 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5542 } else {
5543 dump += INDENT "CommandQueue: <empty>\n";
5544 }
5545
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005546 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005547 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005548 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005549 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005550 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005551 connection->inputChannel->getFd().get(),
5552 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005553 connection->getWindowName().c_str(),
5554 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005555 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005556
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005557 if (!connection->outboundQueue.empty()) {
5558 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5559 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005560 dump += dumpQueue(connection->outboundQueue, currentTime);
5561
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005563 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005564 }
5565
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005566 if (!connection->waitQueue.empty()) {
5567 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5568 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005569 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005570 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005571 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005572 }
5573 }
5574 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005575 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005576 }
5577
5578 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005579 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5580 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005581 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005582 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005583 }
5584
Antonio Kantek15beb512022-06-13 22:35:41 +00005585 if (!mTouchModePerDisplay.empty()) {
5586 dump += INDENT "TouchModePerDisplay:\n";
5587 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5588 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5589 std::to_string(touchMode).c_str());
5590 }
5591 } else {
5592 dump += INDENT "TouchModePerDisplay: <none>\n";
5593 }
5594
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005595 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005596 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5597 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5598 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005599 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005600 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005601}
5602
Michael Wright3dd60e22019-03-27 22:06:44 +00005603void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5604 const size_t numMonitors = monitors.size();
5605 for (size_t i = 0; i < numMonitors; i++) {
5606 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005607 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005608 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5609 dump += "\n";
5610 }
5611}
5612
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005613class LooperEventCallback : public LooperCallback {
5614public:
5615 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5616 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5617
5618private:
5619 std::function<int(int events)> mCallback;
5620};
5621
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005622Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005623 if (DEBUG_CHANNEL_CREATION) {
5624 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5625 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005626
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005627 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005628 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005629 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005630
5631 if (result) {
5632 return base::Error(result) << "Failed to open input channel pair with name " << name;
5633 }
5634
Michael Wrightd02c5b62014-02-10 15:10:22 -08005635 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005636 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005637 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005638 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005639 sp<Connection> connection =
Harry Cutts33476232023-01-30 19:57:29 +00005640 sp<Connection>::make(std::move(serverChannel), /*monitor=*/false, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005641
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005642 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5643 ALOGE("Created a new connection, but the token %p is already known", token.get());
5644 }
5645 mConnectionsByToken.emplace(token, connection);
5646
5647 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5648 this, std::placeholders::_1, token);
5649
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005650 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5651 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005652 } // release lock
5653
5654 // Wake the looper because some connections have changed.
5655 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005656 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005657}
5658
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005659Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005660 const std::string& name,
5661 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005662 std::shared_ptr<InputChannel> serverChannel;
5663 std::unique_ptr<InputChannel> clientChannel;
5664 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5665 if (result) {
5666 return base::Error(result) << "Failed to open input channel pair with name " << name;
5667 }
5668
Michael Wright3dd60e22019-03-27 22:06:44 +00005669 { // acquire lock
5670 std::scoped_lock _l(mLock);
5671
5672 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005673 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5674 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005675 }
5676
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005677 sp<Connection> connection =
Harry Cutts33476232023-01-30 19:57:29 +00005678 sp<Connection>::make(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005679 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005680 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005681
5682 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5683 ALOGE("Created a new connection, but the token %p is already known", token.get());
5684 }
5685 mConnectionsByToken.emplace(token, connection);
5686 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5687 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005688
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005689 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005690
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005691 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5692 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005693 }
Garfield Tan15601662020-09-22 15:32:38 -07005694
Michael Wright3dd60e22019-03-27 22:06:44 +00005695 // Wake the looper because some connections have changed.
5696 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005697 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005698}
5699
Garfield Tan15601662020-09-22 15:32:38 -07005700status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005701 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005702 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005703
Harry Cutts33476232023-01-30 19:57:29 +00005704 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005705 if (status) {
5706 return status;
5707 }
5708 } // release lock
5709
5710 // Wake the poll loop because removing the connection may have changed the current
5711 // synchronization state.
5712 mLooper->wake();
5713 return OK;
5714}
5715
Garfield Tan15601662020-09-22 15:32:38 -07005716status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5717 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005718 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005719 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005720 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005721 return BAD_VALUE;
5722 }
5723
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005724 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005725
Michael Wrightd02c5b62014-02-10 15:10:22 -08005726 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005727 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005728 }
5729
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005730 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005731
5732 nsecs_t currentTime = now();
5733 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5734
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005735 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005736 return OK;
5737}
5738
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005739void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005740 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5741 auto& [displayId, monitors] = *it;
5742 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5743 return monitor.inputChannel->getConnectionToken() == connectionToken;
5744 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005745
Michael Wright3dd60e22019-03-27 22:06:44 +00005746 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005747 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005748 } else {
5749 ++it;
5750 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005751 }
5752}
5753
Michael Wright3dd60e22019-03-27 22:06:44 +00005754status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005755 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005756 return pilferPointersLocked(token);
5757}
Michael Wright3dd60e22019-03-27 22:06:44 +00005758
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005759status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005760 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5761 if (!requestingChannel) {
5762 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5763 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005764 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005765
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005766 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07005767 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.isEmpty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005768 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5769 " Ignoring.");
5770 return BAD_VALUE;
5771 }
5772
5773 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005774 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005775 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005776 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005777 "input channel stole pointer stream");
5778 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005779 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005780 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005781 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005782 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005783 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005784 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005785 if (channel != nullptr && channel->getConnectionToken() != token) {
5786 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5787 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5788 canceledWindows += channel->getName();
5789 }
5790 }
5791 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5792 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5793 canceledWindows.c_str());
5794
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005795 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005796 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08005797 for (BitSet32 idBits(window.pointerIds); !idBits.isEmpty();) {
5798 uint32_t id = idBits.clearFirstMarkedBit();
5799 window.pilferedPointerIds.set(id);
5800 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005801
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005802 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005803 return OK;
5804}
5805
Prabir Pradhan99987712020-11-10 18:43:05 -08005806void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5807 { // acquire lock
5808 std::scoped_lock _l(mLock);
5809 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005810 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005811 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5812 windowHandle != nullptr ? windowHandle->getName().c_str()
5813 : "token without window");
5814 }
5815
Vishnu Nairc519ff72021-01-21 08:23:08 -08005816 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005817 if (focusedToken != windowToken) {
5818 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5819 enabled ? "enable" : "disable");
5820 return;
5821 }
5822
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005823 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005824 ALOGW("Ignoring request to %s Pointer Capture: "
5825 "window has %s requested pointer capture.",
5826 enabled ? "enable" : "disable", enabled ? "already" : "not");
5827 return;
5828 }
5829
Christine Franksb768bb42021-11-29 12:11:31 -08005830 if (enabled) {
5831 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5832 mIneligibleDisplaysForPointerCapture.end(),
5833 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5834 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5835 return;
5836 }
5837 }
5838
Prabir Pradhan99987712020-11-10 18:43:05 -08005839 setPointerCaptureLocked(enabled);
5840 } // release lock
5841
5842 // Wake the thread to process command entries.
5843 mLooper->wake();
5844}
5845
Christine Franksb768bb42021-11-29 12:11:31 -08005846void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5847 { // acquire lock
5848 std::scoped_lock _l(mLock);
5849 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5850 if (!isEligible) {
5851 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5852 }
5853 } // release lock
5854}
5855
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005856std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5857 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005858 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005859 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005860 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005861 }
5862 }
5863 }
5864 return std::nullopt;
5865}
5866
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005867sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005868 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005869 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005870 }
5871
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005872 for (const auto& [token, connection] : mConnectionsByToken) {
5873 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005874 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005875 }
5876 }
Robert Carr4e670e52018-08-15 13:26:12 -07005877
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005878 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005879}
5880
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005881std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5882 sp<Connection> connection = getConnectionLocked(connectionToken);
5883 if (connection == nullptr) {
5884 return "<nullptr>";
5885 }
5886 return connection->getInputChannelName();
5887}
5888
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005889void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005890 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005891 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005892}
5893
Prabir Pradhancef936d2021-07-21 16:17:52 +00005894void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5895 const sp<Connection>& connection, uint32_t seq,
5896 bool handled, nsecs_t consumeTime) {
5897 // Handle post-event policy actions.
5898 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5899 if (dispatchEntryIt == connection->waitQueue.end()) {
5900 return;
5901 }
5902 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5903 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5904 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5905 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5906 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5907 }
5908 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5909 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5910 connection->inputChannel->getConnectionToken(),
5911 dispatchEntry->deliveryTime, consumeTime, finishTime);
5912 }
5913
5914 bool restartEvent;
5915 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5916 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5917 restartEvent =
5918 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5919 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5920 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5921 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5922 handled);
5923 } else {
5924 restartEvent = false;
5925 }
5926
5927 // Dequeue the event and start the next cycle.
5928 // Because the lock might have been released, it is possible that the
5929 // contents of the wait queue to have been drained, so we need to double-check
5930 // a few things.
5931 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5932 if (dispatchEntryIt != connection->waitQueue.end()) {
5933 dispatchEntry = *dispatchEntryIt;
5934 connection->waitQueue.erase(dispatchEntryIt);
5935 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5936 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5937 if (!connection->responsive) {
5938 connection->responsive = isConnectionResponsive(*connection);
5939 if (connection->responsive) {
5940 // The connection was unresponsive, and now it's responsive.
5941 processConnectionResponsiveLocked(*connection);
5942 }
5943 }
5944 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005945 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005946 connection->outboundQueue.push_front(dispatchEntry);
5947 traceOutboundQueueLength(*connection);
5948 } else {
5949 releaseDispatchEntry(dispatchEntry);
5950 }
5951 }
5952
5953 // Start the next dispatch cycle for this connection.
5954 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005955}
5956
Prabir Pradhancef936d2021-07-21 16:17:52 +00005957void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5958 const sp<IBinder>& newToken) {
5959 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5960 scoped_unlock unlock(mLock);
5961 mPolicy->notifyFocusChanged(oldToken, newToken);
5962 };
5963 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005964}
5965
Prabir Pradhancef936d2021-07-21 16:17:52 +00005966void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5967 auto command = [this, token, x, y]() REQUIRES(mLock) {
5968 scoped_unlock unlock(mLock);
5969 mPolicy->notifyDropWindow(token, x, y);
5970 };
5971 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005972}
5973
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005974void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5975 if (connection == nullptr) {
5976 LOG_ALWAYS_FATAL("Caller must check for nullness");
5977 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005978 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5979 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005980 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005981 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005982 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005983 return;
5984 }
5985 /**
5986 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5987 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5988 * has changed. This could cause newer entries to time out before the already dispatched
5989 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5990 * processes the events linearly. So providing information about the oldest entry seems to be
5991 * most useful.
5992 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005993 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005994 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5995 std::string reason =
5996 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005997 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005998 ns2ms(currentWait),
5999 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006000 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006001 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006002
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006003 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6004
6005 // Stop waking up for events on this connection, it is already unresponsive
6006 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006007}
6008
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006009void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6010 std::string reason =
6011 StringPrintf("%s does not have a focused window", application->getName().c_str());
6012 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006013
Prabir Pradhancef936d2021-07-21 16:17:52 +00006014 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
6015 scoped_unlock unlock(mLock);
6016 mPolicy->notifyNoFocusedWindowAnr(application);
6017 };
6018 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006019}
6020
chaviw98318de2021-05-19 16:45:23 -05006021void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006022 const std::string& reason) {
6023 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6024 updateLastAnrStateLocked(windowLabel, reason);
6025}
6026
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006027void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6028 const std::string& reason) {
6029 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006030 updateLastAnrStateLocked(windowLabel, reason);
6031}
6032
6033void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6034 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006035 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006036 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006037 struct tm tm;
6038 localtime_r(&t, &tm);
6039 char timestr[64];
6040 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006041 mLastAnrState.clear();
6042 mLastAnrState += INDENT "ANR:\n";
6043 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006044 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6045 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006046 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006047}
6048
Prabir Pradhancef936d2021-07-21 16:17:52 +00006049void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6050 KeyEntry& entry) {
6051 const KeyEvent event = createKeyEvent(entry);
6052 nsecs_t delay = 0;
6053 { // release lock
6054 scoped_unlock unlock(mLock);
6055 android::base::Timer t;
6056 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
6057 entry.policyFlags);
6058 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6059 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6060 std::to_string(t.duration().count()).c_str());
6061 }
6062 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006063
6064 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006065 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006066 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006067 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006068 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006069 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006070 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006071 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006072}
6073
Prabir Pradhancef936d2021-07-21 16:17:52 +00006074void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006075 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006076 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006077 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006078 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006079 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006080 };
6081 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006082}
6083
Prabir Pradhanedd96402022-02-15 01:46:16 -08006084void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6085 std::optional<int32_t> pid) {
6086 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006087 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006088 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006089 };
6090 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006091}
6092
6093/**
6094 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6095 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6096 * command entry to the command queue.
6097 */
6098void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6099 std::string reason) {
6100 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006101 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006102 if (connection.monitor) {
6103 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6104 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006105 pid = findMonitorPidByTokenLocked(connectionToken);
6106 } else {
6107 // The connection is a window
6108 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6109 reason.c_str());
6110 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6111 if (handle != nullptr) {
6112 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006113 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006114 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006115 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006116}
6117
6118/**
6119 * Tell the policy that a connection has become responsive so that it can stop ANR.
6120 */
6121void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6122 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006123 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006124 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006125 pid = findMonitorPidByTokenLocked(connectionToken);
6126 } else {
6127 // The connection is a window
6128 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6129 if (handle != nullptr) {
6130 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006131 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006132 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006133 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006134}
6135
Prabir Pradhancef936d2021-07-21 16:17:52 +00006136bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006137 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006138 KeyEntry& keyEntry, bool handled) {
6139 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006140 if (!handled) {
6141 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006142 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006143 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006144 return false;
6145 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006146
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006147 // Get the fallback key state.
6148 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006149 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006150 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006151 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006152 connection->inputState.removeFallbackKey(originalKeyCode);
6153 }
6154
6155 if (handled || !dispatchEntry->hasForegroundTarget()) {
6156 // If the application handles the original key for which we previously
6157 // generated a fallback or if the window is not a foreground window,
6158 // then cancel the associated fallback key, if any.
6159 if (fallbackKeyCode != -1) {
6160 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006161 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6162 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6163 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6164 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6165 keyEntry.policyFlags);
6166 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006167 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006168 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006169
6170 mLock.unlock();
6171
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006172 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006173 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006174
6175 mLock.lock();
6176
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006177 // Cancel the fallback key.
6178 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006179 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006180 "application handled the original non-fallback key "
6181 "or is no longer a foreground target, "
6182 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006183 options.keyCode = fallbackKeyCode;
6184 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006185 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006186 connection->inputState.removeFallbackKey(originalKeyCode);
6187 }
6188 } else {
6189 // If the application did not handle a non-fallback key, first check
6190 // that we are in a good state to perform unhandled key event processing
6191 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006192 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006193 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006194 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6195 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6196 "since this is not an initial down. "
6197 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6198 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6199 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006200 return false;
6201 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006202
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006203 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006204 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6205 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6206 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6207 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6208 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006209 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006210
6211 mLock.unlock();
6212
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006213 bool fallback =
6214 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006215 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006216
6217 mLock.lock();
6218
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006219 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006220 connection->inputState.removeFallbackKey(originalKeyCode);
6221 return false;
6222 }
6223
6224 // Latch the fallback keycode for this key on an initial down.
6225 // The fallback keycode cannot change at any other point in the lifecycle.
6226 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006227 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006228 fallbackKeyCode = event.getKeyCode();
6229 } else {
6230 fallbackKeyCode = AKEYCODE_UNKNOWN;
6231 }
6232 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6233 }
6234
6235 ALOG_ASSERT(fallbackKeyCode != -1);
6236
6237 // Cancel the fallback key if the policy decides not to send it anymore.
6238 // We will continue to dispatch the key to the policy but we will no
6239 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006240 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6241 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006242 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6243 if (fallback) {
6244 ALOGD("Unhandled key event: Policy requested to send key %d"
6245 "as a fallback for %d, but on the DOWN it had requested "
6246 "to send %d instead. Fallback canceled.",
6247 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6248 } else {
6249 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6250 "but on the DOWN it had requested to send %d. "
6251 "Fallback canceled.",
6252 originalKeyCode, fallbackKeyCode);
6253 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006254 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006255
Michael Wrightfb04fd52022-11-24 22:31:11 +00006256 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006257 "canceling fallback, policy no longer desires it");
6258 options.keyCode = fallbackKeyCode;
6259 synthesizeCancelationEventsForConnectionLocked(connection, options);
6260
6261 fallback = false;
6262 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006263 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006264 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006265 }
6266 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006267
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006268 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6269 {
6270 std::string msg;
6271 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6272 connection->inputState.getFallbackKeys();
6273 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6274 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6275 }
6276 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6277 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006278 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006279 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006280
6281 if (fallback) {
6282 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006283 keyEntry.eventTime = event.getEventTime();
6284 keyEntry.deviceId = event.getDeviceId();
6285 keyEntry.source = event.getSource();
6286 keyEntry.displayId = event.getDisplayId();
6287 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6288 keyEntry.keyCode = fallbackKeyCode;
6289 keyEntry.scanCode = event.getScanCode();
6290 keyEntry.metaState = event.getMetaState();
6291 keyEntry.repeatCount = event.getRepeatCount();
6292 keyEntry.downTime = event.getDownTime();
6293 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006294
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006295 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6296 ALOGD("Unhandled key event: Dispatching fallback key. "
6297 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6298 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6299 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006300 return true; // restart the event
6301 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006302 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6303 ALOGD("Unhandled key event: No fallback key.");
6304 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006305
6306 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006307 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006308 }
6309 }
6310 return false;
6311}
6312
Prabir Pradhancef936d2021-07-21 16:17:52 +00006313bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006314 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006315 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006316 return false;
6317}
6318
Michael Wrightd02c5b62014-02-10 15:10:22 -08006319void InputDispatcher::traceInboundQueueLengthLocked() {
6320 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006321 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006322 }
6323}
6324
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006325void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006326 if (ATRACE_ENABLED()) {
6327 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006328 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6329 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006330 }
6331}
6332
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006333void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006334 if (ATRACE_ENABLED()) {
6335 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006336 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6337 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006338 }
6339}
6340
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006341void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006342 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006343
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006344 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006345 dumpDispatchStateLocked(dump);
6346
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006347 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006348 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006349 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006350 }
6351}
6352
6353void InputDispatcher::monitor() {
6354 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006355 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006356 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006357 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006358}
6359
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006360/**
6361 * Wake up the dispatcher and wait until it processes all events and commands.
6362 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6363 * this method can be safely called from any thread, as long as you've ensured that
6364 * the work you are interested in completing has already been queued.
6365 */
6366bool InputDispatcher::waitForIdle() {
6367 /**
6368 * Timeout should represent the longest possible time that a device might spend processing
6369 * events and commands.
6370 */
6371 constexpr std::chrono::duration TIMEOUT = 100ms;
6372 std::unique_lock lock(mLock);
6373 mLooper->wake();
6374 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6375 return result == std::cv_status::no_timeout;
6376}
6377
Vishnu Naire798b472020-07-23 13:52:21 -07006378/**
6379 * Sets focus to the window identified by the token. This must be called
6380 * after updating any input window handles.
6381 *
6382 * Params:
6383 * request.token - input channel token used to identify the window that should gain focus.
6384 * request.focusedToken - the token that the caller expects currently to be focused. If the
6385 * specified token does not match the currently focused window, this request will be dropped.
6386 * If the specified focused token matches the currently focused window, the call will succeed.
6387 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6388 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6389 * when requesting the focus change. This determines which request gets
6390 * precedence if there is a focus change request from another source such as pointer down.
6391 */
Vishnu Nair958da932020-08-21 17:12:37 -07006392void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6393 { // acquire lock
6394 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006395 std::optional<FocusResolver::FocusChanges> changes =
6396 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6397 if (changes) {
6398 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006399 }
6400 } // release lock
6401 // Wake up poll loop since it may need to make new input dispatching choices.
6402 mLooper->wake();
6403}
6404
Vishnu Nairc519ff72021-01-21 08:23:08 -08006405void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6406 if (changes.oldFocus) {
6407 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006408 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006409 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006410 "focus left window");
6411 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006412 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006413 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006414 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006415 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006416 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006417 }
6418
Prabir Pradhan99987712020-11-10 18:43:05 -08006419 // If a window has pointer capture, then it must have focus. We need to ensure that this
6420 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6421 // If the window loses focus before it loses pointer capture, then the window can be in a state
6422 // where it has pointer capture but not focus, violating the contract. Therefore we must
6423 // dispatch the pointer capture event before the focus event. Since focus events are added to
6424 // the front of the queue (above), we add the pointer capture event to the front of the queue
6425 // after the focus events are added. This ensures the pointer capture event ends up at the
6426 // front.
6427 disablePointerCaptureForcedLocked();
6428
Vishnu Nairc519ff72021-01-21 08:23:08 -08006429 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006430 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006431 }
6432}
Vishnu Nair958da932020-08-21 17:12:37 -07006433
Prabir Pradhan99987712020-11-10 18:43:05 -08006434void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006435 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006436 return;
6437 }
6438
6439 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6440
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006441 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006442 setPointerCaptureLocked(false);
6443 }
6444
6445 if (!mWindowTokenWithPointerCapture) {
6446 // No need to send capture changes because no window has capture.
6447 return;
6448 }
6449
6450 if (mPendingEvent != nullptr) {
6451 // Move the pending event to the front of the queue. This will give the chance
6452 // for the pending event to be dropped if it is a captured event.
6453 mInboundQueue.push_front(mPendingEvent);
6454 mPendingEvent = nullptr;
6455 }
6456
6457 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006458 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006459 mInboundQueue.push_front(std::move(entry));
6460}
6461
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006462void InputDispatcher::setPointerCaptureLocked(bool enable) {
6463 mCurrentPointerCaptureRequest.enable = enable;
6464 mCurrentPointerCaptureRequest.seq++;
6465 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006466 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006467 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006468 };
6469 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006470}
6471
Vishnu Nair599f1412021-06-21 10:39:58 -07006472void InputDispatcher::displayRemoved(int32_t displayId) {
6473 { // acquire lock
6474 std::scoped_lock _l(mLock);
6475 // Set an empty list to remove all handles from the specific display.
6476 setInputWindowsLocked(/* window handles */ {}, displayId);
6477 setFocusedApplicationLocked(displayId, nullptr);
6478 // Call focus resolver to clean up stale requests. This must be called after input windows
6479 // have been removed for the removed display.
6480 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006481 // Reset pointer capture eligibility, regardless of previous state.
6482 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006483 // Remove the associated touch mode state.
6484 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006485 } // release lock
6486
6487 // Wake up poll loop since it may need to make new input dispatching choices.
6488 mLooper->wake();
6489}
6490
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006491void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6492 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006493 // The listener sends the windows as a flattened array. Separate the windows by display for
6494 // more convenient parsing.
6495 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006496 for (const auto& info : windowInfos) {
6497 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006498 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006499 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006500
6501 { // acquire lock
6502 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006503
6504 // Ensure that we have an entry created for all existing displays so that if a displayId has
6505 // no windows, we can tell that the windows were removed from the display.
6506 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6507 handlesPerDisplay[displayId];
6508 }
6509
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006510 mDisplayInfos.clear();
6511 for (const auto& displayInfo : displayInfos) {
6512 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6513 }
6514
6515 for (const auto& [displayId, handles] : handlesPerDisplay) {
6516 setInputWindowsLocked(handles, displayId);
6517 }
6518 }
6519 // Wake up poll loop since it may need to make new input dispatching choices.
6520 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006521}
6522
Vishnu Nair062a8672021-09-03 16:07:44 -07006523bool InputDispatcher::shouldDropInput(
6524 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006525 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6526 (windowHandle->getInfo()->inputConfig.test(
6527 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006528 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006529 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6530 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006531 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006532 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006533 windowHandle->getInfo()->displayId);
6534 return true;
6535 }
6536 return false;
6537}
6538
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006539void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6540 const std::vector<gui::WindowInfo>& windowInfos,
6541 const std::vector<DisplayInfo>& displayInfos) {
6542 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6543}
6544
Arthur Hungdfd528e2021-12-08 13:23:04 +00006545void InputDispatcher::cancelCurrentTouch() {
6546 {
6547 std::scoped_lock _l(mLock);
6548 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006549 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006550 "cancel current touch");
6551 synthesizeCancelationEventsForAllConnectionsLocked(options);
6552
6553 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006554 }
6555 // Wake up poll loop since there might be work to do.
6556 mLooper->wake();
6557}
6558
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006559void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6560 std::scoped_lock _l(mLock);
6561 mMonitorDispatchingTimeout = timeout;
6562}
6563
Arthur Hungc539dbb2022-12-08 07:45:36 +00006564void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6565 const sp<WindowInfoHandle>& oldWindowHandle,
6566 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006567 TouchState& state, int32_t pointerId,
6568 std::vector<InputTarget>& targets) {
6569 BitSet32 pointerIds;
6570 pointerIds.markBit(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006571 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6572 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6573 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6574 newWindowHandle->getInfo()->inputConfig.test(
6575 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6576 const sp<WindowInfoHandle> oldWallpaper =
6577 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6578 const sp<WindowInfoHandle> newWallpaper =
6579 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6580 if (oldWallpaper == newWallpaper) {
6581 return;
6582 }
6583
6584 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006585 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6586 addWindowTargetLocked(oldWallpaper,
6587 oldTouchedWindow.targetFlags |
6588 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6589 pointerIds, oldTouchedWindow.firstDownTimeInTarget, targets);
6590 state.removeTouchedPointerFromWindow(pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006591 }
6592
6593 if (newWallpaper != nullptr) {
6594 state.addOrUpdateWindow(newWallpaper,
6595 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6596 InputTarget::Flags::WINDOW_IS_OBSCURED |
6597 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6598 pointerIds);
6599 }
6600}
6601
6602void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6603 ftl::Flags<InputTarget::Flags> newTargetFlags,
6604 const sp<WindowInfoHandle> fromWindowHandle,
6605 const sp<WindowInfoHandle> toWindowHandle,
6606 TouchState& state, const BitSet32& pointerIds) {
6607 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6608 fromWindowHandle->getInfo()->inputConfig.test(
6609 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6610 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6611 toWindowHandle->getInfo()->inputConfig.test(
6612 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6613
6614 const sp<WindowInfoHandle> oldWallpaper =
6615 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6616 const sp<WindowInfoHandle> newWallpaper =
6617 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6618 if (oldWallpaper == newWallpaper) {
6619 return;
6620 }
6621
6622 if (oldWallpaper != nullptr) {
6623 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6624 "transferring touch focus to another window");
6625 state.removeWindowByToken(oldWallpaper->getToken());
6626 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6627 }
6628
6629 if (newWallpaper != nullptr) {
6630 nsecs_t downTimeInTarget = now();
6631 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6632 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6633 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6634 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6635 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
6636 sp<Connection> wallpaperConnection = getConnectionLocked(newWallpaper->getToken());
6637 if (wallpaperConnection != nullptr) {
6638 sp<Connection> toConnection = getConnectionLocked(toWindowHandle->getToken());
6639 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6640 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6641 wallpaperFlags);
6642 }
6643 }
6644}
6645
6646sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6647 const sp<WindowInfoHandle>& windowHandle) const {
6648 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6649 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6650 bool foundWindow = false;
6651 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6652 if (!foundWindow && otherHandle != windowHandle) {
6653 continue;
6654 }
6655 if (windowHandle == otherHandle) {
6656 foundWindow = true;
6657 continue;
6658 }
6659
6660 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6661 return otherHandle;
6662 }
6663 }
6664 return nullptr;
6665}
6666
Garfield Tane84e6f92019-08-29 17:28:41 -07006667} // namespace android::inputdispatcher