blob: 204fff45667b0a556a7461a34b52b0c73026db71 [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
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000620} // namespace
621
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622// --- InputDispatcher ---
623
Garfield Tan00f511d2019-06-12 16:55:40 -0700624InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800625 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
626
627InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
628 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700629 : mPolicy(policy),
630 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700631 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800632 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700633 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700634 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700635 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800636 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700637 mDispatchEnabled(false),
638 mDispatchFrozen(false),
639 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100640 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000641 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800642 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800643 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000644 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000645 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700646 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800647 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800648
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700649 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700650#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700651 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700652#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700653 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800654 policy->getDispatcherConfiguration(&mConfig);
655}
656
657InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000658 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800659
Prabir Pradhancef936d2021-07-21 16:17:52 +0000660 resetKeyRepeatLocked();
661 releasePendingEventLocked();
662 drainInboundQueueLocked();
663 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800664
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000665 while (!mConnectionsByToken.empty()) {
666 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000667 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
668 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800669 }
670}
671
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700672status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700673 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700674 return ALREADY_EXISTS;
675 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700676 mThread = std::make_unique<InputThread>(
677 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
678 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700679}
680
681status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700682 if (mThread && mThread->isCallingThread()) {
683 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700684 return INVALID_OPERATION;
685 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700686 mThread.reset();
687 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700688}
689
Michael Wrightd02c5b62014-02-10 15:10:22 -0800690void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700691 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800693 std::scoped_lock _l(mLock);
694 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800695
696 // Run a dispatch loop if there are no pending commands.
697 // The dispatch loop might enqueue commands to run afterwards.
698 if (!haveCommandsLocked()) {
699 dispatchOnceInnerLocked(&nextWakeupTime);
700 }
701
702 // Run all pending commands if there are any.
703 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000704 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700705 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800706 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800707
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700708 // If we are still waiting for ack on some events,
709 // we might have to wake up earlier to check if an app is anr'ing.
710 const nsecs_t nextAnrCheck = processAnrsLocked();
711 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
712
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800713 // We are about to enter an infinitely long sleep, because we have no commands or
714 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700715 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800716 mDispatcherEnteredIdle.notify_all();
717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718 } // release lock
719
720 // Wait for callback or timeout or wake. (make sure we round up, not down)
721 nsecs_t currentTime = now();
722 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
723 mLooper->pollOnce(timeoutMillis);
724}
725
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700726/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500727 * Raise ANR if there is no focused window.
728 * Before the ANR is raised, do a final state check:
729 * 1. The currently focused application must be the same one we are waiting for.
730 * 2. Ensure we still don't have a focused window.
731 */
732void InputDispatcher::processNoFocusedWindowAnrLocked() {
733 // Check if the application that we are waiting for is still focused.
734 std::shared_ptr<InputApplicationHandle> focusedApplication =
735 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
736 if (focusedApplication == nullptr ||
737 focusedApplication->getApplicationToken() !=
738 mAwaitedFocusedApplication->getApplicationToken()) {
739 // Unexpected because we should have reset the ANR timer when focused application changed
740 ALOGE("Waited for a focused window, but focused application has already changed to %s",
741 focusedApplication->getName().c_str());
742 return; // The focused application has changed.
743 }
744
chaviw98318de2021-05-19 16:45:23 -0500745 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500746 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
747 if (focusedWindowHandle != nullptr) {
748 return; // We now have a focused window. No need for ANR.
749 }
750 onAnrLocked(mAwaitedFocusedApplication);
751}
752
753/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700754 * Check if any of the connections' wait queues have events that are too old.
755 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
756 * Return the time at which we should wake up next.
757 */
758nsecs_t InputDispatcher::processAnrsLocked() {
759 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700760 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700761 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
762 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
763 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500764 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700765 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500766 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700767 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700768 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500769 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700770 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
771 }
772 }
773
774 // Check if any connection ANRs are due
775 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
776 if (currentTime < nextAnrCheck) { // most likely scenario
777 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
778 }
779
780 // If we reached here, we have an unresponsive connection.
781 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
782 if (connection == nullptr) {
783 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
784 return nextAnrCheck;
785 }
786 connection->responsive = false;
787 // Stop waking up for this unresponsive connection
788 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000789 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700790 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700791}
792
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800793std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
794 const sp<Connection>& connection) {
795 if (connection->monitor) {
796 return mMonitorDispatchingTimeout;
797 }
798 const sp<WindowInfoHandle> window =
799 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700800 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500801 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700802 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500803 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700804}
805
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
807 nsecs_t currentTime = now();
808
Jeff Browndc5992e2014-04-11 01:27:26 -0700809 // Reset the key repeat timer whenever normal dispatch is suspended while the
810 // device is in a non-interactive state. This is to ensure that we abort a key
811 // repeat if the device is just coming out of sleep.
812 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 resetKeyRepeatLocked();
814 }
815
816 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
817 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100818 if (DEBUG_FOCUS) {
819 ALOGD("Dispatch frozen. Waiting some more.");
820 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821 return;
822 }
823
824 // Optimize latency of app switches.
825 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
826 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
827 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
828 if (mAppSwitchDueTime < *nextWakeupTime) {
829 *nextWakeupTime = mAppSwitchDueTime;
830 }
831
832 // Ready to start a new event.
833 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700834 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700835 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800836 if (isAppSwitchDue) {
837 // The inbound queue is empty so the app switch key we were waiting
838 // for will never arrive. Stop waiting for it.
839 resetPendingAppSwitchLocked(false);
840 isAppSwitchDue = false;
841 }
842
843 // Synthesize a key repeat if appropriate.
844 if (mKeyRepeatState.lastKeyEntry) {
845 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
846 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
847 } else {
848 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
849 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
850 }
851 }
852 }
853
854 // Nothing to do if there is no pending event.
855 if (!mPendingEvent) {
856 return;
857 }
858 } else {
859 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700860 mPendingEvent = mInboundQueue.front();
861 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 traceInboundQueueLengthLocked();
863 }
864
865 // Poke user activity for this event.
866 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700867 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869 }
870
871 // Now we have an event to dispatch.
872 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700873 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700875 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800876 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700877 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700879 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 }
881
882 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700883 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884 }
885
886 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700887 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700888 const ConfigurationChangedEntry& typedEntry =
889 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700890 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700891 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700892 break;
893 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700895 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700896 const DeviceResetEntry& typedEntry =
897 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700898 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700899 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700900 break;
901 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100903 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700904 std::shared_ptr<FocusEntry> typedEntry =
905 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100906 dispatchFocusLocked(currentTime, typedEntry);
907 done = true;
908 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
909 break;
910 }
911
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700912 case EventEntry::Type::TOUCH_MODE_CHANGED: {
913 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
914 dispatchTouchModeChangeLocked(currentTime, typedEntry);
915 done = true;
916 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
917 break;
918 }
919
Prabir Pradhan99987712020-11-10 18:43:05 -0800920 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
921 const auto typedEntry =
922 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
923 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
924 done = true;
925 break;
926 }
927
arthurhungb89ccb02020-12-30 16:19:01 +0800928 case EventEntry::Type::DRAG: {
929 std::shared_ptr<DragEntry> typedEntry =
930 std::static_pointer_cast<DragEntry>(mPendingEvent);
931 dispatchDragLocked(currentTime, typedEntry);
932 done = true;
933 break;
934 }
935
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700936 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700937 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700938 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700939 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700940 resetPendingAppSwitchLocked(true);
941 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700942 } else if (dropReason == DropReason::NOT_DROPPED) {
943 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700944 }
945 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700946 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700947 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700948 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700949 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
950 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700951 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700952 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700953 break;
954 }
955
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700956 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700957 std::shared_ptr<MotionEntry> motionEntry =
958 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700959 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
960 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700962 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700963 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700964 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700965 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
966 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700967 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700968 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700969 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970 }
Chris Yef59a2f42020-10-16 12:55:26 -0700971
972 case EventEntry::Type::SENSOR: {
973 std::shared_ptr<SensorEntry> sensorEntry =
974 std::static_pointer_cast<SensorEntry>(mPendingEvent);
975 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
976 dropReason = DropReason::APP_SWITCH;
977 }
978 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
979 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
980 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
981 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
982 dropReason = DropReason::STALE;
983 }
984 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
985 done = true;
986 break;
987 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988 }
989
990 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700991 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700992 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993 }
Michael Wright3a981722015-06-10 15:26:13 +0100994 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800995
996 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -0700997 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998 }
999}
1000
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001001bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1002 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1003}
1004
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001005/**
1006 * Return true if the events preceding this incoming motion event should be dropped
1007 * Return false otherwise (the default behaviour)
1008 */
1009bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001010 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001011 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001012
1013 // Optimize case where the current application is unresponsive and the user
1014 // decides to touch a window in a different application.
1015 // If the application takes too long to catch up then we drop all events preceding
1016 // the touch into the other window.
1017 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001018 const int32_t displayId = motionEntry.displayId;
1019 const auto [x, y] = resolveTouchedPosition(motionEntry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07001020 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001021
chaviw98318de2021-05-19 16:45:23 -05001022 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -07001023 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001024 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001025 touchedWindowHandle->getApplicationToken() !=
1026 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001027 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001028 ALOGI("Pruning input queue because user touched a different application while waiting "
1029 "for %s",
1030 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001031 return true;
1032 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001033
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001034 // Alternatively, maybe there's a spy window that could handle this event.
1035 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1036 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1037 for (const auto& windowHandle : touchedSpies) {
1038 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001039 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001040 // This spy window could take more input. Drop all events preceding this
1041 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001042 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001043 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001044 mAwaitedFocusedApplication->getName().c_str());
1045 return true;
1046 }
1047 }
1048 }
1049
1050 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1051 // yet been processed by some connections, the dispatcher will wait for these motion
1052 // events to be processed before dispatching the key event. This is because these motion events
1053 // may cause a new window to be launched, which the user might expect to receive focus.
1054 // To prevent waiting forever for such events, just send the key to the currently focused window
1055 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1056 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1057 "just send the pending key event to the focused window.");
1058 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001059 }
1060 return false;
1061}
1062
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001063bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001064 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001065 mInboundQueue.push_back(std::move(newEntry));
1066 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067 traceInboundQueueLengthLocked();
1068
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001069 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001070 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001071 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1072 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001073 // Optimize app switch latency.
1074 // If the application takes too long to catch up then we drop all events preceding
1075 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001076 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001077 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001078 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001079 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001080 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001081 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001082 if (DEBUG_APP_SWITCH) {
1083 ALOGD("App switch is pending!");
1084 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001085 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001086 mAppSwitchSawKeyDown = false;
1087 needWake = true;
1088 }
1089 }
1090 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001091
1092 // If a new up event comes in, and the pending event with same key code has been asked
1093 // to try again later because of the policy. We have to reset the intercept key wake up
1094 // time for it may have been handled in the policy and could be dropped.
1095 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1096 mPendingEvent->type == EventEntry::Type::KEY) {
1097 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1098 if (pendingKey.keyCode == keyEntry.keyCode &&
1099 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001100 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1101 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001102 pendingKey.interceptKeyWakeupTime = 0;
1103 needWake = true;
1104 }
1105 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001106 break;
1107 }
1108
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001109 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001110 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1111 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001112 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1113 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001114 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001115 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001116 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001118 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001119 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1120 break;
1121 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001122 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001123 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001124 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001125 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001126 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1127 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001128 // nothing to do
1129 break;
1130 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131 }
1132
1133 return needWake;
1134}
1135
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001136void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001137 // Do not store sensor event in recent queue to avoid flooding the queue.
1138 if (entry->type != EventEntry::Type::SENSOR) {
1139 mRecentQueue.push_back(entry);
1140 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001141 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001142 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001143 }
1144}
1145
chaviw98318de2021-05-19 16:45:23 -05001146sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1147 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001148 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001149 bool addOutsideTargets,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07001150 bool ignoreDragWindow) const {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001151 if (addOutsideTargets && touchState == nullptr) {
1152 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001153 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 // Traverse windows from front to back to find touched window.
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)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001163 return windowHandle;
1164 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001165
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001166 if (addOutsideTargets &&
1167 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001168 touchState->addOrUpdateWindow(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001169 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170 }
1171 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001172 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 Vishniakou6278ca22022-10-25 11:19:19 -07001760 std::vector<TouchedWindow> touchedWindows =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001761 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001762 /*byref*/ injectionResult);
1763 for (const TouchedWindow& touchedWindow : touchedWindows) {
1764 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED,
1765 "Shouldn't be adding window if the injection didn't succeed.");
1766 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1767 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
1768 inputTargets);
1769 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 } else {
1771 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001772 sp<WindowInfoHandle> focusedWindow =
1773 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1774 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1775 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1776 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001777 InputTarget::Flags::FOREGROUND |
1778 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001779 BitSet32(0), getDownTime(*entry), inputTargets);
1780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001782 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783 return false;
1784 }
1785
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001786 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001787 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001788 return true;
1789 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001790 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001791 CancelationOptions::Mode mode(
1792 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1793 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001794 CancelationOptions options(mode, "input event injection failed");
1795 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 return true;
1797 }
1798
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001799 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001800 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001801
1802 // Dispatch the motion.
1803 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001804 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001805 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806 synthesizeCancelationEventsForAllConnectionsLocked(options);
1807 }
1808 dispatchEventLocked(currentTime, entry, inputTargets);
1809 return true;
1810}
1811
chaviw98318de2021-05-19 16:45:23 -05001812void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001813 bool isExiting, const int32_t rawX,
1814 const int32_t rawY) {
1815 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001816 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001817 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1818 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001819
1820 enqueueInboundEventLocked(std::move(dragEntry));
1821}
1822
1823void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1824 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1825 if (channel == nullptr) {
1826 return; // Window has gone away
1827 }
1828 InputTarget target;
1829 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001830 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001831 entry->dispatchInProgress = true;
1832 dispatchEventLocked(currentTime, entry, {target});
1833}
1834
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001835void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001836 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001837 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001838 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001839 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001840 "metaState=0x%x, buttonState=0x%x,"
1841 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001842 prefix, entry.eventTime, entry.deviceId,
1843 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1844 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1845 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1846 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001848 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1849 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1850 "x=%f, y=%f, pressure=%f, size=%f, "
1851 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1852 "orientation=%f",
1853 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1854 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1855 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1856 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1857 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1858 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1859 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1860 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1861 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1862 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1863 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865}
1866
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001867void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1868 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001869 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001870 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001871 if (DEBUG_DISPATCH_CYCLE) {
1872 ALOGD("dispatchEventToCurrentInputTargets");
1873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001875 updateInteractionTokensLocked(*eventEntry, inputTargets);
1876
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1878
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001879 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001880
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001881 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001882 sp<Connection> connection =
1883 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001884 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001885 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001886 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001887 if (DEBUG_FOCUS) {
1888 ALOGD("Dropping event delivery to target with channel '%s' because it "
1889 "is no longer registered with the input dispatcher.",
1890 inputTarget.inputChannel->getName().c_str());
1891 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892 }
1893 }
1894}
1895
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001896void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1897 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1898 // If the policy decides to close the app, we will get a channel removal event via
1899 // unregisterInputChannel, and will clean up the connection that way. We are already not
1900 // sending new pointers to the connection when it blocked, but focused events will continue to
1901 // pile up.
1902 ALOGW("Canceling events for %s because it is unresponsive",
1903 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001904 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001905 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001906 "application not responding");
1907 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908 }
1909}
1910
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001911void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001912 if (DEBUG_FOCUS) {
1913 ALOGD("Resetting ANR timeouts.");
1914 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915
1916 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001917 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001918 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919}
1920
Tiger Huang721e26f2018-07-24 22:26:19 +08001921/**
1922 * Get the display id that the given event should go to. If this event specifies a valid display id,
1923 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1924 * Focused display is the display that the user most recently interacted with.
1925 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001926int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001927 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001928 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001929 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001930 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1931 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001932 break;
1933 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001934 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001935 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1936 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001937 break;
1938 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001939 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001940 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001941 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001942 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001943 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001944 case EventEntry::Type::SENSOR:
1945 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001946 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001947 return ADISPLAY_ID_NONE;
1948 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001949 }
1950 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1951}
1952
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001953bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1954 const char* focusedWindowName) {
1955 if (mAnrTracker.empty()) {
1956 // already processed all events that we waited for
1957 mKeyIsWaitingForEventsTimeout = std::nullopt;
1958 return false;
1959 }
1960
1961 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1962 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001963 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001964 mKeyIsWaitingForEventsTimeout = currentTime +
1965 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1966 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001967 return true;
1968 }
1969
1970 // We still have pending events, and already started the timer
1971 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1972 return true; // Still waiting
1973 }
1974
1975 // Waited too long, and some connection still hasn't processed all motions
1976 // Just send the key to the focused window
1977 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1978 focusedWindowName);
1979 mKeyIsWaitingForEventsTimeout = std::nullopt;
1980 return false;
1981}
1982
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001983sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
1984 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
1985 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001986 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001987 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988
Tiger Huang721e26f2018-07-24 22:26:19 +08001989 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001990 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001991 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001992 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1993
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 // If there is no currently focused window and no focused application
1995 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001996 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1997 ALOGI("Dropping %s event because there is no focused window or focused application in "
1998 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001999 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002000 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001 }
2002
Vishnu Nair062a8672021-09-03 16:07:44 -07002003 // Drop key events if requested by input feature
2004 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002005 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002006 }
2007
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002008 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2009 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2010 // start interacting with another application via touch (app switch). This code can be removed
2011 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2012 // an app is expected to have a focused window.
2013 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2014 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2015 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002016 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2017 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2018 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002019 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002020 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002021 ALOGW("Waiting because no window has focus but %s may eventually add a "
2022 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002023 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002024 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002025 outInjectionResult = InputEventInjectionResult::PENDING;
2026 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002027 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2028 // Already raised ANR. Drop the event
2029 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002030 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002031 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002032 } else {
2033 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002034 outInjectionResult = InputEventInjectionResult::PENDING;
2035 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002036 }
2037 }
2038
2039 // we have a valid, non-null focused window
2040 resetNoFocusedWindowTimeoutLocked();
2041
Prabir Pradhan5735a322022-04-11 17:23:34 +00002042 // Verify targeted injection.
2043 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2044 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002045 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2046 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047 }
2048
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002049 if (focusedWindowHandle->getInfo()->inputConfig.test(
2050 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002051 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002052 outInjectionResult = InputEventInjectionResult::PENDING;
2053 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002054 }
2055
2056 // If the event is a key event, then we must wait for all previous events to
2057 // complete before delivering it because previous events may have the
2058 // side-effect of transferring focus to a different window and we want to
2059 // ensure that the following keys are sent to the new window.
2060 //
2061 // Suppose the user touches a button in a window then immediately presses "A".
2062 // If the button causes a pop-up window to appear then we want to ensure that
2063 // the "A" key is delivered to the new pop-up window. This is because users
2064 // often anticipate pending UI changes when typing on a keyboard.
2065 // To obtain this behavior, we must serialize key events with respect to all
2066 // prior input events.
2067 if (entry.type == EventEntry::Type::KEY) {
2068 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2069 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002070 outInjectionResult = InputEventInjectionResult::PENDING;
2071 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002072 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073 }
2074
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002075 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2076 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077}
2078
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002079/**
2080 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2081 * that are currently unresponsive.
2082 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002083std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2084 const std::vector<Monitor>& monitors) const {
2085 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002086 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002087 [this](const Monitor& monitor) REQUIRES(mLock) {
2088 sp<Connection> connection =
2089 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002090 if (connection == nullptr) {
2091 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002092 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002093 return false;
2094 }
2095 if (!connection->responsive) {
2096 ALOGW("Unresponsive monitor %s will not get the new gesture",
2097 connection->inputChannel->getName().c_str());
2098 return false;
2099 }
2100 return true;
2101 });
2102 return responsiveMonitors;
2103}
2104
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002105/**
2106 * In general, touch should be always split between windows. Some exceptions:
2107 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2108 * from the same device, *and* the window that's receiving the current pointer does not support
2109 * split touch.
2110 * 2. Don't split mouse events
2111 */
2112bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2113 const MotionEntry& entry) const {
2114 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2115 // We should never split mouse events
2116 return false;
2117 }
2118 for (const TouchedWindow& touchedWindow : touchState.windows) {
2119 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2120 // Spy windows should not affect whether or not touch is split.
2121 continue;
2122 }
2123 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2124 continue;
2125 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002126 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2127 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2128 // Wallpaper window should not affect whether or not touch is split
2129 continue;
2130 }
2131
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002132 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2133 // being sent there. For now, use deviceId from touch state.
2134 if (entry.deviceId == touchState.deviceId && !touchedWindow.pointerIds.isEmpty()) {
2135 return false;
2136 }
2137 }
2138 return true;
2139}
2140
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002141std::vector<TouchedWindow> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002142 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2143 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002144 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002146 std::vector<TouchedWindow> touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147 // For security reasons, we defer updating the touch state until we are sure that
2148 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002149 const int32_t displayId = entry.displayId;
2150 const int32_t action = entry.action;
2151 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152
2153 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002154 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002156 // Copy current touch state into tempTouchState.
2157 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2158 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002159 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002160 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002161 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2162 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002163 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002164 }
2165
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002166 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002167 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002168 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002169
2170 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2171 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2172 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2173 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2174 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002175 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002176
Michael Wrightd02c5b62014-02-10 15:10:22 -08002177 if (newGesture) {
2178 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002179 if (switchedDevice && tempTouchState.isDown() && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002180 ALOGI("Dropping event because a pointer for a different device is already down "
2181 "in display %" PRId32,
2182 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002183 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002184 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakouf0ab2c82022-10-25 18:15:28 -07002185 return touchedWindows; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002187 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002188 tempTouchState.deviceId = entry.deviceId;
2189 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002191 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002192 ALOGI("Dropping move event because a pointer for a different device is already active "
2193 "in display %" PRId32,
2194 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002195 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002196 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakouf0ab2c82022-10-25 18:15:28 -07002197 return touchedWindows; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198 }
2199
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002200 if (isHoverAction) {
2201 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2202 // all of the existing hovering pointers and recompute.
2203 tempTouchState.clearHoveringPointers();
2204 }
2205
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2207 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002208 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002209 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002210 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002211 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002212 sp<WindowInfoHandle> newTouchedWindowHandle =
2213 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus,
2214 isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002215
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002217 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002218 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2219 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002221 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002222 }
2223
Prabir Pradhan5735a322022-04-11 17:23:34 +00002224 // Verify targeted injection.
2225 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2226 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002227 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002228 newTouchedWindowHandle = nullptr;
2229 goto Failed;
2230 }
2231
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002232 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002233 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002234 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2235 // New window supports splitting, but we should never split mouse events.
2236 isSplit = !isFromMouse;
2237 } else if (isSplit) {
2238 // New window does not support splitting but we have already split events.
2239 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002240 newTouchedWindowHandle = nullptr;
2241 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002242 } else {
2243 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002244 // be delivered to a new window which supports split touch. Pointers from a mouse device
2245 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002246 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002247 }
2248
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002249 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002250 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002251 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002252 // Process the foreground window first so that it is the first to receive the event.
2253 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002254 }
2255
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002256 if (newTouchedWindows.empty()) {
2257 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2258 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002259 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002260 goto Failed;
2261 }
2262
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002263 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002264 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002265 continue;
2266 }
2267
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002268 if (isHoverAction) {
2269 const int32_t pointerId = entry.pointerProperties[0].id;
2270 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2271 // Pointer left. Remove it
2272 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2273 } else {
2274 // The "windowHandle" is the target of this hovering pointer.
2275 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId,
2276 pointerId);
2277 }
2278 }
2279
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002280 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002281 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002282
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002283 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2284 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002285 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002286 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002287
2288 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002289 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002290 }
2291 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002292 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002293 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002294 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002295 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002296
2297 // Update the temporary touch state.
2298 BitSet32 pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002299 if (!isHoverAction) {
2300 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2301 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002302
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002303 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
2304 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002305
2306 // If this is the pointer going down and the touched window has a wallpaper
2307 // then also add the touched wallpaper windows so they are locked in for the duration
2308 // of the touch gesture.
2309 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2310 // engine only supports touch events. We would need to add a mechanism similar
2311 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2312 if (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2313 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2314 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2315 windowHandle->getInfo()->inputConfig.test(
2316 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2317 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2318 if (wallpaper != nullptr) {
2319 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2320 InputTarget::Flags::WINDOW_IS_OBSCURED |
2321 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2322 InputTarget::Flags::DISPATCH_AS_IS;
2323 if (isSplit) {
2324 wallpaperFlags |= InputTarget::Flags::SPLIT;
2325 }
2326 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2327 entry.eventTime);
2328 }
2329 }
2330 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002332
2333 // If any existing window is pilfering pointers from newly added window, remove it
2334 BitSet32 canceledPointers = BitSet32(0);
2335 for (const TouchedWindow& window : tempTouchState.windows) {
2336 if (window.isPilferingPointers) {
2337 canceledPointers |= window.pointerIds;
2338 }
2339 }
2340 tempTouchState.cancelPointersForNonPilferingWindows(canceledPointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341 } else {
2342 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2343
2344 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002345 if (!tempTouchState.isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002346 ALOGD_IF(DEBUG_FOCUS,
2347 "Dropping event because the pointer is not down or we previously "
2348 "dropped the pointer down event in display %" PRId32 ": %s",
2349 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002350 outInjectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351 goto Failed;
2352 }
2353
arthurhung6d4bed92021-03-17 11:59:33 +08002354 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002355
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002357 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002358 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002359 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07002360 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002361 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002362 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002363 sp<WindowInfoHandle> newTouchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002364 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002365
Prabir Pradhan5735a322022-04-11 17:23:34 +00002366 // Verify targeted injection.
2367 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2368 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002369 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002370 newTouchedWindowHandle = nullptr;
2371 goto Failed;
2372 }
2373
Vishnu Nair062a8672021-09-03 16:07:44 -07002374 // Drop touch events if requested by input feature
2375 if (newTouchedWindowHandle != nullptr &&
2376 shouldDropInput(entry, newTouchedWindowHandle)) {
2377 newTouchedWindowHandle = nullptr;
2378 }
2379
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002380 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2381 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002382 if (DEBUG_FOCUS) {
2383 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2384 oldTouchedWindowHandle->getName().c_str(),
2385 newTouchedWindowHandle->getName().c_str(), displayId);
2386 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002387 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002388 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002389 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002390 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002391
2392 // Make a slippery entrance into the new window.
2393 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002394 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395 }
2396
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002397 ftl::Flags<InputTarget::Flags> targetFlags =
2398 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002399 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002400 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002401 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002402 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002403 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002404 }
2405 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002406 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002407 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002408 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002409 }
2410
2411 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002412 pointerIds.markBit(entry.pointerProperties[0].id);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002413 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2414 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002415
2416 // Check if the wallpaper window should deliver the corresponding event.
2417 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
2418 tempTouchState, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419 }
2420 }
Arthur Hung96483742022-11-15 03:30:48 +00002421
2422 // Update the pointerIds for non-splittable when it received pointer down.
2423 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2424 // If no split, we suppose all touched windows should receive pointer down.
2425 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2426 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2427 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2428 // Ignore drag window for it should just track one pointer.
2429 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2430 continue;
2431 }
2432 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2433 }
2434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002435 }
2436
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002437 // Update dispatching for hover enter and exit.
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002438 {
2439 std::vector<TouchedWindow> hoveringWindows =
2440 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2441 touchedWindows.insert(touchedWindows.end(), hoveringWindows.begin(), hoveringWindows.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442 }
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002443 // Ensure that we have at least one foreground window or at least one window that cannot be a
2444 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2445 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2446 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002447 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2448 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002449 return !canReceiveForegroundTouches(
2450 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002451 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002452 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002453 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2454 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002455 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002456 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457 }
2458
Prabir Pradhan5735a322022-04-11 17:23:34 +00002459 // Ensure that all touched windows are valid for injection.
2460 if (entry.injectionState != nullptr) {
2461 std::string errs;
2462 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002463 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002464 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2465 // dispatched to any uid, since the coords will be zeroed out later.
2466 continue;
2467 }
2468 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2469 if (err) errs += "\n - " + *err;
2470 }
2471 if (!errs.empty()) {
2472 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2473 "%d:%s",
2474 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002475 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002476 goto Failed;
2477 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002478 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002479
Michael Wrightd02c5b62014-02-10 15:10:22 -08002480 // Check whether windows listening for outside touches are owned by the same UID. If it is
2481 // set the policy flag that we will not reveal coordinate information to this window.
2482 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002483 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002484 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002485 if (foregroundWindowHandle) {
2486 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002487 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002488 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
chaviw98318de2021-05-19 16:45:23 -05002489 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2490 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2491 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002492 InputTarget::Flags::ZERO_COORDS,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002493 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002494 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002495 }
2496 }
2497 }
2498 }
2499
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002500 // Success! Output targets for everything except hovers.
2501 if (!isHoverAction) {
2502 touchedWindows.insert(touchedWindows.end(), tempTouchState.windows.begin(),
2503 tempTouchState.windows.end());
2504 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002505
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002506 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002507 // Drop the outside or hover touch windows since we will not care about them
2508 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002509 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510
2511Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002513 if (switchedDevice) {
2514 if (DEBUG_FOCUS) {
2515 ALOGD("Conflicting pointer actions: Switched to a different device.");
2516 }
2517 *outConflictingPointerActions = true;
2518 }
2519
2520 if (isHoverAction) {
2521 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002522 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002523 ALOGD_IF(DEBUG_FOCUS,
2524 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002525 *outConflictingPointerActions = true;
2526 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002527 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2528 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2529 tempTouchState.deviceId = entry.deviceId;
2530 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002531 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002532 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2533 // Pointer went up.
2534 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
2535 tempTouchState.clearWindowsWithoutPointers();
2536 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002537 // All pointers up or canceled.
2538 tempTouchState.reset();
2539 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2540 // First pointer went down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002541 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002542 ALOGD("Conflicting pointer actions: Down received while already down.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002543 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002544 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002545 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2546 // One pointer went up.
2547 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2548 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002550 for (size_t i = 0; i < tempTouchState.windows.size();) {
2551 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2552 touchedWindow.pointerIds.clearBit(pointerId);
2553 if (touchedWindow.pointerIds.isEmpty()) {
2554 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2555 continue;
2556 }
2557 i += 1;
2558 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559 }
2560
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002561 // Save changes unless the action was scroll in which case the temporary touch
2562 // state was only valid for this one action.
2563 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002564 if (displayId >= 0) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002565 mTouchStatesByDisplay[displayId] = tempTouchState;
2566 } else {
2567 mTouchStatesByDisplay.erase(displayId);
2568 }
2569 }
2570
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002571 if (tempTouchState.windows.empty()) {
2572 mTouchStatesByDisplay.erase(displayId);
2573 }
2574
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002575 return touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002576}
2577
arthurhung6d4bed92021-03-17 11:59:33 +08002578void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002579 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2580 // have an explicit reason to support it.
2581 constexpr bool isStylus = false;
2582
chaviw98318de2021-05-19 16:45:23 -05002583 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002584 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002585 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002586 if (dropWindow) {
2587 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002588 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002589 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002590 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002591 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002592 }
2593 mDragState.reset();
2594}
2595
2596void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002597 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002598 return;
2599 }
2600
arthurhung6d4bed92021-03-17 11:59:33 +08002601 if (!mDragState->isStartDrag) {
2602 mDragState->isStartDrag = true;
2603 mDragState->isStylusButtonDownAtStart =
2604 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2605 }
2606
Arthur Hung54745652022-04-20 07:17:41 +00002607 // Find the pointer index by id.
2608 int32_t pointerIndex = 0;
2609 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2610 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2611 if (pointerProperties.id == mDragState->pointerId) {
2612 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002613 }
Arthur Hung54745652022-04-20 07:17:41 +00002614 }
arthurhung6d4bed92021-03-17 11:59:33 +08002615
Arthur Hung54745652022-04-20 07:17:41 +00002616 if (uint32_t(pointerIndex) == entry.pointerCount) {
2617 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002618 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002619 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002620 return;
2621 }
2622
2623 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2624 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2625 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2626
2627 switch (maskedAction) {
2628 case AMOTION_EVENT_ACTION_MOVE: {
2629 // Handle the special case : stylus button no longer pressed.
2630 bool isStylusButtonDown =
2631 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2632 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2633 finishDragAndDrop(entry.displayId, x, y);
2634 return;
2635 }
2636
2637 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2638 // until we have an explicit reason to support it.
2639 constexpr bool isStylus = false;
2640
2641 const sp<WindowInfoHandle> hoverWindowHandle =
2642 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2643 isStylus, false /*addOutsideTargets*/,
2644 true /*ignoreDragWindow*/);
2645 // enqueue drag exit if needed.
2646 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2647 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2648 if (mDragState->dragHoverWindowHandle != nullptr) {
2649 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2650 y);
2651 }
2652 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2653 }
2654 // enqueue drag location if needed.
2655 if (hoverWindowHandle != nullptr) {
2656 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2657 }
2658 break;
2659 }
2660
2661 case AMOTION_EVENT_ACTION_POINTER_UP:
2662 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2663 break;
2664 }
2665 // The drag pointer is up.
2666 [[fallthrough]];
2667 case AMOTION_EVENT_ACTION_UP:
2668 finishDragAndDrop(entry.displayId, x, y);
2669 break;
2670 case AMOTION_EVENT_ACTION_CANCEL: {
2671 ALOGD("Receiving cancel when drag and drop.");
2672 sendDropWindowCommandLocked(nullptr, 0, 0);
2673 mDragState.reset();
2674 break;
2675 }
arthurhungb89ccb02020-12-30 16:19:01 +08002676 }
2677}
2678
chaviw98318de2021-05-19 16:45:23 -05002679void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002680 ftl::Flags<InputTarget::Flags> targetFlags,
2681 BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002682 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002683 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002684 std::vector<InputTarget>::iterator it =
2685 std::find_if(inputTargets.begin(), inputTargets.end(),
2686 [&windowHandle](const InputTarget& inputTarget) {
2687 return inputTarget.inputChannel->getConnectionToken() ==
2688 windowHandle->getToken();
2689 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002690
chaviw98318de2021-05-19 16:45:23 -05002691 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002692
2693 if (it == inputTargets.end()) {
2694 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002695 std::shared_ptr<InputChannel> inputChannel =
2696 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002697 if (inputChannel == nullptr) {
2698 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2699 return;
2700 }
2701 inputTarget.inputChannel = inputChannel;
2702 inputTarget.flags = targetFlags;
2703 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002704 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002705 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2706 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002707 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002708 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002709 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002710 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002711 inputTargets.push_back(inputTarget);
2712 it = inputTargets.end() - 1;
2713 }
2714
2715 ALOG_ASSERT(it->flags == targetFlags);
2716 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2717
chaviw1ff3d1e2020-07-01 15:53:47 -07002718 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002719}
2720
Michael Wright3dd60e22019-03-27 22:06:44 +00002721void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002722 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002723 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2724 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002725
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002726 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2727 InputTarget target;
2728 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002729 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002730 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2731 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002732 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2733 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002734 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002735 target.setDefaultPointerTransform(target.displayTransform);
2736 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737 }
2738}
2739
Robert Carrc9bf1d32020-04-13 17:21:08 -07002740/**
2741 * Indicate whether one window handle should be considered as obscuring
2742 * another window handle. We only check a few preconditions. Actually
2743 * checking the bounds is left to the caller.
2744 */
chaviw98318de2021-05-19 16:45:23 -05002745static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2746 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002747 // Compare by token so cloned layers aren't counted
2748 if (haveSameToken(windowHandle, otherHandle)) {
2749 return false;
2750 }
2751 auto info = windowHandle->getInfo();
2752 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002753 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002754 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002755 } else if (otherInfo->alpha == 0 &&
2756 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002757 // Those act as if they were invisible, so we don't need to flag them.
2758 // We do want to potentially flag touchable windows even if they have 0
2759 // opacity, since they can consume touches and alter the effects of the
2760 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002761 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002762 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2763 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002764 } else if (info->ownerUid == otherInfo->ownerUid) {
2765 // If ownerUid is the same we don't generate occlusion events as there
2766 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002767 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002768 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002769 return false;
2770 } else if (otherInfo->displayId != info->displayId) {
2771 return false;
2772 }
2773 return true;
2774}
2775
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002776/**
2777 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2778 * untrusted, one should check:
2779 *
2780 * 1. If result.hasBlockingOcclusion is true.
2781 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2782 * BLOCK_UNTRUSTED.
2783 *
2784 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2785 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2786 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2787 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2788 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2789 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2790 *
2791 * If neither of those is true, then it means the touch can be allowed.
2792 */
2793InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002794 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2795 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002796 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002797 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002798 TouchOcclusionInfo info;
2799 info.hasBlockingOcclusion = false;
2800 info.obscuringOpacity = 0;
2801 info.obscuringUid = -1;
2802 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002803 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002804 if (windowHandle == otherHandle) {
2805 break; // All future windows are below us. Exit early.
2806 }
chaviw98318de2021-05-19 16:45:23 -05002807 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002808 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2809 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002810 if (DEBUG_TOUCH_OCCLUSION) {
2811 info.debugInfo.push_back(
2812 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2813 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002814 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2815 // we perform the checks below to see if the touch can be propagated or not based on the
2816 // window's touch occlusion mode
2817 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2818 info.hasBlockingOcclusion = true;
2819 info.obscuringUid = otherInfo->ownerUid;
2820 info.obscuringPackage = otherInfo->packageName;
2821 break;
2822 }
2823 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2824 uint32_t uid = otherInfo->ownerUid;
2825 float opacity =
2826 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2827 // Given windows A and B:
2828 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2829 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2830 opacityByUid[uid] = opacity;
2831 if (opacity > info.obscuringOpacity) {
2832 info.obscuringOpacity = opacity;
2833 info.obscuringUid = uid;
2834 info.obscuringPackage = otherInfo->packageName;
2835 }
2836 }
2837 }
2838 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002839 if (DEBUG_TOUCH_OCCLUSION) {
2840 info.debugInfo.push_back(
2841 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2842 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002843 return info;
2844}
2845
chaviw98318de2021-05-19 16:45:23 -05002846std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002847 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002848 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2849 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2850 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2851 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002852 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2853 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2854 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2855 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2856 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002857 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002858 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002859}
2860
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002861bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2862 if (occlusionInfo.hasBlockingOcclusion) {
2863 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2864 occlusionInfo.obscuringUid);
2865 return false;
2866 }
2867 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2868 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2869 "%.2f, maximum allowed = %.2f)",
2870 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2871 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2872 return false;
2873 }
2874 return true;
2875}
2876
chaviw98318de2021-05-19 16:45:23 -05002877bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002878 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002879 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002880 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2881 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002882 if (windowHandle == otherHandle) {
2883 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002884 }
chaviw98318de2021-05-19 16:45:23 -05002885 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002886 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002887 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888 return true;
2889 }
2890 }
2891 return false;
2892}
2893
chaviw98318de2021-05-19 16:45:23 -05002894bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002895 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002896 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2897 const WindowInfo* windowInfo = windowHandle->getInfo();
2898 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002899 if (windowHandle == otherHandle) {
2900 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002901 }
chaviw98318de2021-05-19 16:45:23 -05002902 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002903 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002904 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002905 return true;
2906 }
2907 }
2908 return false;
2909}
2910
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002911std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002912 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002913 if (applicationHandle != nullptr) {
2914 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002915 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002916 } else {
2917 return applicationHandle->getName();
2918 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002919 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002920 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002921 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002922 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923 }
2924}
2925
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002926void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002927 if (!isUserActivityEvent(eventEntry)) {
2928 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002929 return;
2930 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002931 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002932 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002933 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002934 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002935 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002936 if (DEBUG_DISPATCH_CYCLE) {
2937 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2938 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002939 return;
2940 }
2941 }
2942
2943 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002944 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002945 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002946 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2947 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002948 return;
2949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002950
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002951 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002952 eventType = USER_ACTIVITY_EVENT_TOUCH;
2953 }
2954 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002955 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002956 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002957 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2958 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002959 return;
2960 }
2961 eventType = USER_ACTIVITY_EVENT_BUTTON;
2962 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002963 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002964 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002965 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002966 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002967 break;
2968 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002969 }
2970
Prabir Pradhancef936d2021-07-21 16:17:52 +00002971 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2972 REQUIRES(mLock) {
2973 scoped_unlock unlock(mLock);
2974 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2975 };
2976 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002977}
2978
2979void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002980 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002981 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002982 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002983 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002984 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002985 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002986 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002987 ATRACE_NAME(message.c_str());
2988 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002989 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002990 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002991 "globalScaleFactor=%f, pointerIds=0x%x %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002992 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002993 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2994 inputTarget.getPointerInfoString().c_str());
2995 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002996
2997 // Skip this event if the connection status is not normal.
2998 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002999 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003000 if (DEBUG_DISPATCH_CYCLE) {
3001 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003002 connection->getInputChannelName().c_str(),
3003 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003005 return;
3006 }
3007
3008 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003009 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003010 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003011 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003012 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003013
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003014 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003015 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003016 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
3017 "Splitting motion events requires a down time to be set for the "
3018 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003019 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003020 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3021 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003022 if (!splitMotionEntry) {
3023 return; // split event was dropped
3024 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003025 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3026 std::string reason = std::string("reason=pointer cancel on split window");
3027 android_log_event_list(LOGTAG_INPUT_CANCEL)
3028 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3029 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003030 if (DEBUG_FOCUS) {
3031 ALOGD("channel '%s' ~ Split motion event.",
3032 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003033 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003034 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003035 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3036 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003037 return;
3038 }
3039 }
3040
3041 // Not splitting. Enqueue dispatch entries for the event as is.
3042 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3043}
3044
3045void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003046 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003047 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003048 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003049 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003050 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003051 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003052 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003053 ATRACE_NAME(message.c_str());
3054 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003055 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3056 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003057
hongzuo liu95785e22022-09-06 02:51:35 +00003058 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003059
3060 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003061 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003062 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003063 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003064 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003065 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003066 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003067 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003068 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003069 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003070 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003071 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003072 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003073
3074 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003075 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003076 startDispatchCycleLocked(currentTime, connection);
3077 }
3078}
3079
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003080void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003081 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003082 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003083 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003084 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003085 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3086 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003087 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003088 ATRACE_NAME(message.c_str());
3089 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003090 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3091 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003092 return;
3093 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003094
3095 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3096 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097
3098 // This is a new event.
3099 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003100 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003101 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003102
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003103 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3104 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003105 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003106 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003107 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003108 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003109 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003110 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003111 dispatchEntry->resolvedAction = keyEntry.action;
3112 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003113
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003114 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3115 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003116 if (DEBUG_DISPATCH_CYCLE) {
3117 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3118 "event",
3119 connection->getInputChannelName().c_str());
3120 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003121 return; // skip the inconsistent event
3122 }
3123 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003124 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003125
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003126 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003127 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003128 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3129 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3130 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3131 static_cast<int32_t>(IdGenerator::Source::OTHER);
3132 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003133 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003134 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003135 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003136 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003137 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003138 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003139 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003140 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003141 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003142 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3143 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003144 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003145 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003146 }
3147 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003148 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3149 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003150 if (DEBUG_DISPATCH_CYCLE) {
3151 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3152 "enter event",
3153 connection->getInputChannelName().c_str());
3154 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003155 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3156 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003157 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3158 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003160 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003161 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003162 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3163 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003164 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003165 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3166 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003167
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003168 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3169 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003170 if (DEBUG_DISPATCH_CYCLE) {
3171 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3172 "event",
3173 connection->getInputChannelName().c_str());
3174 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003175 return; // skip the inconsistent event
3176 }
3177
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003178 dispatchEntry->resolvedEventId =
3179 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3180 ? mIdGenerator.nextId()
3181 : motionEntry.id;
3182 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3183 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3184 ") to MotionEvent(id=0x%" PRIx32 ").",
3185 motionEntry.id, dispatchEntry->resolvedEventId);
3186 ATRACE_NAME(message.c_str());
3187 }
3188
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003189 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3190 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3191 // Skip reporting pointer down outside focus to the policy.
3192 break;
3193 }
3194
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003195 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003196 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003197
3198 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003199 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003200 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003201 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003202 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3203 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003204 break;
3205 }
Chris Yef59a2f42020-10-16 12:55:26 -07003206 case EventEntry::Type::SENSOR: {
3207 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3208 break;
3209 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003210 case EventEntry::Type::CONFIGURATION_CHANGED:
3211 case EventEntry::Type::DEVICE_RESET: {
3212 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003213 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003214 break;
3215 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216 }
3217
3218 // Remember that we are waiting for this dispatch to complete.
3219 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003220 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221 }
3222
3223 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003224 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003225 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003226}
3227
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003228/**
3229 * This function is purely for debugging. It helps us understand where the user interaction
3230 * was taking place. For example, if user is touching launcher, we will see a log that user
3231 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3232 * We will see both launcher and wallpaper in that list.
3233 * Once the interaction with a particular set of connections starts, no new logs will be printed
3234 * until the set of interacted connections changes.
3235 *
3236 * The following items are skipped, to reduce the logspam:
3237 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3238 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3239 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3240 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3241 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003242 */
3243void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3244 const std::vector<InputTarget>& targets) {
3245 // Skip ACTION_UP events, and all events other than keys and motions
3246 if (entry.type == EventEntry::Type::KEY) {
3247 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3248 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3249 return;
3250 }
3251 } else if (entry.type == EventEntry::Type::MOTION) {
3252 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3253 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3254 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3255 return;
3256 }
3257 } else {
3258 return; // Not a key or a motion
3259 }
3260
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003261 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003262 std::vector<sp<Connection>> newConnections;
3263 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003264 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003265 continue; // Skip windows that receive ACTION_OUTSIDE
3266 }
3267
3268 sp<IBinder> token = target.inputChannel->getConnectionToken();
3269 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003270 if (connection == nullptr) {
3271 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003272 }
3273 newConnectionTokens.insert(std::move(token));
3274 newConnections.emplace_back(connection);
3275 }
3276 if (newConnectionTokens == mInteractionConnectionTokens) {
3277 return; // no change
3278 }
3279 mInteractionConnectionTokens = newConnectionTokens;
3280
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003281 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003282 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003283 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003284 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003285 std::string message = "Interaction with: " + targetList;
3286 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003287 message += "<none>";
3288 }
3289 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3290}
3291
chaviwfd6d3512019-03-25 13:23:49 -07003292void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003293 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003294 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003295 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3296 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003297 return;
3298 }
3299
Vishnu Nairc519ff72021-01-21 08:23:08 -08003300 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003301 if (focusedToken == token) {
3302 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003303 return;
3304 }
3305
Prabir Pradhancef936d2021-07-21 16:17:52 +00003306 auto command = [this, token]() REQUIRES(mLock) {
3307 scoped_unlock unlock(mLock);
3308 mPolicy->onPointerDownOutsideFocus(token);
3309 };
3310 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311}
3312
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003313status_t InputDispatcher::publishMotionEvent(Connection& connection,
3314 DispatchEntry& dispatchEntry) const {
3315 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3316 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3317
3318 PointerCoords scaledCoords[MAX_POINTERS];
3319 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3320
3321 // Set the X and Y offset and X and Y scale depending on the input source.
3322 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003323 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003324 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3325 if (globalScaleFactor != 1.0f) {
3326 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3327 scaledCoords[i] = motionEntry.pointerCoords[i];
3328 // Don't apply window scale here since we don't want scale to affect raw
3329 // coordinates. The scale will be sent back to the client and applied
3330 // later when requesting relative coordinates.
3331 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3332 1 /* windowYScale */);
3333 }
3334 usingCoords = scaledCoords;
3335 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003336 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003337 // We don't want the dispatch target to know the coordinates
3338 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3339 scaledCoords[i].clear();
3340 }
3341 usingCoords = scaledCoords;
3342 }
3343
3344 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3345
3346 // Publish the motion event.
3347 return connection.inputPublisher
3348 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3349 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3350 std::move(hmac), dispatchEntry.resolvedAction,
3351 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3352 motionEntry.edgeFlags, motionEntry.metaState,
3353 motionEntry.buttonState, motionEntry.classification,
3354 dispatchEntry.transform, motionEntry.xPrecision,
3355 motionEntry.yPrecision, motionEntry.xCursorPosition,
3356 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3357 motionEntry.downTime, motionEntry.eventTime,
3358 motionEntry.pointerCount, motionEntry.pointerProperties,
3359 usingCoords);
3360}
3361
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003363 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003364 if (ATRACE_ENABLED()) {
3365 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003366 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003367 ATRACE_NAME(message.c_str());
3368 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003369 if (DEBUG_DISPATCH_CYCLE) {
3370 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003372
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003373 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003374 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003376 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003377 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003378
3379 // Publish the event.
3380 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003381 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3382 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003383 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003384 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3385 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003386 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3387 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3388 << connection->getInputChannelName();
3389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003391 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003392 status = connection->inputPublisher
3393 .publishKeyEvent(dispatchEntry->seq,
3394 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3395 keyEntry.source, keyEntry.displayId,
3396 std::move(hmac), dispatchEntry->resolvedAction,
3397 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3398 keyEntry.scanCode, keyEntry.metaState,
3399 keyEntry.repeatCount, keyEntry.downTime,
3400 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003401 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003402 }
3403
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003404 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003405 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3406 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3407 << connection->getInputChannelName();
3408 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003409 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003410 break;
3411 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003412
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003413 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003414 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003415 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003416 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003417 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003418 break;
3419 }
3420
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003421 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3422 const TouchModeEntry& touchModeEntry =
3423 static_cast<const TouchModeEntry&>(eventEntry);
3424 status = connection->inputPublisher
3425 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3426 touchModeEntry.inTouchMode);
3427
3428 break;
3429 }
3430
Prabir Pradhan99987712020-11-10 18:43:05 -08003431 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3432 const auto& captureEntry =
3433 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3434 status = connection->inputPublisher
3435 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003436 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003437 break;
3438 }
3439
arthurhungb89ccb02020-12-30 16:19:01 +08003440 case EventEntry::Type::DRAG: {
3441 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3442 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3443 dragEntry.id, dragEntry.x,
3444 dragEntry.y,
3445 dragEntry.isExiting);
3446 break;
3447 }
3448
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003449 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003450 case EventEntry::Type::DEVICE_RESET:
3451 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003452 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003453 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003454 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003455 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003456 }
3457
3458 // Check the result.
3459 if (status) {
3460 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003461 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003462 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003463 "This is unexpected because the wait queue is empty, so the pipe "
3464 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003465 "event to it, status=%s(%d)",
3466 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3467 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3469 } else {
3470 // Pipe is full and we are waiting for the app to finish process some events
3471 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003472 if (DEBUG_DISPATCH_CYCLE) {
3473 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3474 "waiting for the application to catch up",
3475 connection->getInputChannelName().c_str());
3476 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477 }
3478 } else {
3479 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003480 "status=%s(%d)",
3481 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3482 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3484 }
3485 return;
3486 }
3487
3488 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003489 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3490 connection->outboundQueue.end(),
3491 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003492 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003493 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003494 if (connection->responsive) {
3495 mAnrTracker.insert(dispatchEntry->timeoutTime,
3496 connection->inputChannel->getConnectionToken());
3497 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003498 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499 }
3500}
3501
chaviw09c8d2d2020-08-24 15:48:26 -07003502std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3503 size_t size;
3504 switch (event.type) {
3505 case VerifiedInputEvent::Type::KEY: {
3506 size = sizeof(VerifiedKeyEvent);
3507 break;
3508 }
3509 case VerifiedInputEvent::Type::MOTION: {
3510 size = sizeof(VerifiedMotionEvent);
3511 break;
3512 }
3513 }
3514 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3515 return mHmacKeyManager.sign(start, size);
3516}
3517
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003518const std::array<uint8_t, 32> InputDispatcher::getSignature(
3519 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003520 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3521 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003522 // Only sign events up and down events as the purely move events
3523 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003524 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003525 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003526
3527 VerifiedMotionEvent verifiedEvent =
3528 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3529 verifiedEvent.actionMasked = actionMasked;
3530 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3531 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003532}
3533
3534const std::array<uint8_t, 32> InputDispatcher::getSignature(
3535 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3536 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3537 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3538 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003539 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003540}
3541
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003543 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003544 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003545 if (DEBUG_DISPATCH_CYCLE) {
3546 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3547 connection->getInputChannelName().c_str(), seq, toString(handled));
3548 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003549
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003550 if (connection->status == Connection::Status::BROKEN ||
3551 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003552 return;
3553 }
3554
3555 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003556 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3557 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3558 };
3559 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560}
3561
3562void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003563 const sp<Connection>& connection,
3564 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003565 if (DEBUG_DISPATCH_CYCLE) {
3566 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3567 connection->getInputChannelName().c_str(), toString(notify));
3568 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003569
3570 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003571 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003572 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003573 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003574 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003575
3576 // The connection appears to be unrecoverably broken.
3577 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003578 if (connection->status == Connection::Status::NORMAL) {
3579 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580
3581 if (notify) {
3582 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003583 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3584 connection->getInputChannelName().c_str());
3585
3586 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003587 scoped_unlock unlock(mLock);
3588 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3589 };
3590 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591 }
3592 }
3593}
3594
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003595void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3596 while (!queue.empty()) {
3597 DispatchEntry* dispatchEntry = queue.front();
3598 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003599 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600 }
3601}
3602
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003603void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003605 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606 }
3607 delete dispatchEntry;
3608}
3609
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003610int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3611 std::scoped_lock _l(mLock);
3612 sp<Connection> connection = getConnectionLocked(connectionToken);
3613 if (connection == nullptr) {
3614 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3615 connectionToken.get(), events);
3616 return 0; // remove the callback
3617 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003619 bool notify;
3620 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3621 if (!(events & ALOOPER_EVENT_INPUT)) {
3622 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3623 "events=0x%x",
3624 connection->getInputChannelName().c_str(), events);
3625 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 }
3627
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003628 nsecs_t currentTime = now();
3629 bool gotOne = false;
3630 status_t status = OK;
3631 for (;;) {
3632 Result<InputPublisher::ConsumerResponse> result =
3633 connection->inputPublisher.receiveConsumerResponse();
3634 if (!result.ok()) {
3635 status = result.error().code();
3636 break;
3637 }
3638
3639 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3640 const InputPublisher::Finished& finish =
3641 std::get<InputPublisher::Finished>(*result);
3642 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3643 finish.consumeTime);
3644 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003645 if (shouldReportMetricsForConnection(*connection)) {
3646 const InputPublisher::Timeline& timeline =
3647 std::get<InputPublisher::Timeline>(*result);
3648 mLatencyTracker
3649 .trackGraphicsLatency(timeline.inputEventId,
3650 connection->inputChannel->getConnectionToken(),
3651 std::move(timeline.graphicsTimeline));
3652 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003653 }
3654 gotOne = true;
3655 }
3656 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003657 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003658 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003659 return 1;
3660 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661 }
3662
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003663 notify = status != DEAD_OBJECT || !connection->monitor;
3664 if (notify) {
3665 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3666 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3667 status);
3668 }
3669 } else {
3670 // Monitor channels are never explicitly unregistered.
3671 // We do it automatically when the remote endpoint is closed so don't warn about them.
3672 const bool stillHaveWindowHandle =
3673 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3674 notify = !connection->monitor && stillHaveWindowHandle;
3675 if (notify) {
3676 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3677 connection->getInputChannelName().c_str(), events);
3678 }
3679 }
3680
3681 // Remove the channel.
3682 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3683 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684}
3685
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003686void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003688 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003689 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 }
3691}
3692
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003693void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003694 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003695 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003696 for (const Monitor& monitor : monitors) {
3697 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003698 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003699 }
3700}
3701
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003703 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003704 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003705 if (connection == nullptr) {
3706 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003707 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003708
3709 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710}
3711
3712void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3713 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003714 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715 return;
3716 }
3717
3718 nsecs_t currentTime = now();
3719
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003720 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003721 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003723 if (cancelationEvents.empty()) {
3724 return;
3725 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003726 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3727 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3728 "with reality: %s, mode=%d.",
3729 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3730 options.mode);
3731 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003732
Arthur Hungb3307ee2021-10-14 10:57:37 +00003733 std::string reason = std::string("reason=").append(options.reason);
3734 android_log_event_list(LOGTAG_INPUT_CANCEL)
3735 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3736
Svet Ganov5d3bc372020-01-26 23:11:07 -08003737 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003738 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003739 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3740 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003741 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003742 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003743 target.globalScaleFactor = windowInfo->globalScaleFactor;
3744 }
3745 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003746 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003747
hongzuo liu95785e22022-09-06 02:51:35 +00003748 const bool wasEmpty = connection->outboundQueue.empty();
3749
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003750 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003751 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003752 switch (cancelationEventEntry->type) {
3753 case EventEntry::Type::KEY: {
3754 logOutboundKeyDetails("cancel - ",
3755 static_cast<const KeyEntry&>(*cancelationEventEntry));
3756 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003757 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003758 case EventEntry::Type::MOTION: {
3759 logOutboundMotionDetails("cancel - ",
3760 static_cast<const MotionEntry&>(*cancelationEventEntry));
3761 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003763 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003764 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003765 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3766 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003767 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003768 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003769 break;
3770 }
3771 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003772 case EventEntry::Type::DEVICE_RESET:
3773 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003774 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003775 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003776 break;
3777 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003778 }
3779
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003780 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003781 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003783
hongzuo liu95785e22022-09-06 02:51:35 +00003784 // If the outbound queue was previously empty, start the dispatch cycle going.
3785 if (wasEmpty && !connection->outboundQueue.empty()) {
3786 startDispatchCycleLocked(currentTime, connection);
3787 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788}
3789
Svet Ganov5d3bc372020-01-26 23:11:07 -08003790void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Arthur Hungc539dbb2022-12-08 07:45:36 +00003791 const nsecs_t downTime, const sp<Connection>& connection,
3792 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003793 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003794 return;
3795 }
3796
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003797 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003798 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003799
3800 if (downEvents.empty()) {
3801 return;
3802 }
3803
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003804 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003805 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3806 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003807 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003808
3809 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003810 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003811 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3812 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003813 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003814 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003815 target.globalScaleFactor = windowInfo->globalScaleFactor;
3816 }
3817 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00003818 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003819
hongzuo liu95785e22022-09-06 02:51:35 +00003820 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003821 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003822 switch (downEventEntry->type) {
3823 case EventEntry::Type::MOTION: {
3824 logOutboundMotionDetails("down - ",
3825 static_cast<const MotionEntry&>(*downEventEntry));
3826 break;
3827 }
3828
3829 case EventEntry::Type::KEY:
3830 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003831 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003832 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003833 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003834 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003835 case EventEntry::Type::SENSOR:
3836 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003837 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003838 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003839 break;
3840 }
3841 }
3842
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003843 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003844 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003845 }
3846
hongzuo liu95785e22022-09-06 02:51:35 +00003847 // If the outbound queue was previously empty, start the dispatch cycle going.
3848 if (wasEmpty && !connection->outboundQueue.empty()) {
3849 startDispatchCycleLocked(downTime, connection);
3850 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003851}
3852
Arthur Hungc539dbb2022-12-08 07:45:36 +00003853void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
3854 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
3855 if (windowHandle != nullptr) {
3856 sp<Connection> wallpaperConnection = getConnectionLocked(windowHandle->getToken());
3857 if (wallpaperConnection != nullptr) {
3858 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
3859 }
3860 }
3861}
3862
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003863std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003864 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865 ALOG_ASSERT(pointerIds.value != 0);
3866
3867 uint32_t splitPointerIndexMap[MAX_POINTERS];
3868 PointerProperties splitPointerProperties[MAX_POINTERS];
3869 PointerCoords splitPointerCoords[MAX_POINTERS];
3870
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003871 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872 uint32_t splitPointerCount = 0;
3873
3874 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003875 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003877 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878 uint32_t pointerId = uint32_t(pointerProperties.id);
3879 if (pointerIds.hasBit(pointerId)) {
3880 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3881 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3882 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003883 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884 splitPointerCount += 1;
3885 }
3886 }
3887
3888 if (splitPointerCount != pointerIds.count()) {
3889 // This is bad. We are missing some of the pointers that we expected to deliver.
3890 // Most likely this indicates that we received an ACTION_MOVE events that has
3891 // different pointer ids than we expected based on the previous ACTION_DOWN
3892 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3893 // in this way.
3894 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003895 "we expected there to be %d pointers. This probably means we received "
3896 "a broken sequence of pointer ids from the input device.",
3897 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003898 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899 }
3900
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003901 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003903 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3904 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3906 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003907 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908 uint32_t pointerId = uint32_t(pointerProperties.id);
3909 if (pointerIds.hasBit(pointerId)) {
3910 if (pointerIds.count() == 1) {
3911 // The first/last pointer went down/up.
3912 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003913 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003914 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3915 ? AMOTION_EVENT_ACTION_CANCEL
3916 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 } else {
3918 // A secondary pointer went down/up.
3919 uint32_t splitPointerIndex = 0;
3920 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3921 splitPointerIndex += 1;
3922 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003923 action = maskedAction |
3924 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925 }
3926 } else {
3927 // An unrelated pointer changed.
3928 action = AMOTION_EVENT_ACTION_MOVE;
3929 }
3930 }
3931
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003932 if (action == AMOTION_EVENT_ACTION_DOWN) {
3933 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3934 "Split motion event has mismatching downTime and eventTime for "
3935 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3936 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3937 }
3938
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003939 int32_t newId = mIdGenerator.nextId();
3940 if (ATRACE_ENABLED()) {
3941 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3942 ") to MotionEvent(id=0x%" PRIx32 ").",
3943 originalMotionEntry.id, newId);
3944 ATRACE_NAME(message.c_str());
3945 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003946 std::unique_ptr<MotionEntry> splitMotionEntry =
3947 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3948 originalMotionEntry.deviceId, originalMotionEntry.source,
3949 originalMotionEntry.displayId,
3950 originalMotionEntry.policyFlags, action,
3951 originalMotionEntry.actionButton,
3952 originalMotionEntry.flags, originalMotionEntry.metaState,
3953 originalMotionEntry.buttonState,
3954 originalMotionEntry.classification,
3955 originalMotionEntry.edgeFlags,
3956 originalMotionEntry.xPrecision,
3957 originalMotionEntry.yPrecision,
3958 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003959 originalMotionEntry.yCursorPosition, splitDownTime,
3960 splitPointerCount, splitPointerProperties,
3961 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003963 if (originalMotionEntry.injectionState) {
3964 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965 splitMotionEntry->injectionState->refCount += 1;
3966 }
3967
3968 return splitMotionEntry;
3969}
3970
3971void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003972 if (DEBUG_INBOUND_EVENT_DETAILS) {
3973 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975
Antonio Kantekf16f2832021-09-28 04:39:20 +00003976 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003978 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003979
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003980 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3981 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3982 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983 } // release lock
3984
3985 if (needWake) {
3986 mLooper->wake();
3987 }
3988}
3989
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003990/**
3991 * If one of the meta shortcuts is detected, process them here:
3992 * Meta + Backspace -> generate BACK
3993 * Meta + Enter -> generate HOME
3994 * This will potentially overwrite keyCode and metaState.
3995 */
3996void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003997 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003998 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3999 int32_t newKeyCode = AKEYCODE_UNKNOWN;
4000 if (keyCode == AKEYCODE_DEL) {
4001 newKeyCode = AKEYCODE_BACK;
4002 } else if (keyCode == AKEYCODE_ENTER) {
4003 newKeyCode = AKEYCODE_HOME;
4004 }
4005 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004006 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004007 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004008 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004009 keyCode = newKeyCode;
4010 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4011 }
4012 } else if (action == AKEY_EVENT_ACTION_UP) {
4013 // In order to maintain a consistent stream of up and down events, check to see if the key
4014 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4015 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004016 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004017 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004018 auto replacementIt = mReplacedKeys.find(replacement);
4019 if (replacementIt != mReplacedKeys.end()) {
4020 keyCode = replacementIt->second;
4021 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004022 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4023 }
4024 }
4025}
4026
Michael Wrightd02c5b62014-02-10 15:10:22 -08004027void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004028 if (DEBUG_INBOUND_EVENT_DETAILS) {
4029 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
4030 "policyFlags=0x%x, action=0x%x, "
4031 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
4032 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
4033 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
4034 args->downTime);
4035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004036 if (!validateKeyEvent(args->action)) {
4037 return;
4038 }
4039
4040 uint32_t policyFlags = args->policyFlags;
4041 int32_t flags = args->flags;
4042 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004043 // InputDispatcher tracks and generates key repeats on behalf of
4044 // whatever notifies it, so repeatCount should always be set to 0
4045 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4047 policyFlags |= POLICY_FLAG_VIRTUAL;
4048 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4049 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004050 if (policyFlags & POLICY_FLAG_FUNCTION) {
4051 metaState |= AMETA_FUNCTION_ON;
4052 }
4053
4054 policyFlags |= POLICY_FLAG_TRUSTED;
4055
Michael Wright78f24442014-08-06 15:55:28 -07004056 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004057 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004058
Michael Wrightd02c5b62014-02-10 15:10:22 -08004059 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004060 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08004061 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
4062 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063
Michael Wright2b3c3302018-03-02 17:19:13 +00004064 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004066 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4067 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004068 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004069 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070
Antonio Kantekf16f2832021-09-28 04:39:20 +00004071 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072 { // acquire lock
4073 mLock.lock();
4074
4075 if (shouldSendKeyToInputFilterLocked(args)) {
4076 mLock.unlock();
4077
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004078 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4080 return; // event was consumed by the filter
4081 }
4082
4083 mLock.lock();
4084 }
4085
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004086 std::unique_ptr<KeyEntry> newEntry =
4087 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4088 args->displayId, policyFlags, args->action, flags,
4089 keyCode, args->scanCode, metaState, repeatCount,
4090 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004092 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004093 mLock.unlock();
4094 } // release lock
4095
4096 if (needWake) {
4097 mLooper->wake();
4098 }
4099}
4100
4101bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4102 return mInputFilterEnabled;
4103}
4104
4105void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004106 if (DEBUG_INBOUND_EVENT_DETAILS) {
4107 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4108 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004109 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004110 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4111 "yCursorPosition=%f, downTime=%" PRId64,
4112 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004113 args->policyFlags, MotionEvent::actionToString(args->action).c_str(),
4114 args->actionButton, args->flags, args->metaState, args->buttonState, args->edgeFlags,
4115 args->xPrecision, args->yPrecision, args->xCursorPosition, args->yCursorPosition,
4116 args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004117 for (uint32_t i = 0; i < args->pointerCount; i++) {
4118 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4119 "x=%f, y=%f, pressure=%f, size=%f, "
4120 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4121 "orientation=%f",
4122 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4123 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4124 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4125 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4126 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4127 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4128 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4129 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4130 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4131 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4132 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -08004134 LOG_ALWAYS_FATAL_IF(!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4135 args->pointerProperties),
4136 "Invalid event: %s", args->dump().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137
4138 uint32_t policyFlags = args->policyFlags;
4139 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004140
4141 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004142 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004143 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4144 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004145 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147
Antonio Kantekf16f2832021-09-28 04:39:20 +00004148 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149 { // acquire lock
4150 mLock.lock();
4151
4152 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004153 ui::Transform displayTransform;
4154 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4155 displayTransform = it->second.transform;
4156 }
4157
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 mLock.unlock();
4159
4160 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004161 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4162 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004163 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004164 displayTransform, args->xPrecision, args->yPrecision,
4165 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004166 args->downTime, args->eventTime, args->pointerCount,
4167 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168
4169 policyFlags |= POLICY_FLAG_FILTERED;
4170 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4171 return; // event was consumed by the filter
4172 }
4173
4174 mLock.lock();
4175 }
4176
4177 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004178 std::unique_ptr<MotionEntry> newEntry =
4179 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4180 args->source, args->displayId, policyFlags,
4181 args->action, args->actionButton, args->flags,
4182 args->metaState, args->buttonState,
4183 args->classification, args->edgeFlags,
4184 args->xPrecision, args->yPrecision,
4185 args->xCursorPosition, args->yCursorPosition,
4186 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004187 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004189 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4190 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4191 !mInputFilterEnabled) {
4192 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4193 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4194 }
4195
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004196 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197 mLock.unlock();
4198 } // release lock
4199
4200 if (needWake) {
4201 mLooper->wake();
4202 }
4203}
4204
Chris Yef59a2f42020-10-16 12:55:26 -07004205void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004206 if (DEBUG_INBOUND_EVENT_DETAILS) {
4207 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4208 " sensorType=%s",
4209 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004210 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004211 }
Chris Yef59a2f42020-10-16 12:55:26 -07004212
Antonio Kantekf16f2832021-09-28 04:39:20 +00004213 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004214 { // acquire lock
4215 mLock.lock();
4216
4217 // Just enqueue a new sensor event.
4218 std::unique_ptr<SensorEntry> newEntry =
4219 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4220 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4221 args->sensorType, args->accuracy,
4222 args->accuracyChanged, args->values);
4223
4224 needWake = enqueueInboundEventLocked(std::move(newEntry));
4225 mLock.unlock();
4226 } // release lock
4227
4228 if (needWake) {
4229 mLooper->wake();
4230 }
4231}
4232
Chris Yefb552902021-02-03 17:18:37 -08004233void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004234 if (DEBUG_INBOUND_EVENT_DETAILS) {
4235 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4236 args->deviceId, args->isOn);
4237 }
Chris Yefb552902021-02-03 17:18:37 -08004238 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4239}
4240
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004242 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243}
4244
4245void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004246 if (DEBUG_INBOUND_EVENT_DETAILS) {
4247 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4248 "switchMask=0x%08x",
4249 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4250 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251
4252 uint32_t policyFlags = args->policyFlags;
4253 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004254 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255}
4256
4257void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004258 if (DEBUG_INBOUND_EVENT_DETAILS) {
4259 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4260 args->deviceId);
4261 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262
Antonio Kantekf16f2832021-09-28 04:39:20 +00004263 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004265 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004267 std::unique_ptr<DeviceResetEntry> newEntry =
4268 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4269 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 } // release lock
4271
4272 if (needWake) {
4273 mLooper->wake();
4274 }
4275}
4276
Prabir Pradhan7e186182020-11-10 13:56:45 -08004277void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004278 if (DEBUG_INBOUND_EVENT_DETAILS) {
4279 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004280 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004281 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004282
Antonio Kantekf16f2832021-09-28 04:39:20 +00004283 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004284 { // acquire lock
4285 std::scoped_lock _l(mLock);
4286 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004287 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004288 needWake = enqueueInboundEventLocked(std::move(entry));
4289 } // release lock
4290
4291 if (needWake) {
4292 mLooper->wake();
4293 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004294}
4295
Prabir Pradhan5735a322022-04-11 17:23:34 +00004296InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4297 std::optional<int32_t> targetUid,
4298 InputEventInjectionSync syncMode,
4299 std::chrono::milliseconds timeout,
4300 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004301 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004302 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4303 "policyFlags=0x%08x",
4304 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4305 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004306 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004307 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308
Prabir Pradhan5735a322022-04-11 17:23:34 +00004309 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004311 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004312 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4313 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4314 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4315 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4316 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004317 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004318 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004319 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004320 }
4321
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004322 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004324 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004325 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4326 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004327 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004328 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004329 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004331 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004332 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4333 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4334 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004335 int32_t keyCode = incomingKey.getKeyCode();
4336 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004337 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004338 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004339 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004340 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004341 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4342 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4343 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004345 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4346 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004347 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004348
4349 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4350 android::base::Timer t;
4351 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4352 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4353 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4354 std::to_string(t.duration().count()).c_str());
4355 }
4356 }
4357
4358 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004359 std::unique_ptr<KeyEntry> injectedEntry =
4360 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004361 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004362 incomingKey.getDisplayId(), policyFlags, action,
4363 flags, keyCode, incomingKey.getScanCode(), metaState,
4364 incomingKey.getRepeatCount(),
4365 incomingKey.getDownTime());
4366 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004367 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368 }
4369
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004370 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004371 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004372 const int32_t action = motionEvent.getAction();
4373 const bool isPointerEvent =
4374 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4375 // If a pointer event has no displayId specified, inject it to the default display.
4376 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4377 ? ADISPLAY_ID_DEFAULT
4378 : event->getDisplayId();
4379 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004380 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004381 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004382 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004383 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004384 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004385 }
4386
4387 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004388 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004389 android::base::Timer t;
4390 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4391 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4392 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4393 std::to_string(t.duration().count()).c_str());
4394 }
4395 }
4396
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004397 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4398 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4399 }
4400
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004401 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004402 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4403 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004404 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004405 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4406 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004407 displayId, policyFlags, action, actionButton,
4408 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004409 motionEvent.getButtonState(),
4410 motionEvent.getClassification(),
4411 motionEvent.getEdgeFlags(),
4412 motionEvent.getXPrecision(),
4413 motionEvent.getYPrecision(),
4414 motionEvent.getRawXCursorPosition(),
4415 motionEvent.getRawYCursorPosition(),
4416 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004417 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004418 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004419 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004420 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004421 sampleEventTimes += 1;
4422 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004423 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004424 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4425 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004426 displayId, policyFlags, action, actionButton,
4427 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004428 motionEvent.getButtonState(),
4429 motionEvent.getClassification(),
4430 motionEvent.getEdgeFlags(),
4431 motionEvent.getXPrecision(),
4432 motionEvent.getYPrecision(),
4433 motionEvent.getRawXCursorPosition(),
4434 motionEvent.getRawYCursorPosition(),
4435 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004436 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004437 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004438 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4439 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004440 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004441 }
4442 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004444
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004445 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004446 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004447 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004448 }
4449
Prabir Pradhan5735a322022-04-11 17:23:34 +00004450 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004451 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004452 injectionState->injectionIsAsync = true;
4453 }
4454
4455 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004456 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004457
4458 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004459 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004460 if (DEBUG_INJECTION) {
4461 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4462 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004463 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004464 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004465 }
4466
4467 mLock.unlock();
4468
4469 if (needWake) {
4470 mLooper->wake();
4471 }
4472
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004473 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004474 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004475 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004476
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004477 if (syncMode == InputEventInjectionSync::NONE) {
4478 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479 } else {
4480 for (;;) {
4481 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004482 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004483 break;
4484 }
4485
4486 nsecs_t remainingTimeout = endTime - now();
4487 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004488 if (DEBUG_INJECTION) {
4489 ALOGD("injectInputEvent - Timed out waiting for injection result "
4490 "to become available.");
4491 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004492 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493 break;
4494 }
4495
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004496 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004497 }
4498
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004499 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4500 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004502 if (DEBUG_INJECTION) {
4503 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4504 injectionState->pendingForegroundDispatches);
4505 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004506 nsecs_t remainingTimeout = endTime - now();
4507 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004508 if (DEBUG_INJECTION) {
4509 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4510 "dispatches to finish.");
4511 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004512 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004513 break;
4514 }
4515
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004516 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004517 }
4518 }
4519 }
4520
4521 injectionState->release();
4522 } // release lock
4523
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004524 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004525 LOG(DEBUG) << "injectInputEvent - Finished with result "
4526 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004527 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004528
4529 return injectionResult;
4530}
4531
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004532std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004533 std::array<uint8_t, 32> calculatedHmac;
4534 std::unique_ptr<VerifiedInputEvent> result;
4535 switch (event.getType()) {
4536 case AINPUT_EVENT_TYPE_KEY: {
4537 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4538 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4539 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004540 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004541 break;
4542 }
4543 case AINPUT_EVENT_TYPE_MOTION: {
4544 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4545 VerifiedMotionEvent verifiedMotionEvent =
4546 verifiedMotionEventFromMotionEvent(motionEvent);
4547 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004548 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004549 break;
4550 }
4551 default: {
4552 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4553 return nullptr;
4554 }
4555 }
4556 if (calculatedHmac == INVALID_HMAC) {
4557 return nullptr;
4558 }
4559 if (calculatedHmac != event.getHmac()) {
4560 return nullptr;
4561 }
4562 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004563}
4564
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004565void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004566 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004567 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004568 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004569 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004570 LOG(DEBUG) << "Setting input event injection result to "
4571 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004572 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004573
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004574 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575 // Log the outcome since the injector did not wait for the injection result.
4576 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004577 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004578 ALOGV("Asynchronous input event injection succeeded.");
4579 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004580 case InputEventInjectionResult::TARGET_MISMATCH:
4581 ALOGV("Asynchronous input event injection target mismatch.");
4582 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004583 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004584 ALOGW("Asynchronous input event injection failed.");
4585 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004586 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004587 ALOGW("Asynchronous input event injection timed out.");
4588 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004589 case InputEventInjectionResult::PENDING:
4590 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4591 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004592 }
4593 }
4594
4595 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004596 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004597 }
4598}
4599
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004600void InputDispatcher::transformMotionEntryForInjectionLocked(
4601 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004602 // Input injection works in the logical display coordinate space, but the input pipeline works
4603 // display space, so we need to transform the injected events accordingly.
4604 const auto it = mDisplayInfos.find(entry.displayId);
4605 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004606 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004607
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004608 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4609 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4610 const vec2 cursor =
4611 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4612 {entry.xCursorPosition, entry.yCursorPosition});
4613 entry.xCursorPosition = cursor.x;
4614 entry.yCursorPosition = cursor.y;
4615 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004616 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004617 entry.pointerCoords[i] =
4618 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4619 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004620 }
4621}
4622
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004623void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4624 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004625 if (injectionState) {
4626 injectionState->pendingForegroundDispatches += 1;
4627 }
4628}
4629
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004630void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4631 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632 if (injectionState) {
4633 injectionState->pendingForegroundDispatches -= 1;
4634
4635 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004636 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004637 }
4638 }
4639}
4640
chaviw98318de2021-05-19 16:45:23 -05004641const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004642 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004643 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004644 auto it = mWindowHandlesByDisplay.find(displayId);
4645 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004646}
4647
chaviw98318de2021-05-19 16:45:23 -05004648sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004649 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004650 if (windowHandleToken == nullptr) {
4651 return nullptr;
4652 }
4653
Arthur Hungb92218b2018-08-14 12:00:21 +08004654 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004655 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4656 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004657 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004658 return windowHandle;
4659 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004660 }
4661 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004662 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663}
4664
chaviw98318de2021-05-19 16:45:23 -05004665sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4666 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004667 if (windowHandleToken == nullptr) {
4668 return nullptr;
4669 }
4670
chaviw98318de2021-05-19 16:45:23 -05004671 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004672 if (windowHandle->getToken() == windowHandleToken) {
4673 return windowHandle;
4674 }
4675 }
4676 return nullptr;
4677}
4678
chaviw98318de2021-05-19 16:45:23 -05004679sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4680 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004681 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004682 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4683 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004684 if (handle->getId() == windowHandle->getId() &&
4685 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004686 if (windowHandle->getInfo()->displayId != it.first) {
4687 ALOGE("Found window %s in display %" PRId32
4688 ", but it should belong to display %" PRId32,
4689 windowHandle->getName().c_str(), it.first,
4690 windowHandle->getInfo()->displayId);
4691 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004692 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004693 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004694 }
4695 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004696 return nullptr;
4697}
4698
chaviw98318de2021-05-19 16:45:23 -05004699sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004700 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4701 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702}
4703
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004704bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4705 const MotionEntry& motionEntry) const {
4706 const WindowInfo& info = *window->getInfo();
4707
4708 // Skip spy window targets that are not valid for targeted injection.
4709 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004710 return false;
4711 }
4712
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004713 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4714 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4715 return false;
4716 }
4717
4718 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4719 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4720 window->getName().c_str());
4721 return false;
4722 }
4723
4724 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004725 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004726 ALOGW("Not sending touch to %s because there's no corresponding connection",
4727 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004728 return false;
4729 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004730
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004731 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004732 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004733 return false;
4734 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004735
4736 // Drop events that can't be trusted due to occlusion
4737 const auto [x, y] = resolveTouchedPosition(motionEntry);
4738 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4739 if (!isTouchTrustedLocked(occlusionInfo)) {
4740 if (DEBUG_TOUCH_OCCLUSION) {
4741 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4742 for (const auto& log : occlusionInfo.debugInfo) {
4743 ALOGD("%s", log.c_str());
4744 }
4745 }
4746 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4747 occlusionInfo.obscuringUid);
4748 return false;
4749 }
4750
4751 // Drop touch events if requested by input feature
4752 if (shouldDropInput(motionEntry, window)) {
4753 return false;
4754 }
4755
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004756 return true;
4757}
4758
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004759std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4760 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004761 auto connectionIt = mConnectionsByToken.find(token);
4762 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004763 return nullptr;
4764 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004765 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004766}
4767
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004768void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004769 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4770 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004771 // Remove all handles on a display if there are no windows left.
4772 mWindowHandlesByDisplay.erase(displayId);
4773 return;
4774 }
4775
4776 // Since we compare the pointer of input window handles across window updates, we need
4777 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004778 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4779 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4780 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004781 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004782 }
4783
chaviw98318de2021-05-19 16:45:23 -05004784 std::vector<sp<WindowInfoHandle>> newHandles;
4785 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004786 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004787 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004788 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004789 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004790 const bool canReceiveInput =
4791 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4792 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004793 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004794 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004795 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004796 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004797 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004798 }
4799
4800 if (info->displayId != displayId) {
4801 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4802 handle->getName().c_str(), displayId, info->displayId);
4803 continue;
4804 }
4805
Robert Carredd13602020-04-13 17:24:34 -07004806 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4807 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004808 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004809 oldHandle->updateFrom(handle);
4810 newHandles.push_back(oldHandle);
4811 } else {
4812 newHandles.push_back(handle);
4813 }
4814 }
4815
4816 // Insert or replace
4817 mWindowHandlesByDisplay[displayId] = newHandles;
4818}
4819
Arthur Hung72d8dc32020-03-28 00:48:39 +00004820void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004821 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004822 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004823 { // acquire lock
4824 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004825 for (const auto& [displayId, handles] : handlesPerDisplay) {
4826 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004827 }
4828 }
4829 // Wake up poll loop since it may need to make new input dispatching choices.
4830 mLooper->wake();
4831}
4832
Arthur Hungb92218b2018-08-14 12:00:21 +08004833/**
4834 * Called from InputManagerService, update window handle list by displayId that can receive input.
4835 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4836 * If set an empty list, remove all handles from the specific display.
4837 * For focused handle, check if need to change and send a cancel event to previous one.
4838 * For removed handle, check if need to send a cancel event if already in touch.
4839 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004840void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004841 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004842 if (DEBUG_FOCUS) {
4843 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004844 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004845 windowList += iwh->getName() + " ";
4846 }
4847 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4848 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004849
Prabir Pradhand65552b2021-10-07 11:23:50 -07004850 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004851 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004852 const WindowInfo& info = *window->getInfo();
4853
4854 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004855 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004856 if (noInputWindow && window->getToken() != nullptr) {
4857 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4858 window->getName().c_str());
4859 window->releaseChannel();
4860 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004861
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004862 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004863 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4864 !info.inputConfig.test(
4865 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004866 "%s has feature SPY, but is not a trusted overlay.",
4867 window->getName().c_str());
4868
Prabir Pradhand65552b2021-10-07 11:23:50 -07004869 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004870 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4871 !info.inputConfig.test(
4872 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004873 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4874 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004875 }
4876
Arthur Hung72d8dc32020-03-28 00:48:39 +00004877 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004878 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004879
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004880 // Save the old windows' orientation by ID before it gets updated.
4881 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004882 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004883 oldWindowOrientations.emplace(handle->getId(),
4884 handle->getInfo()->transform.getOrientation());
4885 }
4886
chaviw98318de2021-05-19 16:45:23 -05004887 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004888
chaviw98318de2021-05-19 16:45:23 -05004889 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004890
Vishnu Nairc519ff72021-01-21 08:23:08 -08004891 std::optional<FocusResolver::FocusChanges> changes =
4892 mFocusResolver.setInputWindows(displayId, windowHandles);
4893 if (changes) {
4894 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004895 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004896
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004897 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4898 mTouchStatesByDisplay.find(displayId);
4899 if (stateIt != mTouchStatesByDisplay.end()) {
4900 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004901 for (size_t i = 0; i < state.windows.size();) {
4902 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004903 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004904 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004905 ALOGD("Touched window was removed: %s in display %" PRId32,
4906 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004907 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004908 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004909 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4910 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004911 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00004912 "touched window was removed");
4913 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004914 // Since we are about to drop the touch, cancel the events for the wallpaper as
4915 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004916 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004917 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4918 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004919 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004920 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004921 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004923 state.windows.erase(state.windows.begin() + i);
4924 } else {
4925 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926 }
4927 }
arthurhungb89ccb02020-12-30 16:19:01 +08004928
arthurhung6d4bed92021-03-17 11:59:33 +08004929 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004930 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004931 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004932 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004933 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004934 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4935 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004936 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004937 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004938 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004939
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004940 // Determine if the orientation of any of the input windows have changed, and cancel all
4941 // pointer events if necessary.
4942 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4943 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4944 if (newWindowHandle != nullptr &&
4945 newWindowHandle->getInfo()->transform.getOrientation() !=
4946 oldWindowOrientations[oldWindowHandle->getId()]) {
4947 std::shared_ptr<InputChannel> inputChannel =
4948 getInputChannelLocked(newWindowHandle->getToken());
4949 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004950 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004951 "touched window's orientation changed");
4952 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004953 }
4954 }
4955 }
4956
Arthur Hung72d8dc32020-03-28 00:48:39 +00004957 // Release information for windows that are no longer present.
4958 // This ensures that unused input channels are released promptly.
4959 // Otherwise, they might stick around until the window handle is destroyed
4960 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004961 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004962 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004963 if (DEBUG_FOCUS) {
4964 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004965 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004966 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004967 }
chaviw291d88a2019-02-14 10:33:58 -08004968 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004969}
4970
4971void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004972 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004973 if (DEBUG_FOCUS) {
4974 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4975 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4976 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004977 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004978 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004979 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004980 } // release lock
4981
4982 // Wake up poll loop since it may need to make new input dispatching choices.
4983 mLooper->wake();
4984}
4985
Vishnu Nair599f1412021-06-21 10:39:58 -07004986void InputDispatcher::setFocusedApplicationLocked(
4987 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4988 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4989 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4990
4991 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4992 return; // This application is already focused. No need to wake up or change anything.
4993 }
4994
4995 // Set the new application handle.
4996 if (inputApplicationHandle != nullptr) {
4997 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4998 } else {
4999 mFocusedApplicationHandlesByDisplay.erase(displayId);
5000 }
5001
5002 // No matter what the old focused application was, stop waiting on it because it is
5003 // no longer focused.
5004 resetNoFocusedWindowTimeoutLocked();
5005}
5006
Tiger Huang721e26f2018-07-24 22:26:19 +08005007/**
5008 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5009 * the display not specified.
5010 *
5011 * We track any unreleased events for each window. If a window loses the ability to receive the
5012 * released event, we will send a cancel event to it. So when the focused display is changed, we
5013 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5014 * display. The display-specified events won't be affected.
5015 */
5016void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005017 if (DEBUG_FOCUS) {
5018 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5019 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005020 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005021 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005022
5023 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005024 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005025 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005026 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005027 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005028 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005029 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005030 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005031 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005032 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005033 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005034 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5035 }
5036 }
5037 mFocusedDisplayId = displayId;
5038
Chris Ye3c2d6f52020-08-09 10:39:48 -07005039 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005040 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005041 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005042
Vishnu Nairad321cd2020-08-20 16:40:21 -07005043 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005044 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005045 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005046 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005047 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005048 }
5049 }
5050 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005051 } // release lock
5052
5053 // Wake up poll loop since it may need to make new input dispatching choices.
5054 mLooper->wake();
5055}
5056
Michael Wrightd02c5b62014-02-10 15:10:22 -08005057void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005058 if (DEBUG_FOCUS) {
5059 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5060 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005061
5062 bool changed;
5063 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005064 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005065
5066 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5067 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005068 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005069 }
5070
5071 if (mDispatchEnabled && !enabled) {
5072 resetAndDropEverythingLocked("dispatcher is being disabled");
5073 }
5074
5075 mDispatchEnabled = enabled;
5076 mDispatchFrozen = frozen;
5077 changed = true;
5078 } else {
5079 changed = false;
5080 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005081 } // release lock
5082
5083 if (changed) {
5084 // Wake up poll loop since it may need to make new input dispatching choices.
5085 mLooper->wake();
5086 }
5087}
5088
5089void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005090 if (DEBUG_FOCUS) {
5091 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5092 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005093
5094 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005095 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005096
5097 if (mInputFilterEnabled == enabled) {
5098 return;
5099 }
5100
5101 mInputFilterEnabled = enabled;
5102 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5103 } // release lock
5104
5105 // Wake up poll loop since there might be work to do to drop everything.
5106 mLooper->wake();
5107}
5108
Antonio Kanteka042c022022-07-06 16:51:07 -07005109bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5110 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005111 bool needWake = false;
5112 {
5113 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005114 ALOGD_IF(DEBUG_TOUCH_MODE,
5115 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5116 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5117 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5118 mTouchModePerDisplay.count(displayId) == 0
5119 ? "not set"
5120 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5121
Antonio Kantek15beb512022-06-13 22:35:41 +00005122 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5123 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005124 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005125 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005126 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005127 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5128 !recentWindowsAreOwnedByLocked(pid, uid)) {
5129 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5130 "window nor none of the previously interacted window",
5131 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005132 return false;
5133 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005134 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005135 mTouchModePerDisplay[displayId] = inTouchMode;
5136 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5137 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005138 needWake = enqueueInboundEventLocked(std::move(entry));
5139 } // release lock
5140
5141 if (needWake) {
5142 mLooper->wake();
5143 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005144 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005145}
5146
Antonio Kantek48710e42022-03-24 14:19:30 -07005147bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5148 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5149 if (focusedToken == nullptr) {
5150 return false;
5151 }
5152 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5153 return isWindowOwnedBy(windowHandle, pid, uid);
5154}
5155
5156bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5157 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5158 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5159 const sp<WindowInfoHandle> windowHandle =
5160 getWindowHandleLocked(connectionToken);
5161 return isWindowOwnedBy(windowHandle, pid, uid);
5162 }) != mInteractionConnectionTokens.end();
5163}
5164
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005165void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5166 if (opacity < 0 || opacity > 1) {
5167 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5168 return;
5169 }
5170
5171 std::scoped_lock lock(mLock);
5172 mMaximumObscuringOpacityForTouch = opacity;
5173}
5174
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005175std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5176InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005177 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5178 for (TouchedWindow& w : state.windows) {
5179 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005180 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005181 }
5182 }
5183 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005184 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005185}
5186
arthurhungb89ccb02020-12-30 16:19:01 +08005187bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5188 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005189 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005190 if (DEBUG_FOCUS) {
5191 ALOGD("Trivial transfer to same window.");
5192 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005193 return true;
5194 }
5195
Michael Wrightd02c5b62014-02-10 15:10:22 -08005196 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005197 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005198
Arthur Hungabbb9d82021-09-01 14:52:30 +00005199 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005200 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005201 if (state == nullptr || touchedWindow == nullptr) {
5202 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005203 return false;
5204 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005205
Arthur Hungabbb9d82021-09-01 14:52:30 +00005206 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5207 if (toWindowHandle == nullptr) {
5208 ALOGW("Cannot transfer focus because to window not found.");
5209 return false;
5210 }
5211
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005212 if (DEBUG_FOCUS) {
5213 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005214 touchedWindow->windowHandle->getName().c_str(),
5215 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005216 }
5217
Arthur Hungabbb9d82021-09-01 14:52:30 +00005218 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005219 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005220 BitSet32 pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005221 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005222 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005223
Arthur Hungabbb9d82021-09-01 14:52:30 +00005224 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005225 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005226 ftl::Flags<InputTarget::Flags> newTargetFlags =
5227 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005228 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005229 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005230 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005231 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005232
Arthur Hungabbb9d82021-09-01 14:52:30 +00005233 // Store the dragging window.
5234 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005235 if (pointerIds.count() != 1) {
5236 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5237 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005238 return false;
5239 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005240 // Track the pointer id for drag window and generate the drag state.
5241 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005242 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005243 }
5244
Arthur Hungabbb9d82021-09-01 14:52:30 +00005245 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005246 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5247 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005248 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005249 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005250 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005251 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005252 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005253 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005254 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5255 newTargetFlags);
5256
5257 // Check if the wallpaper window should deliver the corresponding event.
5258 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5259 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005260 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005261 } // release lock
5262
5263 // Wake up poll loop since it may need to make new input dispatching choices.
5264 mLooper->wake();
5265 return true;
5266}
5267
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005268/**
5269 * Get the touched foreground window on the given display.
5270 * Return null if there are no windows touched on that display, or if more than one foreground
5271 * window is being touched.
5272 */
5273sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5274 auto stateIt = mTouchStatesByDisplay.find(displayId);
5275 if (stateIt == mTouchStatesByDisplay.end()) {
5276 ALOGI("No touch state on display %" PRId32, displayId);
5277 return nullptr;
5278 }
5279
5280 const TouchState& state = stateIt->second;
5281 sp<WindowInfoHandle> touchedForegroundWindow;
5282 // If multiple foreground windows are touched, return nullptr
5283 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005284 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005285 if (touchedForegroundWindow != nullptr) {
5286 ALOGI("Two or more foreground windows: %s and %s",
5287 touchedForegroundWindow->getName().c_str(),
5288 window.windowHandle->getName().c_str());
5289 return nullptr;
5290 }
5291 touchedForegroundWindow = window.windowHandle;
5292 }
5293 }
5294 return touchedForegroundWindow;
5295}
5296
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005297// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005298bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005299 sp<IBinder> fromToken;
5300 { // acquire lock
5301 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005302 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005303 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005304 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5305 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005306 return false;
5307 }
5308
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005309 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5310 if (from == nullptr) {
5311 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5312 return false;
5313 }
5314
5315 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005316 } // release lock
5317
5318 return transferTouchFocus(fromToken, destChannelToken);
5319}
5320
Michael Wrightd02c5b62014-02-10 15:10:22 -08005321void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005322 if (DEBUG_FOCUS) {
5323 ALOGD("Resetting and dropping all events (%s).", reason);
5324 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005325
Michael Wrightfb04fd52022-11-24 22:31:11 +00005326 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005327 synthesizeCancelationEventsForAllConnectionsLocked(options);
5328
5329 resetKeyRepeatLocked();
5330 releasePendingEventLocked();
5331 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005332 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005333
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005334 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005335 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005336 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005337}
5338
5339void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005340 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005341 dumpDispatchStateLocked(dump);
5342
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005343 std::istringstream stream(dump);
5344 std::string line;
5345
5346 while (std::getline(stream, line, '\n')) {
5347 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005348 }
5349}
5350
Prabir Pradhan99987712020-11-10 18:43:05 -08005351std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5352 std::string dump;
5353
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005354 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5355 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005356
5357 std::string windowName = "None";
5358 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005359 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005360 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5361 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5362 : "token has capture without window";
5363 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005364 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005365
5366 return dump;
5367}
5368
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005369void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005370 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5371 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5372 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005373 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005374
Tiger Huang721e26f2018-07-24 22:26:19 +08005375 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5376 dump += StringPrintf(INDENT "FocusedApplications:\n");
5377 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5378 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005379 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005380 const std::chrono::duration timeout =
5381 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005382 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005383 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005384 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005385 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005386 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005387 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005388 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005389
Vishnu Nairc519ff72021-01-21 08:23:08 -08005390 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005391 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005392
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005393 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005394 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005395 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005396 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5397 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005398 }
5399 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005400 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005401 }
5402
arthurhung6d4bed92021-03-17 11:59:33 +08005403 if (mDragState) {
5404 dump += StringPrintf(INDENT "DragState:\n");
5405 mDragState->dump(dump, INDENT2);
5406 }
5407
Arthur Hungb92218b2018-08-14 12:00:21 +08005408 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005409 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5410 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5411 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5412 const auto& displayInfo = it->second;
5413 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5414 displayInfo.logicalHeight);
5415 displayInfo.transform.dump(dump, "transform", INDENT4);
5416 } else {
5417 dump += INDENT2 "No DisplayInfo found!\n";
5418 }
5419
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005420 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005421 dump += INDENT2 "Windows:\n";
5422 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005423 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5424 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005425
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005426 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005427 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005428 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005429 "applicationInfo.name=%s, "
5430 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005431 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005432 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005433 windowInfo->displayId,
5434 windowInfo->inputConfig.string().c_str(),
5435 windowInfo->alpha, windowInfo->frameLeft,
5436 windowInfo->frameTop, windowInfo->frameRight,
5437 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005438 windowInfo->applicationInfo.name.c_str(),
5439 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005440 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005441 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005442 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005443 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005444 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005445 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005446 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005447 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005448 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005449 }
5450 } else {
5451 dump += INDENT2 "Windows: <none>\n";
5452 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005453 }
5454 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005455 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005456 }
5457
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005458 if (!mGlobalMonitorsByDisplay.empty()) {
5459 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5460 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005461 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005463 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005464 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005465 }
5466
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005467 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005468
5469 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005470 if (!mRecentQueue.empty()) {
5471 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005472 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005473 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005474 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005475 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005476 }
5477 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005478 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005479 }
5480
5481 // Dump event currently being dispatched.
5482 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005483 dump += INDENT "PendingEvent:\n";
5484 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005485 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005486 dump += StringPrintf(", age=%" PRId64 "ms\n",
5487 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005489 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490 }
5491
5492 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005493 if (!mInboundQueue.empty()) {
5494 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005495 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005496 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005497 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005498 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005499 }
5500 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005501 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005502 }
5503
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005504 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005505 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005506 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005507 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005508 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005509 }
5510 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005511 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005512 }
5513
Prabir Pradhancef936d2021-07-21 16:17:52 +00005514 if (!mCommandQueue.empty()) {
5515 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5516 } else {
5517 dump += INDENT "CommandQueue: <empty>\n";
5518 }
5519
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005520 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005521 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005522 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005523 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005524 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005525 connection->inputChannel->getFd().get(),
5526 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005527 connection->getWindowName().c_str(),
5528 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005529 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005530
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005531 if (!connection->outboundQueue.empty()) {
5532 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5533 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005534 dump += dumpQueue(connection->outboundQueue, currentTime);
5535
Michael Wrightd02c5b62014-02-10 15:10:22 -08005536 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005537 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005538 }
5539
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005540 if (!connection->waitQueue.empty()) {
5541 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5542 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005543 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005544 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005545 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005546 }
5547 }
5548 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005549 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005550 }
5551
5552 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005553 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5554 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005555 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005556 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005557 }
5558
Antonio Kantek15beb512022-06-13 22:35:41 +00005559 if (!mTouchModePerDisplay.empty()) {
5560 dump += INDENT "TouchModePerDisplay:\n";
5561 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5562 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5563 std::to_string(touchMode).c_str());
5564 }
5565 } else {
5566 dump += INDENT "TouchModePerDisplay: <none>\n";
5567 }
5568
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005569 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005570 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5571 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5572 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005573 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005574 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005575}
5576
Michael Wright3dd60e22019-03-27 22:06:44 +00005577void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5578 const size_t numMonitors = monitors.size();
5579 for (size_t i = 0; i < numMonitors; i++) {
5580 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005581 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005582 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5583 dump += "\n";
5584 }
5585}
5586
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005587class LooperEventCallback : public LooperCallback {
5588public:
5589 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5590 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5591
5592private:
5593 std::function<int(int events)> mCallback;
5594};
5595
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005596Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005597 if (DEBUG_CHANNEL_CREATION) {
5598 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005600
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005601 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005602 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005603 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005604
5605 if (result) {
5606 return base::Error(result) << "Failed to open input channel pair with name " << name;
5607 }
5608
Michael Wrightd02c5b62014-02-10 15:10:22 -08005609 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005610 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005611 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005612 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005613 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005614 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005615
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005616 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5617 ALOGE("Created a new connection, but the token %p is already known", token.get());
5618 }
5619 mConnectionsByToken.emplace(token, connection);
5620
5621 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5622 this, std::placeholders::_1, token);
5623
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005624 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5625 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005626 } // release lock
5627
5628 // Wake the looper because some connections have changed.
5629 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005630 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005631}
5632
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005633Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005634 const std::string& name,
5635 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005636 std::shared_ptr<InputChannel> serverChannel;
5637 std::unique_ptr<InputChannel> clientChannel;
5638 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5639 if (result) {
5640 return base::Error(result) << "Failed to open input channel pair with name " << name;
5641 }
5642
Michael Wright3dd60e22019-03-27 22:06:44 +00005643 { // acquire lock
5644 std::scoped_lock _l(mLock);
5645
5646 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005647 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5648 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005649 }
5650
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005651 sp<Connection> connection =
5652 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005653 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005654 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005655
5656 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5657 ALOGE("Created a new connection, but the token %p is already known", token.get());
5658 }
5659 mConnectionsByToken.emplace(token, connection);
5660 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5661 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005662
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005663 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005664
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005665 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5666 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005667 }
Garfield Tan15601662020-09-22 15:32:38 -07005668
Michael Wright3dd60e22019-03-27 22:06:44 +00005669 // Wake the looper because some connections have changed.
5670 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005671 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005672}
5673
Garfield Tan15601662020-09-22 15:32:38 -07005674status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005675 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005676 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005677
Garfield Tan15601662020-09-22 15:32:38 -07005678 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005679 if (status) {
5680 return status;
5681 }
5682 } // release lock
5683
5684 // Wake the poll loop because removing the connection may have changed the current
5685 // synchronization state.
5686 mLooper->wake();
5687 return OK;
5688}
5689
Garfield Tan15601662020-09-22 15:32:38 -07005690status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5691 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005692 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005693 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005694 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005695 return BAD_VALUE;
5696 }
5697
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005698 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005699
Michael Wrightd02c5b62014-02-10 15:10:22 -08005700 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005701 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005702 }
5703
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005704 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005705
5706 nsecs_t currentTime = now();
5707 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5708
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005709 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005710 return OK;
5711}
5712
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005713void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005714 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5715 auto& [displayId, monitors] = *it;
5716 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5717 return monitor.inputChannel->getConnectionToken() == connectionToken;
5718 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005719
Michael Wright3dd60e22019-03-27 22:06:44 +00005720 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005721 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005722 } else {
5723 ++it;
5724 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005725 }
5726}
5727
Michael Wright3dd60e22019-03-27 22:06:44 +00005728status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005729 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005730 return pilferPointersLocked(token);
5731}
Michael Wright3dd60e22019-03-27 22:06:44 +00005732
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005733status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005734 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5735 if (!requestingChannel) {
5736 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5737 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005738 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005739
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005740 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07005741 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.isEmpty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005742 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5743 " Ignoring.");
5744 return BAD_VALUE;
5745 }
5746
5747 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005748 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005749 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005750 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005751 "input channel stole pointer stream");
5752 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005753 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005754 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005755 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005756 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005757 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005758 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005759 if (channel != nullptr && channel->getConnectionToken() != token) {
5760 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5761 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5762 canceledWindows += channel->getName();
5763 }
5764 }
5765 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5766 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5767 canceledWindows.c_str());
5768
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005769 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005770 // This only blocks relevant pointers to be sent to other windows
5771 window.isPilferingPointers = true;
5772
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005773 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005774 return OK;
5775}
5776
Prabir Pradhan99987712020-11-10 18:43:05 -08005777void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5778 { // acquire lock
5779 std::scoped_lock _l(mLock);
5780 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005781 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005782 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5783 windowHandle != nullptr ? windowHandle->getName().c_str()
5784 : "token without window");
5785 }
5786
Vishnu Nairc519ff72021-01-21 08:23:08 -08005787 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005788 if (focusedToken != windowToken) {
5789 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5790 enabled ? "enable" : "disable");
5791 return;
5792 }
5793
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005794 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005795 ALOGW("Ignoring request to %s Pointer Capture: "
5796 "window has %s requested pointer capture.",
5797 enabled ? "enable" : "disable", enabled ? "already" : "not");
5798 return;
5799 }
5800
Christine Franksb768bb42021-11-29 12:11:31 -08005801 if (enabled) {
5802 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5803 mIneligibleDisplaysForPointerCapture.end(),
5804 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5805 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5806 return;
5807 }
5808 }
5809
Prabir Pradhan99987712020-11-10 18:43:05 -08005810 setPointerCaptureLocked(enabled);
5811 } // release lock
5812
5813 // Wake the thread to process command entries.
5814 mLooper->wake();
5815}
5816
Christine Franksb768bb42021-11-29 12:11:31 -08005817void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5818 { // acquire lock
5819 std::scoped_lock _l(mLock);
5820 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5821 if (!isEligible) {
5822 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5823 }
5824 } // release lock
5825}
5826
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005827std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5828 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005829 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005830 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005831 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005832 }
5833 }
5834 }
5835 return std::nullopt;
5836}
5837
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005838sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005839 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005840 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005841 }
5842
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005843 for (const auto& [token, connection] : mConnectionsByToken) {
5844 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005845 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005846 }
5847 }
Robert Carr4e670e52018-08-15 13:26:12 -07005848
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005849 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005850}
5851
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005852std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5853 sp<Connection> connection = getConnectionLocked(connectionToken);
5854 if (connection == nullptr) {
5855 return "<nullptr>";
5856 }
5857 return connection->getInputChannelName();
5858}
5859
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005860void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005861 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005862 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005863}
5864
Prabir Pradhancef936d2021-07-21 16:17:52 +00005865void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5866 const sp<Connection>& connection, uint32_t seq,
5867 bool handled, nsecs_t consumeTime) {
5868 // Handle post-event policy actions.
5869 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5870 if (dispatchEntryIt == connection->waitQueue.end()) {
5871 return;
5872 }
5873 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5874 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5875 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5876 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5877 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5878 }
5879 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5880 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5881 connection->inputChannel->getConnectionToken(),
5882 dispatchEntry->deliveryTime, consumeTime, finishTime);
5883 }
5884
5885 bool restartEvent;
5886 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5887 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5888 restartEvent =
5889 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5890 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5891 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5892 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5893 handled);
5894 } else {
5895 restartEvent = false;
5896 }
5897
5898 // Dequeue the event and start the next cycle.
5899 // Because the lock might have been released, it is possible that the
5900 // contents of the wait queue to have been drained, so we need to double-check
5901 // a few things.
5902 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5903 if (dispatchEntryIt != connection->waitQueue.end()) {
5904 dispatchEntry = *dispatchEntryIt;
5905 connection->waitQueue.erase(dispatchEntryIt);
5906 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5907 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5908 if (!connection->responsive) {
5909 connection->responsive = isConnectionResponsive(*connection);
5910 if (connection->responsive) {
5911 // The connection was unresponsive, and now it's responsive.
5912 processConnectionResponsiveLocked(*connection);
5913 }
5914 }
5915 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005916 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005917 connection->outboundQueue.push_front(dispatchEntry);
5918 traceOutboundQueueLength(*connection);
5919 } else {
5920 releaseDispatchEntry(dispatchEntry);
5921 }
5922 }
5923
5924 // Start the next dispatch cycle for this connection.
5925 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005926}
5927
Prabir Pradhancef936d2021-07-21 16:17:52 +00005928void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5929 const sp<IBinder>& newToken) {
5930 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5931 scoped_unlock unlock(mLock);
5932 mPolicy->notifyFocusChanged(oldToken, newToken);
5933 };
5934 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005935}
5936
Prabir Pradhancef936d2021-07-21 16:17:52 +00005937void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5938 auto command = [this, token, x, y]() REQUIRES(mLock) {
5939 scoped_unlock unlock(mLock);
5940 mPolicy->notifyDropWindow(token, x, y);
5941 };
5942 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005943}
5944
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005945void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5946 if (connection == nullptr) {
5947 LOG_ALWAYS_FATAL("Caller must check for nullness");
5948 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005949 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5950 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005951 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005952 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005953 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005954 return;
5955 }
5956 /**
5957 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5958 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5959 * has changed. This could cause newer entries to time out before the already dispatched
5960 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5961 * processes the events linearly. So providing information about the oldest entry seems to be
5962 * most useful.
5963 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005964 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005965 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5966 std::string reason =
5967 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005968 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005969 ns2ms(currentWait),
5970 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005971 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005972 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005973
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005974 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5975
5976 // Stop waking up for events on this connection, it is already unresponsive
5977 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005978}
5979
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005980void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5981 std::string reason =
5982 StringPrintf("%s does not have a focused window", application->getName().c_str());
5983 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005984
Prabir Pradhancef936d2021-07-21 16:17:52 +00005985 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5986 scoped_unlock unlock(mLock);
5987 mPolicy->notifyNoFocusedWindowAnr(application);
5988 };
5989 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005990}
5991
chaviw98318de2021-05-19 16:45:23 -05005992void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005993 const std::string& reason) {
5994 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5995 updateLastAnrStateLocked(windowLabel, reason);
5996}
5997
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005998void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5999 const std::string& reason) {
6000 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006001 updateLastAnrStateLocked(windowLabel, reason);
6002}
6003
6004void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6005 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006006 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006007 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006008 struct tm tm;
6009 localtime_r(&t, &tm);
6010 char timestr[64];
6011 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006012 mLastAnrState.clear();
6013 mLastAnrState += INDENT "ANR:\n";
6014 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006015 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6016 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006017 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006018}
6019
Prabir Pradhancef936d2021-07-21 16:17:52 +00006020void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6021 KeyEntry& entry) {
6022 const KeyEvent event = createKeyEvent(entry);
6023 nsecs_t delay = 0;
6024 { // release lock
6025 scoped_unlock unlock(mLock);
6026 android::base::Timer t;
6027 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
6028 entry.policyFlags);
6029 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6030 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6031 std::to_string(t.duration().count()).c_str());
6032 }
6033 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006034
6035 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006036 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006037 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006038 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006039 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006040 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006041 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006043}
6044
Prabir Pradhancef936d2021-07-21 16:17:52 +00006045void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006046 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006047 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006048 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006049 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006050 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006051 };
6052 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006053}
6054
Prabir Pradhanedd96402022-02-15 01:46:16 -08006055void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6056 std::optional<int32_t> pid) {
6057 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006058 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006059 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006060 };
6061 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006062}
6063
6064/**
6065 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6066 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6067 * command entry to the command queue.
6068 */
6069void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6070 std::string reason) {
6071 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006072 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006073 if (connection.monitor) {
6074 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6075 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006076 pid = findMonitorPidByTokenLocked(connectionToken);
6077 } else {
6078 // The connection is a window
6079 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6080 reason.c_str());
6081 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6082 if (handle != nullptr) {
6083 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006084 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006085 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006086 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006087}
6088
6089/**
6090 * Tell the policy that a connection has become responsive so that it can stop ANR.
6091 */
6092void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6093 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006094 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006095 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006096 pid = findMonitorPidByTokenLocked(connectionToken);
6097 } else {
6098 // The connection is a window
6099 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6100 if (handle != nullptr) {
6101 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006102 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006103 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006104 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006105}
6106
Prabir Pradhancef936d2021-07-21 16:17:52 +00006107bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006108 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006109 KeyEntry& keyEntry, bool handled) {
6110 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006111 if (!handled) {
6112 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006113 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006114 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006115 return false;
6116 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006117
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006118 // Get the fallback key state.
6119 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006120 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006121 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006122 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006123 connection->inputState.removeFallbackKey(originalKeyCode);
6124 }
6125
6126 if (handled || !dispatchEntry->hasForegroundTarget()) {
6127 // If the application handles the original key for which we previously
6128 // generated a fallback or if the window is not a foreground window,
6129 // then cancel the associated fallback key, if any.
6130 if (fallbackKeyCode != -1) {
6131 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006132 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6133 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6134 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6135 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6136 keyEntry.policyFlags);
6137 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006138 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006139 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006140
6141 mLock.unlock();
6142
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006143 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006144 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006145
6146 mLock.lock();
6147
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006148 // Cancel the fallback key.
6149 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006150 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006151 "application handled the original non-fallback key "
6152 "or is no longer a foreground target, "
6153 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006154 options.keyCode = fallbackKeyCode;
6155 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006156 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006157 connection->inputState.removeFallbackKey(originalKeyCode);
6158 }
6159 } else {
6160 // If the application did not handle a non-fallback key, first check
6161 // that we are in a good state to perform unhandled key event processing
6162 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006163 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006164 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006165 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6166 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6167 "since this is not an initial down. "
6168 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6169 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6170 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006171 return false;
6172 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006173
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006174 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006175 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6176 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6177 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6178 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6179 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006180 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006181
6182 mLock.unlock();
6183
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006184 bool fallback =
6185 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006186 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006187
6188 mLock.lock();
6189
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006190 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006191 connection->inputState.removeFallbackKey(originalKeyCode);
6192 return false;
6193 }
6194
6195 // Latch the fallback keycode for this key on an initial down.
6196 // The fallback keycode cannot change at any other point in the lifecycle.
6197 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006198 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006199 fallbackKeyCode = event.getKeyCode();
6200 } else {
6201 fallbackKeyCode = AKEYCODE_UNKNOWN;
6202 }
6203 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6204 }
6205
6206 ALOG_ASSERT(fallbackKeyCode != -1);
6207
6208 // Cancel the fallback key if the policy decides not to send it anymore.
6209 // We will continue to dispatch the key to the policy but we will no
6210 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006211 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6212 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006213 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6214 if (fallback) {
6215 ALOGD("Unhandled key event: Policy requested to send key %d"
6216 "as a fallback for %d, but on the DOWN it had requested "
6217 "to send %d instead. Fallback canceled.",
6218 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6219 } else {
6220 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6221 "but on the DOWN it had requested to send %d. "
6222 "Fallback canceled.",
6223 originalKeyCode, fallbackKeyCode);
6224 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006225 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006226
Michael Wrightfb04fd52022-11-24 22:31:11 +00006227 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006228 "canceling fallback, policy no longer desires it");
6229 options.keyCode = fallbackKeyCode;
6230 synthesizeCancelationEventsForConnectionLocked(connection, options);
6231
6232 fallback = false;
6233 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006234 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006235 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006236 }
6237 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006238
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006239 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6240 {
6241 std::string msg;
6242 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6243 connection->inputState.getFallbackKeys();
6244 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6245 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6246 }
6247 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6248 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006249 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006250 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006251
6252 if (fallback) {
6253 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006254 keyEntry.eventTime = event.getEventTime();
6255 keyEntry.deviceId = event.getDeviceId();
6256 keyEntry.source = event.getSource();
6257 keyEntry.displayId = event.getDisplayId();
6258 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6259 keyEntry.keyCode = fallbackKeyCode;
6260 keyEntry.scanCode = event.getScanCode();
6261 keyEntry.metaState = event.getMetaState();
6262 keyEntry.repeatCount = event.getRepeatCount();
6263 keyEntry.downTime = event.getDownTime();
6264 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006265
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006266 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6267 ALOGD("Unhandled key event: Dispatching fallback key. "
6268 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6269 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6270 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006271 return true; // restart the event
6272 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006273 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6274 ALOGD("Unhandled key event: No fallback key.");
6275 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006276
6277 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006278 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006279 }
6280 }
6281 return false;
6282}
6283
Prabir Pradhancef936d2021-07-21 16:17:52 +00006284bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006285 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006286 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006287 return false;
6288}
6289
Michael Wrightd02c5b62014-02-10 15:10:22 -08006290void InputDispatcher::traceInboundQueueLengthLocked() {
6291 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006292 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006293 }
6294}
6295
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006296void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006297 if (ATRACE_ENABLED()) {
6298 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006299 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6300 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006301 }
6302}
6303
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006304void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006305 if (ATRACE_ENABLED()) {
6306 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006307 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6308 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006309 }
6310}
6311
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006312void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006313 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006314
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006315 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006316 dumpDispatchStateLocked(dump);
6317
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006318 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006319 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006320 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006321 }
6322}
6323
6324void InputDispatcher::monitor() {
6325 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006326 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006327 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006328 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006329}
6330
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006331/**
6332 * Wake up the dispatcher and wait until it processes all events and commands.
6333 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6334 * this method can be safely called from any thread, as long as you've ensured that
6335 * the work you are interested in completing has already been queued.
6336 */
6337bool InputDispatcher::waitForIdle() {
6338 /**
6339 * Timeout should represent the longest possible time that a device might spend processing
6340 * events and commands.
6341 */
6342 constexpr std::chrono::duration TIMEOUT = 100ms;
6343 std::unique_lock lock(mLock);
6344 mLooper->wake();
6345 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6346 return result == std::cv_status::no_timeout;
6347}
6348
Vishnu Naire798b472020-07-23 13:52:21 -07006349/**
6350 * Sets focus to the window identified by the token. This must be called
6351 * after updating any input window handles.
6352 *
6353 * Params:
6354 * request.token - input channel token used to identify the window that should gain focus.
6355 * request.focusedToken - the token that the caller expects currently to be focused. If the
6356 * specified token does not match the currently focused window, this request will be dropped.
6357 * If the specified focused token matches the currently focused window, the call will succeed.
6358 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6359 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6360 * when requesting the focus change. This determines which request gets
6361 * precedence if there is a focus change request from another source such as pointer down.
6362 */
Vishnu Nair958da932020-08-21 17:12:37 -07006363void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6364 { // acquire lock
6365 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006366 std::optional<FocusResolver::FocusChanges> changes =
6367 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6368 if (changes) {
6369 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006370 }
6371 } // release lock
6372 // Wake up poll loop since it may need to make new input dispatching choices.
6373 mLooper->wake();
6374}
6375
Vishnu Nairc519ff72021-01-21 08:23:08 -08006376void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6377 if (changes.oldFocus) {
6378 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006379 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006380 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006381 "focus left window");
6382 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006383 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006384 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006385 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006386 if (changes.newFocus) {
6387 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006388 }
6389
Prabir Pradhan99987712020-11-10 18:43:05 -08006390 // If a window has pointer capture, then it must have focus. We need to ensure that this
6391 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6392 // If the window loses focus before it loses pointer capture, then the window can be in a state
6393 // where it has pointer capture but not focus, violating the contract. Therefore we must
6394 // dispatch the pointer capture event before the focus event. Since focus events are added to
6395 // the front of the queue (above), we add the pointer capture event to the front of the queue
6396 // after the focus events are added. This ensures the pointer capture event ends up at the
6397 // front.
6398 disablePointerCaptureForcedLocked();
6399
Vishnu Nairc519ff72021-01-21 08:23:08 -08006400 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006401 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006402 }
6403}
Vishnu Nair958da932020-08-21 17:12:37 -07006404
Prabir Pradhan99987712020-11-10 18:43:05 -08006405void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006406 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006407 return;
6408 }
6409
6410 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6411
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006412 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006413 setPointerCaptureLocked(false);
6414 }
6415
6416 if (!mWindowTokenWithPointerCapture) {
6417 // No need to send capture changes because no window has capture.
6418 return;
6419 }
6420
6421 if (mPendingEvent != nullptr) {
6422 // Move the pending event to the front of the queue. This will give the chance
6423 // for the pending event to be dropped if it is a captured event.
6424 mInboundQueue.push_front(mPendingEvent);
6425 mPendingEvent = nullptr;
6426 }
6427
6428 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006429 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006430 mInboundQueue.push_front(std::move(entry));
6431}
6432
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006433void InputDispatcher::setPointerCaptureLocked(bool enable) {
6434 mCurrentPointerCaptureRequest.enable = enable;
6435 mCurrentPointerCaptureRequest.seq++;
6436 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006437 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006438 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006439 };
6440 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006441}
6442
Vishnu Nair599f1412021-06-21 10:39:58 -07006443void InputDispatcher::displayRemoved(int32_t displayId) {
6444 { // acquire lock
6445 std::scoped_lock _l(mLock);
6446 // Set an empty list to remove all handles from the specific display.
6447 setInputWindowsLocked(/* window handles */ {}, displayId);
6448 setFocusedApplicationLocked(displayId, nullptr);
6449 // Call focus resolver to clean up stale requests. This must be called after input windows
6450 // have been removed for the removed display.
6451 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006452 // Reset pointer capture eligibility, regardless of previous state.
6453 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006454 // Remove the associated touch mode state.
6455 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006456 } // release lock
6457
6458 // Wake up poll loop since it may need to make new input dispatching choices.
6459 mLooper->wake();
6460}
6461
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006462void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6463 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006464 // The listener sends the windows as a flattened array. Separate the windows by display for
6465 // more convenient parsing.
6466 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006467 for (const auto& info : windowInfos) {
6468 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006469 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006470 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006471
6472 { // acquire lock
6473 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006474
6475 // Ensure that we have an entry created for all existing displays so that if a displayId has
6476 // no windows, we can tell that the windows were removed from the display.
6477 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6478 handlesPerDisplay[displayId];
6479 }
6480
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006481 mDisplayInfos.clear();
6482 for (const auto& displayInfo : displayInfos) {
6483 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6484 }
6485
6486 for (const auto& [displayId, handles] : handlesPerDisplay) {
6487 setInputWindowsLocked(handles, displayId);
6488 }
6489 }
6490 // Wake up poll loop since it may need to make new input dispatching choices.
6491 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006492}
6493
Vishnu Nair062a8672021-09-03 16:07:44 -07006494bool InputDispatcher::shouldDropInput(
6495 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006496 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6497 (windowHandle->getInfo()->inputConfig.test(
6498 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006499 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006500 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6501 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006502 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006503 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006504 windowHandle->getInfo()->displayId);
6505 return true;
6506 }
6507 return false;
6508}
6509
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006510void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6511 const std::vector<gui::WindowInfo>& windowInfos,
6512 const std::vector<DisplayInfo>& displayInfos) {
6513 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6514}
6515
Arthur Hungdfd528e2021-12-08 13:23:04 +00006516void InputDispatcher::cancelCurrentTouch() {
6517 {
6518 std::scoped_lock _l(mLock);
6519 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006520 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006521 "cancel current touch");
6522 synthesizeCancelationEventsForAllConnectionsLocked(options);
6523
6524 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006525 }
6526 // Wake up poll loop since there might be work to do.
6527 mLooper->wake();
6528}
6529
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006530void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6531 std::scoped_lock _l(mLock);
6532 mMonitorDispatchingTimeout = timeout;
6533}
6534
Arthur Hungc539dbb2022-12-08 07:45:36 +00006535void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6536 const sp<WindowInfoHandle>& oldWindowHandle,
6537 const sp<WindowInfoHandle>& newWindowHandle,
6538 TouchState& state, const BitSet32& pointerIds) {
6539 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6540 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6541 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6542 newWindowHandle->getInfo()->inputConfig.test(
6543 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6544 const sp<WindowInfoHandle> oldWallpaper =
6545 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6546 const sp<WindowInfoHandle> newWallpaper =
6547 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6548 if (oldWallpaper == newWallpaper) {
6549 return;
6550 }
6551
6552 if (oldWallpaper != nullptr) {
6553 state.addOrUpdateWindow(oldWallpaper, InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6554 BitSet32(0));
6555 }
6556
6557 if (newWallpaper != nullptr) {
6558 state.addOrUpdateWindow(newWallpaper,
6559 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6560 InputTarget::Flags::WINDOW_IS_OBSCURED |
6561 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6562 pointerIds);
6563 }
6564}
6565
6566void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6567 ftl::Flags<InputTarget::Flags> newTargetFlags,
6568 const sp<WindowInfoHandle> fromWindowHandle,
6569 const sp<WindowInfoHandle> toWindowHandle,
6570 TouchState& state, const BitSet32& pointerIds) {
6571 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6572 fromWindowHandle->getInfo()->inputConfig.test(
6573 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6574 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6575 toWindowHandle->getInfo()->inputConfig.test(
6576 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6577
6578 const sp<WindowInfoHandle> oldWallpaper =
6579 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6580 const sp<WindowInfoHandle> newWallpaper =
6581 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6582 if (oldWallpaper == newWallpaper) {
6583 return;
6584 }
6585
6586 if (oldWallpaper != nullptr) {
6587 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6588 "transferring touch focus to another window");
6589 state.removeWindowByToken(oldWallpaper->getToken());
6590 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6591 }
6592
6593 if (newWallpaper != nullptr) {
6594 nsecs_t downTimeInTarget = now();
6595 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6596 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6597 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6598 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6599 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
6600 sp<Connection> wallpaperConnection = getConnectionLocked(newWallpaper->getToken());
6601 if (wallpaperConnection != nullptr) {
6602 sp<Connection> toConnection = getConnectionLocked(toWindowHandle->getToken());
6603 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6604 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6605 wallpaperFlags);
6606 }
6607 }
6608}
6609
6610sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6611 const sp<WindowInfoHandle>& windowHandle) const {
6612 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6613 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6614 bool foundWindow = false;
6615 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6616 if (!foundWindow && otherHandle != windowHandle) {
6617 continue;
6618 }
6619 if (windowHandle == otherHandle) {
6620 foundWindow = true;
6621 continue;
6622 }
6623
6624 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6625 return otherHandle;
6626 }
6627 }
6628 return nullptr;
6629}
6630
Garfield Tane84e6f92019-08-29 17:28:41 -07006631} // namespace android::inputdispatcher