blob: 4d3e6def009f4db5b76ffa7bd9b697140f2aed8a [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080023#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080024#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050025#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070026#include <binder/Binder.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080027#include <ftl/enum.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070028#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050029#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070030#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080031#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080032#include <input/PrintTools.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070033#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010034#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070035#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080036
Michael Wright44753b12020-07-08 13:48:11 +010037#include <cerrno>
38#include <cinttypes>
39#include <climits>
40#include <cstddef>
41#include <ctime>
42#include <queue>
43#include <sstream>
44
45#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000046#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070047#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010048
Michael Wrightd02c5b62014-02-10 15:10:22 -080049#define INDENT " "
50#define INDENT2 " "
51#define INDENT3 " "
52#define INDENT4 " "
53
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080054using namespace android::ftl::flag_operators;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080055using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000056using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080057using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070058using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050059using android::gui::FocusRequest;
60using android::gui::TouchOcclusionMode;
61using android::gui::WindowInfo;
62using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080063using android::os::InputEventInjectionResult;
64using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080065
Garfield Tane84e6f92019-08-29 17:28:41 -070066namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080067
Prabir Pradhancef936d2021-07-21 16:17:52 +000068namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000069// Temporarily releases a held mutex for the lifetime of the instance.
70// Named to match std::scoped_lock
71class scoped_unlock {
72public:
73 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
74 ~scoped_unlock() { mMutex.lock(); }
75
76private:
77 std::mutex& mMutex;
78};
79
Michael Wrightd02c5b62014-02-10 15:10:22 -080080// Default input dispatching timeout if there is no focused application or paused window
81// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080082const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
83 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
84 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080085
86// Amount of time to allow for all pending events to be processed when an app switch
87// key is on the way. This is used to preempt input dispatch and drop input events
88// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000089constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080090
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080091const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080092
Michael Wrightd02c5b62014-02-10 15:10:22 -080093// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000094constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
95
96// Log a warning when an interception call takes longer than this to process.
97constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080098
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -070099// Additional key latency in case a connection is still processing some motion events.
100// This will help with the case when a user touched a button that opens a new window,
101// and gives us the chance to dispatch the key to this new window.
102constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
103
Michael Wrightd02c5b62014-02-10 15:10:22 -0800104// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000105constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
106
Antonio Kantekea47acb2021-12-23 12:41:25 -0800107// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000108constexpr int LOGTAG_INPUT_INTERACTION = 62000;
109constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000110constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000111
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000112inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800113 return systemTime(SYSTEM_TIME_MONOTONIC);
114}
115
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000116inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800117 return value ? "true" : "false";
118}
119
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000120inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000121 if (binder == nullptr) {
122 return "<null>";
123 }
124 return StringPrintf("%p", binder.get());
125}
126
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000127inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700128 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
129 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800130}
131
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000132bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800133 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700134 case AKEY_EVENT_ACTION_DOWN:
135 case AKEY_EVENT_ACTION_UP:
136 return true;
137 default:
138 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139 }
140}
141
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000142bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700143 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144 ALOGE("Key event has invalid action code 0x%x", action);
145 return false;
146 }
147 return true;
148}
149
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000150bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800151 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700152 case AMOTION_EVENT_ACTION_DOWN:
153 case AMOTION_EVENT_ACTION_UP:
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800154 return pointerCount == 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700155 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700156 case AMOTION_EVENT_ACTION_HOVER_ENTER:
157 case AMOTION_EVENT_ACTION_HOVER_MOVE:
158 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800159 return pointerCount >= 1;
160 case AMOTION_EVENT_ACTION_CANCEL:
161 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700162 case AMOTION_EVENT_ACTION_SCROLL:
163 return true;
164 case AMOTION_EVENT_ACTION_POINTER_DOWN:
165 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800166 const int32_t index = MotionEvent::getActionIndex(action);
167 return index >= 0 && index < pointerCount && pointerCount > 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700168 }
169 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
170 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
171 return actionButton != 0;
172 default:
173 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800174 }
175}
176
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000177int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500178 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
179}
180
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000181bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
182 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700183 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800184 ALOGE("Motion event has invalid action code 0x%x", action);
185 return false;
186 }
187 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800188 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %zu.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700189 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800190 return false;
191 }
192 BitSet32 pointerIdBits;
193 for (size_t i = 0; i < pointerCount; i++) {
194 int32_t id = pointerProperties[i].id;
195 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700196 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
197 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800198 return false;
199 }
200 if (pointerIdBits.hasBit(id)) {
201 ALOGE("Motion event has duplicate pointer id %d", id);
202 return false;
203 }
204 pointerIdBits.markBit(id);
205 }
206 return true;
207}
208
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000209std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800210 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000211 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800212 }
213
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000214 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800215 bool first = true;
216 Region::const_iterator cur = region.begin();
217 Region::const_iterator const tail = region.end();
218 while (cur != tail) {
219 if (first) {
220 first = false;
221 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800222 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800224 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800225 cur++;
226 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000227 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800228}
229
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000230std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500231 constexpr size_t maxEntries = 50; // max events to print
232 constexpr size_t skipBegin = maxEntries / 2;
233 const size_t skipEnd = queue.size() - maxEntries / 2;
234 // skip from maxEntries / 2 ... size() - maxEntries/2
235 // only print from 0 .. skipBegin and then from skipEnd .. size()
236
237 std::string dump;
238 for (size_t i = 0; i < queue.size(); i++) {
239 const DispatchEntry& entry = *queue[i];
240 if (i >= skipBegin && i < skipEnd) {
241 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
242 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
243 continue;
244 }
245 dump.append(INDENT4);
246 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800247 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
248 "ms",
249 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500250 ns2ms(currentTime - entry.eventEntry->eventTime));
251 if (entry.deliveryTime != 0) {
252 // This entry was delivered, so add information on how long we've been waiting
253 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
254 }
255 dump.append("\n");
256 }
257 return dump;
258}
259
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700260/**
261 * Find the entry in std::unordered_map by key, and return it.
262 * If the entry is not found, return a default constructed entry.
263 *
264 * Useful when the entries are vectors, since an empty vector will be returned
265 * if the entry is not found.
266 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
267 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700268template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000269V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700270 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700271 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800272}
273
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000274bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700275 if (first == second) {
276 return true;
277 }
278
279 if (first == nullptr || second == nullptr) {
280 return false;
281 }
282
283 return first->getToken() == second->getToken();
284}
285
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000286bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000287 if (first == nullptr || second == nullptr) {
288 return false;
289 }
290 return first->applicationInfo.token != nullptr &&
291 first->applicationInfo.token == second->applicationInfo.token;
292}
293
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800294std::unique_ptr<DispatchEntry> createDispatchEntry(
295 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
296 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700297 if (inputTarget.useDefaultPointerTransform()) {
298 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700299 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700300 inputTarget.displayTransform,
301 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000302 }
303
304 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
305 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
306
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700307 std::vector<PointerCoords> pointerCoords;
308 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000309
310 // Use the first pointer information to normalize all other pointers. This could be any pointer
311 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700312 // uses the transform for the normalized pointer.
313 const ui::Transform& firstPointerTransform =
314 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
315 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000316
317 // Iterate through all pointers in the event to normalize against the first.
318 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
319 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
320 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700321 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000322
323 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700324 // First, apply the current pointer's transform to update the coordinates into
325 // window space.
326 pointerCoords[pointerIndex].transform(currTransform);
327 // Next, apply the inverse transform of the normalized coordinates so the
328 // current coordinates are transformed into the normalized coordinate space.
329 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000330 }
331
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700332 std::unique_ptr<MotionEntry> combinedMotionEntry =
333 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
334 motionEntry.deviceId, motionEntry.source,
335 motionEntry.displayId, motionEntry.policyFlags,
336 motionEntry.action, motionEntry.actionButton,
337 motionEntry.flags, motionEntry.metaState,
338 motionEntry.buttonState, motionEntry.classification,
339 motionEntry.edgeFlags, motionEntry.xPrecision,
340 motionEntry.yPrecision, motionEntry.xCursorPosition,
341 motionEntry.yCursorPosition, motionEntry.downTime,
342 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000343 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000344
345 if (motionEntry.injectionState) {
346 combinedMotionEntry->injectionState = motionEntry.injectionState;
347 combinedMotionEntry->injectionState->refCount += 1;
348 }
349
350 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700351 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700352 firstPointerTransform, inputTarget.displayTransform,
353 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000354 return dispatchEntry;
355}
356
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000357status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
358 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700359 std::unique_ptr<InputChannel> uniqueServerChannel;
360 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
361
362 serverChannel = std::move(uniqueServerChannel);
363 return result;
364}
365
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500366template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000367bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500368 if (lhs == nullptr && rhs == nullptr) {
369 return true;
370 }
371 if (lhs == nullptr || rhs == nullptr) {
372 return false;
373 }
374 return *lhs == *rhs;
375}
376
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000377KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000378 KeyEvent event;
379 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
380 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
381 entry.repeatCount, entry.downTime, entry.eventTime);
382 return event;
383}
384
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000385bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000386 // Do not keep track of gesture monitors. They receive every event and would disproportionately
387 // affect the statistics.
388 if (connection.monitor) {
389 return false;
390 }
391 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
392 if (!connection.responsive) {
393 return false;
394 }
395 return true;
396}
397
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000398bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000399 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
400 const int32_t& inputEventId = eventEntry.id;
401 if (inputEventId != dispatchEntry.resolvedEventId) {
402 // Event was transmuted
403 return false;
404 }
405 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
406 return false;
407 }
408 // Only track latency for events that originated from hardware
409 if (eventEntry.isSynthesized()) {
410 return false;
411 }
412 const EventEntry::Type& inputEventEntryType = eventEntry.type;
413 if (inputEventEntryType == EventEntry::Type::KEY) {
414 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
415 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
416 return false;
417 }
418 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
419 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
420 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
421 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
422 return false;
423 }
424 } else {
425 // Not a key or a motion
426 return false;
427 }
428 if (!shouldReportMetricsForConnection(connection)) {
429 return false;
430 }
431 return true;
432}
433
Prabir Pradhancef936d2021-07-21 16:17:52 +0000434/**
435 * Connection is responsive if it has no events in the waitQueue that are older than the
436 * current time.
437 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000438bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000439 const nsecs_t currentTime = now();
440 for (const DispatchEntry* entry : connection.waitQueue) {
441 if (entry->timeoutTime < currentTime) {
442 return false;
443 }
444 }
445 return true;
446}
447
Antonio Kantekf16f2832021-09-28 04:39:20 +0000448// Returns true if the event type passed as argument represents a user activity.
449bool isUserActivityEvent(const EventEntry& eventEntry) {
450 switch (eventEntry.type) {
451 case EventEntry::Type::FOCUS:
452 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
453 case EventEntry::Type::DRAG:
454 case EventEntry::Type::TOUCH_MODE_CHANGED:
455 case EventEntry::Type::SENSOR:
456 case EventEntry::Type::CONFIGURATION_CHANGED:
457 return false;
458 case EventEntry::Type::DEVICE_RESET:
459 case EventEntry::Type::KEY:
460 case EventEntry::Type::MOTION:
461 return true;
462 }
463}
464
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800465// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhand65552b2021-10-07 11:23:50 -0700466bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, int32_t x, int32_t y,
467 bool isStylus) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800468 const auto inputConfig = windowInfo.inputConfig;
469 if (windowInfo.displayId != displayId ||
470 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800471 return false;
472 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700473 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800474 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800475 return false;
476 }
Prabir Pradhan06349042022-02-04 09:19:17 -0800477 if (!windowInfo.touchableRegionContainsPoint(x, y)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800478 return false;
479 }
480 return true;
481}
482
Prabir Pradhand65552b2021-10-07 11:23:50 -0700483bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
484 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000485 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700486}
487
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800488// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000489// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
490// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
491// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800492// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000493bool canReceiveForegroundTouches(const WindowInfo& info) {
494 // A non-touchable window can still receive touch events (e.g. in the case of
495 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
496 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
497}
498
Antonio Kantek48710e42022-03-24 14:19:30 -0700499bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
500 if (windowHandle == nullptr) {
501 return false;
502 }
503 const WindowInfo* windowInfo = windowHandle->getInfo();
504 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
505 return true;
506 }
507 return false;
508}
509
Prabir Pradhan5735a322022-04-11 17:23:34 +0000510// Checks targeted injection using the window's owner's uid.
511// Returns an empty string if an entry can be sent to the given window, or an error message if the
512// entry is a targeted injection whose uid target doesn't match the window owner.
513std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
514 const EventEntry& entry) {
515 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
516 // The event was not injected, or the injected event does not target a window.
517 return {};
518 }
519 const int32_t uid = *entry.injectionState->targetUid;
520 if (window == nullptr) {
521 return StringPrintf("No valid window target for injection into uid %d.", uid);
522 }
523 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
524 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
525 "owned by uid %d.",
526 uid, window->getName().c_str(), window->getInfo()->ownerUid);
527 }
528 return {};
529}
530
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700531Point resolveTouchedPosition(const MotionEntry& entry) {
532 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
533 // Always dispatch mouse events to cursor position.
534 if (isFromMouse) {
535 return Point(static_cast<int32_t>(entry.xCursorPosition),
536 static_cast<int32_t>(entry.yCursorPosition));
537 }
538
539 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
540 return Point(static_cast<int32_t>(
541 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X)),
542 static_cast<int32_t>(
543 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)));
544}
545
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700546std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
547 if (eventEntry.type == EventEntry::Type::KEY) {
548 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
549 return keyEntry.downTime;
550 } else if (eventEntry.type == EventEntry::Type::MOTION) {
551 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
552 return motionEntry.downTime;
553 }
554 return std::nullopt;
555}
556
Siarhei Vishniakoud57302f2022-11-08 11:12:29 -0800557/**
558 * Compare the old touch state to the new touch state, and generate the corresponding touched
559 * windows (== input targets).
560 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
561 * If the pointer just entered the new window, produce HOVER_ENTER.
562 * For pointers remaining in the window, produce HOVER_MOVE.
563 */
564std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
565 const TouchState& newTouchState,
566 const MotionEntry& entry) {
567 std::vector<TouchedWindow> out;
568 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
569 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
570 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
571 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
572 // Not a hover event - don't need to do anything
573 return out;
574 }
575
576 // We should consider all hovering pointers here. But for now, just use the first one
577 const int32_t pointerId = entry.pointerProperties[0].id;
578
579 std::set<sp<WindowInfoHandle>> oldWindows;
580 if (oldState != nullptr) {
581 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
582 }
583
584 std::set<sp<WindowInfoHandle>> newWindows =
585 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
586
587 // If the pointer is no longer in the new window set, send HOVER_EXIT.
588 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
589 if (newWindows.find(oldWindow) == newWindows.end()) {
590 TouchedWindow touchedWindow;
591 touchedWindow.windowHandle = oldWindow;
592 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
593 touchedWindow.pointerIds.markBit(pointerId);
594 out.push_back(touchedWindow);
595 }
596 }
597
598 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
599 TouchedWindow touchedWindow;
600 touchedWindow.windowHandle = newWindow;
601 if (oldWindows.find(newWindow) == oldWindows.end()) {
602 // Any windows that have this pointer now, and didn't have it before, should get
603 // HOVER_ENTER
604 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
605 } else {
606 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
607 LOG_ALWAYS_FATAL_IF(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE);
608 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
609 }
610 touchedWindow.pointerIds.markBit(pointerId);
611 out.push_back(touchedWindow);
612 }
613 return out;
614}
615
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000616} // namespace
617
Michael Wrightd02c5b62014-02-10 15:10:22 -0800618// --- InputDispatcher ---
619
Garfield Tan00f511d2019-06-12 16:55:40 -0700620InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800621 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
622
623InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
624 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700625 : mPolicy(policy),
626 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700627 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800628 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700629 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700630 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700631 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800632 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700633 mDispatchEnabled(false),
634 mDispatchFrozen(false),
635 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100636 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000637 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800638 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800639 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000640 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000641 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700642 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800643 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800644
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700645 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700646#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700647 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700648#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700649 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650 policy->getDispatcherConfiguration(&mConfig);
651}
652
653InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000654 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800655
Prabir Pradhancef936d2021-07-21 16:17:52 +0000656 resetKeyRepeatLocked();
657 releasePendingEventLocked();
658 drainInboundQueueLocked();
659 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800660
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000661 while (!mConnectionsByToken.empty()) {
662 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000663 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
664 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800665 }
666}
667
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700668status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700669 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700670 return ALREADY_EXISTS;
671 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700672 mThread = std::make_unique<InputThread>(
673 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
674 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700675}
676
677status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700678 if (mThread && mThread->isCallingThread()) {
679 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700680 return INVALID_OPERATION;
681 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700682 mThread.reset();
683 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700684}
685
Michael Wrightd02c5b62014-02-10 15:10:22 -0800686void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700687 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800689 std::scoped_lock _l(mLock);
690 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800691
692 // Run a dispatch loop if there are no pending commands.
693 // The dispatch loop might enqueue commands to run afterwards.
694 if (!haveCommandsLocked()) {
695 dispatchOnceInnerLocked(&nextWakeupTime);
696 }
697
698 // Run all pending commands if there are any.
699 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000700 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700701 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800702 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800703
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700704 // If we are still waiting for ack on some events,
705 // we might have to wake up earlier to check if an app is anr'ing.
706 const nsecs_t nextAnrCheck = processAnrsLocked();
707 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
708
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800709 // We are about to enter an infinitely long sleep, because we have no commands or
710 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700711 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800712 mDispatcherEnteredIdle.notify_all();
713 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714 } // release lock
715
716 // Wait for callback or timeout or wake. (make sure we round up, not down)
717 nsecs_t currentTime = now();
718 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
719 mLooper->pollOnce(timeoutMillis);
720}
721
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700722/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500723 * Raise ANR if there is no focused window.
724 * Before the ANR is raised, do a final state check:
725 * 1. The currently focused application must be the same one we are waiting for.
726 * 2. Ensure we still don't have a focused window.
727 */
728void InputDispatcher::processNoFocusedWindowAnrLocked() {
729 // Check if the application that we are waiting for is still focused.
730 std::shared_ptr<InputApplicationHandle> focusedApplication =
731 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
732 if (focusedApplication == nullptr ||
733 focusedApplication->getApplicationToken() !=
734 mAwaitedFocusedApplication->getApplicationToken()) {
735 // Unexpected because we should have reset the ANR timer when focused application changed
736 ALOGE("Waited for a focused window, but focused application has already changed to %s",
737 focusedApplication->getName().c_str());
738 return; // The focused application has changed.
739 }
740
chaviw98318de2021-05-19 16:45:23 -0500741 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500742 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
743 if (focusedWindowHandle != nullptr) {
744 return; // We now have a focused window. No need for ANR.
745 }
746 onAnrLocked(mAwaitedFocusedApplication);
747}
748
749/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700750 * Check if any of the connections' wait queues have events that are too old.
751 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
752 * Return the time at which we should wake up next.
753 */
754nsecs_t InputDispatcher::processAnrsLocked() {
755 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700756 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700757 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
758 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
759 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500760 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700761 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500762 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700763 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700764 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500765 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700766 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
767 }
768 }
769
770 // Check if any connection ANRs are due
771 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
772 if (currentTime < nextAnrCheck) { // most likely scenario
773 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
774 }
775
776 // If we reached here, we have an unresponsive connection.
777 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
778 if (connection == nullptr) {
779 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
780 return nextAnrCheck;
781 }
782 connection->responsive = false;
783 // Stop waking up for this unresponsive connection
784 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000785 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700786 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700787}
788
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800789std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
790 const sp<Connection>& connection) {
791 if (connection->monitor) {
792 return mMonitorDispatchingTimeout;
793 }
794 const sp<WindowInfoHandle> window =
795 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700796 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500797 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700798 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500799 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700800}
801
Michael Wrightd02c5b62014-02-10 15:10:22 -0800802void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
803 nsecs_t currentTime = now();
804
Jeff Browndc5992e2014-04-11 01:27:26 -0700805 // Reset the key repeat timer whenever normal dispatch is suspended while the
806 // device is in a non-interactive state. This is to ensure that we abort a key
807 // repeat if the device is just coming out of sleep.
808 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800809 resetKeyRepeatLocked();
810 }
811
812 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
813 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100814 if (DEBUG_FOCUS) {
815 ALOGD("Dispatch frozen. Waiting some more.");
816 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800817 return;
818 }
819
820 // Optimize latency of app switches.
821 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
822 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
823 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
824 if (mAppSwitchDueTime < *nextWakeupTime) {
825 *nextWakeupTime = mAppSwitchDueTime;
826 }
827
828 // Ready to start a new event.
829 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700830 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700831 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800832 if (isAppSwitchDue) {
833 // The inbound queue is empty so the app switch key we were waiting
834 // for will never arrive. Stop waiting for it.
835 resetPendingAppSwitchLocked(false);
836 isAppSwitchDue = false;
837 }
838
839 // Synthesize a key repeat if appropriate.
840 if (mKeyRepeatState.lastKeyEntry) {
841 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
842 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
843 } else {
844 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
845 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
846 }
847 }
848 }
849
850 // Nothing to do if there is no pending event.
851 if (!mPendingEvent) {
852 return;
853 }
854 } else {
855 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700856 mPendingEvent = mInboundQueue.front();
857 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858 traceInboundQueueLengthLocked();
859 }
860
861 // Poke user activity for this event.
862 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700863 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865 }
866
867 // Now we have an event to dispatch.
868 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700869 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700871 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700873 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700875 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800876 }
877
878 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700879 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 }
881
882 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700883 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700884 const ConfigurationChangedEntry& typedEntry =
885 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700886 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700887 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700888 break;
889 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700891 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700892 const DeviceResetEntry& typedEntry =
893 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700894 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700895 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700896 break;
897 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100899 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700900 std::shared_ptr<FocusEntry> typedEntry =
901 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100902 dispatchFocusLocked(currentTime, typedEntry);
903 done = true;
904 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
905 break;
906 }
907
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700908 case EventEntry::Type::TOUCH_MODE_CHANGED: {
909 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
910 dispatchTouchModeChangeLocked(currentTime, typedEntry);
911 done = true;
912 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
913 break;
914 }
915
Prabir Pradhan99987712020-11-10 18:43:05 -0800916 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
917 const auto typedEntry =
918 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
919 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
920 done = true;
921 break;
922 }
923
arthurhungb89ccb02020-12-30 16:19:01 +0800924 case EventEntry::Type::DRAG: {
925 std::shared_ptr<DragEntry> typedEntry =
926 std::static_pointer_cast<DragEntry>(mPendingEvent);
927 dispatchDragLocked(currentTime, typedEntry);
928 done = true;
929 break;
930 }
931
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700932 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700933 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700934 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700935 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700936 resetPendingAppSwitchLocked(true);
937 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700938 } else if (dropReason == DropReason::NOT_DROPPED) {
939 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700940 }
941 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700942 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700943 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700944 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700945 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
946 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700947 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700948 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700949 break;
950 }
951
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700952 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700953 std::shared_ptr<MotionEntry> motionEntry =
954 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700955 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
956 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700958 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700959 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700960 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700961 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
962 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700963 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700964 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700965 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966 }
Chris Yef59a2f42020-10-16 12:55:26 -0700967
968 case EventEntry::Type::SENSOR: {
969 std::shared_ptr<SensorEntry> sensorEntry =
970 std::static_pointer_cast<SensorEntry>(mPendingEvent);
971 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
972 dropReason = DropReason::APP_SWITCH;
973 }
974 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
975 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
976 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
977 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
978 dropReason = DropReason::STALE;
979 }
980 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
981 done = true;
982 break;
983 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984 }
985
986 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700987 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700988 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 }
Michael Wright3a981722015-06-10 15:26:13 +0100990 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991
992 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -0700993 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 }
995}
996
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800997bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
998 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
999}
1000
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001001/**
1002 * Return true if the events preceding this incoming motion event should be dropped
1003 * Return false otherwise (the default behaviour)
1004 */
1005bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001006 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001007 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001008
1009 // Optimize case where the current application is unresponsive and the user
1010 // decides to touch a window in a different application.
1011 // If the application takes too long to catch up then we drop all events preceding
1012 // the touch into the other window.
1013 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001014 const int32_t displayId = motionEntry.displayId;
1015 const auto [x, y] = resolveTouchedPosition(motionEntry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07001016 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001017
chaviw98318de2021-05-19 16:45:23 -05001018 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -07001019 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001020 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001021 touchedWindowHandle->getApplicationToken() !=
1022 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001023 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001024 ALOGI("Pruning input queue because user touched a different application while waiting "
1025 "for %s",
1026 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001027 return true;
1028 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001029
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001030 // Alternatively, maybe there's a spy window that could handle this event.
1031 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1032 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1033 for (const auto& windowHandle : touchedSpies) {
1034 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001035 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001036 // This spy window could take more input. Drop all events preceding this
1037 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001038 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001039 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001040 mAwaitedFocusedApplication->getName().c_str());
1041 return true;
1042 }
1043 }
1044 }
1045
1046 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1047 // yet been processed by some connections, the dispatcher will wait for these motion
1048 // events to be processed before dispatching the key event. This is because these motion events
1049 // may cause a new window to be launched, which the user might expect to receive focus.
1050 // To prevent waiting forever for such events, just send the key to the currently focused window
1051 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1052 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1053 "just send the pending key event to the focused window.");
1054 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001055 }
1056 return false;
1057}
1058
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001059bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001060 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001061 mInboundQueue.push_back(std::move(newEntry));
1062 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001063 traceInboundQueueLengthLocked();
1064
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001065 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001066 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001067 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1068 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001069 // Optimize app switch latency.
1070 // If the application takes too long to catch up then we drop all events preceding
1071 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001072 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001073 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001074 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001075 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001076 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001077 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001078 if (DEBUG_APP_SWITCH) {
1079 ALOGD("App switch is pending!");
1080 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001081 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001082 mAppSwitchSawKeyDown = false;
1083 needWake = true;
1084 }
1085 }
1086 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001087
1088 // If a new up event comes in, and the pending event with same key code has been asked
1089 // to try again later because of the policy. We have to reset the intercept key wake up
1090 // time for it may have been handled in the policy and could be dropped.
1091 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1092 mPendingEvent->type == EventEntry::Type::KEY) {
1093 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1094 if (pendingKey.keyCode == keyEntry.keyCode &&
1095 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001096 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1097 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001098 pendingKey.interceptKeyWakeupTime = 0;
1099 needWake = true;
1100 }
1101 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001102 break;
1103 }
1104
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001105 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001106 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1107 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001108 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1109 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001110 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001111 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001112 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001113 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001114 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001115 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1116 break;
1117 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001118 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001119 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001120 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001121 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001122 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1123 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001124 // nothing to do
1125 break;
1126 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127 }
1128
1129 return needWake;
1130}
1131
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001132void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001133 // Do not store sensor event in recent queue to avoid flooding the queue.
1134 if (entry->type != EventEntry::Type::SENSOR) {
1135 mRecentQueue.push_back(entry);
1136 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001137 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001138 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139 }
1140}
1141
chaviw98318de2021-05-19 16:45:23 -05001142sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1143 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001144 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001145 bool addOutsideTargets,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07001146 bool ignoreDragWindow) const {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001147 if (addOutsideTargets && touchState == nullptr) {
1148 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001149 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001150 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001151 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001152 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001153 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001154 continue;
1155 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001156
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001157 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001158 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001159 return windowHandle;
1160 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001161
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001162 if (addOutsideTargets &&
1163 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001164 touchState->addOrUpdateWindow(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001165 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001166 }
1167 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001168 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169}
1170
Prabir Pradhand65552b2021-10-07 11:23:50 -07001171std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1172 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001173 // Traverse windows from front to back and gather the touched spy windows.
1174 std::vector<sp<WindowInfoHandle>> spyWindows;
1175 const auto& windowHandles = getWindowHandlesLocked(displayId);
1176 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1177 const WindowInfo& info = *windowHandle->getInfo();
1178
Prabir Pradhand65552b2021-10-07 11:23:50 -07001179 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001180 continue;
1181 }
1182 if (!info.isSpy()) {
1183 // The first touched non-spy window was found, so return the spy windows touched so far.
1184 return spyWindows;
1185 }
1186 spyWindows.push_back(windowHandle);
1187 }
1188 return spyWindows;
1189}
1190
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001191void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192 const char* reason;
1193 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001194 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001195 if (DEBUG_INBOUND_EVENT_DETAILS) {
1196 ALOGD("Dropped event because policy consumed it.");
1197 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001198 reason = "inbound event was dropped because the policy consumed it";
1199 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001200 case DropReason::DISABLED:
1201 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001202 ALOGI("Dropped event because input dispatch is disabled.");
1203 }
1204 reason = "inbound event was dropped because input dispatch is disabled";
1205 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001206 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001207 ALOGI("Dropped event because of pending overdue app switch.");
1208 reason = "inbound event was dropped because of pending overdue app switch";
1209 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001210 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001211 ALOGI("Dropped event because the current application is not responding and the user "
1212 "has started interacting with a different application.");
1213 reason = "inbound event was dropped because the current application is not responding "
1214 "and the user has started interacting with a different application";
1215 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001216 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001217 ALOGI("Dropped event because it is stale.");
1218 reason = "inbound event was dropped because it is stale";
1219 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001220 case DropReason::NO_POINTER_CAPTURE:
1221 ALOGI("Dropped event because there is no window with Pointer Capture.");
1222 reason = "inbound event was dropped because there is no window with Pointer Capture";
1223 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001224 case DropReason::NOT_DROPPED: {
1225 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001226 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 }
1229
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001230 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001231 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001232 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001234 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001236 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001237 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1238 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001239 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001240 synthesizeCancelationEventsForAllConnectionsLocked(options);
1241 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001242 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1243 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001244 synthesizeCancelationEventsForAllConnectionsLocked(options);
1245 }
1246 break;
1247 }
Chris Yef59a2f42020-10-16 12:55:26 -07001248 case EventEntry::Type::SENSOR: {
1249 break;
1250 }
arthurhungb89ccb02020-12-30 16:19:01 +08001251 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1252 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001253 break;
1254 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001255 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001256 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001257 case EventEntry::Type::CONFIGURATION_CHANGED:
1258 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001259 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001260 break;
1261 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 }
1263}
1264
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001265static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001266 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1267 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268}
1269
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001270bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1271 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1272 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1273 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274}
1275
1276bool InputDispatcher::isAppSwitchPendingLocked() {
Colin Cross5b799302022-10-18 21:52:41 -07001277 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278}
1279
1280void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001281 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001283 if (DEBUG_APP_SWITCH) {
1284 if (handled) {
1285 ALOGD("App switch has arrived.");
1286 } else {
1287 ALOGD("App switch was abandoned.");
1288 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290}
1291
Michael Wrightd02c5b62014-02-10 15:10:22 -08001292bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001293 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294}
1295
Prabir Pradhancef936d2021-07-21 16:17:52 +00001296bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001297 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298 return false;
1299 }
1300
1301 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001302 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001303 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001304 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1305 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001306 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307 return true;
1308}
1309
Prabir Pradhancef936d2021-07-21 16:17:52 +00001310void InputDispatcher::postCommandLocked(Command&& command) {
1311 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001312}
1313
1314void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001315 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001316 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001317 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 releaseInboundEventLocked(entry);
1319 }
1320 traceInboundQueueLengthLocked();
1321}
1322
1323void InputDispatcher::releasePendingEventLocked() {
1324 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001326 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001327 }
1328}
1329
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001330void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001332 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001333 if (DEBUG_DISPATCH_CYCLE) {
1334 ALOGD("Injected inbound event was dropped.");
1335 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001336 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 }
1338 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001339 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 }
1341 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001342}
1343
1344void InputDispatcher::resetKeyRepeatLocked() {
1345 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001346 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001347 }
1348}
1349
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001350std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1351 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352
Michael Wright2e732952014-09-24 13:26:59 -07001353 uint32_t policyFlags = entry->policyFlags &
1354 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001356 std::shared_ptr<KeyEntry> newEntry =
1357 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1358 entry->source, entry->displayId, policyFlags, entry->action,
1359 entry->flags, entry->keyCode, entry->scanCode,
1360 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001361
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001362 newEntry->syntheticRepeat = true;
1363 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001365 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366}
1367
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001368bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001369 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001370 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1371 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001373
1374 // Reset key repeating in case a keyboard device was added or removed or something.
1375 resetKeyRepeatLocked();
1376
1377 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001378 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1379 scoped_unlock unlock(mLock);
1380 mPolicy->notifyConfigurationChanged(eventTime);
1381 };
1382 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001383 return true;
1384}
1385
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001386bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1387 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001388 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1389 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1390 entry.deviceId);
1391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001392
liushenxiang42232912021-05-21 20:24:09 +08001393 // Reset key repeating in case a keyboard device was disabled or enabled.
1394 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1395 resetKeyRepeatLocked();
1396 }
1397
Michael Wrightfb04fd52022-11-24 22:31:11 +00001398 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001399 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400 synthesizeCancelationEventsForAllConnectionsLocked(options);
1401 return true;
1402}
1403
Vishnu Nairad321cd2020-08-20 16:40:21 -07001404void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001405 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001406 if (mPendingEvent != nullptr) {
1407 // Move the pending event to the front of the queue. This will give the chance
1408 // for the pending event to get dispatched to the newly focused window
1409 mInboundQueue.push_front(mPendingEvent);
1410 mPendingEvent = nullptr;
1411 }
1412
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001413 std::unique_ptr<FocusEntry> focusEntry =
1414 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1415 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001416
1417 // This event should go to the front of the queue, but behind all other focus events
1418 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001419 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001420 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001421 [](const std::shared_ptr<EventEntry>& event) {
1422 return event->type == EventEntry::Type::FOCUS;
1423 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001424
1425 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001426 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001427}
1428
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001429void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001430 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001431 if (channel == nullptr) {
1432 return; // Window has gone away
1433 }
1434 InputTarget target;
1435 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001436 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001437 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001438 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1439 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001440 std::string reason = std::string("reason=").append(entry->reason);
1441 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001442 dispatchEventLocked(currentTime, entry, {target});
1443}
1444
Prabir Pradhan99987712020-11-10 18:43:05 -08001445void InputDispatcher::dispatchPointerCaptureChangedLocked(
1446 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1447 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001448 dropReason = DropReason::NOT_DROPPED;
1449
Prabir Pradhan99987712020-11-10 18:43:05 -08001450 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001451 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001452
1453 if (entry->pointerCaptureRequest.enable) {
1454 // Enable Pointer Capture.
1455 if (haveWindowWithPointerCapture &&
1456 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001457 // This can happen if pointer capture is disabled and re-enabled before we notify the
1458 // app of the state change, so there is no need to notify the app.
1459 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1460 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001461 }
1462 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001463 // This can happen if a window requests capture and immediately releases capture.
1464 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001465 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001466 return;
1467 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001468 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1469 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1470 return;
1471 }
1472
Vishnu Nairc519ff72021-01-21 08:23:08 -08001473 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001474 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1475 mWindowTokenWithPointerCapture = token;
1476 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001477 // Disable Pointer Capture.
1478 // We do not check if the sequence number matches for requests to disable Pointer Capture
1479 // for two reasons:
1480 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1481 // to disable capture with the same sequence number: one generated by
1482 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1483 // Capture being disabled in InputReader.
1484 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1485 // actual Pointer Capture state that affects events being generated by input devices is
1486 // in InputReader.
1487 if (!haveWindowWithPointerCapture) {
1488 // Pointer capture was already forcefully disabled because of focus change.
1489 dropReason = DropReason::NOT_DROPPED;
1490 return;
1491 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001492 token = mWindowTokenWithPointerCapture;
1493 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001494 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001495 setPointerCaptureLocked(false);
1496 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001497 }
1498
1499 auto channel = getInputChannelLocked(token);
1500 if (channel == nullptr) {
1501 // Window has gone away, clean up Pointer Capture state.
1502 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001503 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001504 setPointerCaptureLocked(false);
1505 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001506 return;
1507 }
1508 InputTarget target;
1509 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001510 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001511 entry->dispatchInProgress = true;
1512 dispatchEventLocked(currentTime, entry, {target});
1513
1514 dropReason = DropReason::NOT_DROPPED;
1515}
1516
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001517void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1518 const std::shared_ptr<TouchModeEntry>& entry) {
1519 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001520 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001521 if (windowHandles.empty()) {
1522 return;
1523 }
1524 const std::vector<InputTarget> inputTargets =
1525 getInputTargetsFromWindowHandlesLocked(windowHandles);
1526 if (inputTargets.empty()) {
1527 return;
1528 }
1529 entry->dispatchInProgress = true;
1530 dispatchEventLocked(currentTime, entry, inputTargets);
1531}
1532
1533std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1534 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1535 std::vector<InputTarget> inputTargets;
1536 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001537 const sp<IBinder>& token = handle->getToken();
1538 if (token == nullptr) {
1539 continue;
1540 }
1541 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1542 if (channel == nullptr) {
1543 continue; // Window has gone away
1544 }
1545 InputTarget target;
1546 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001547 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001548 inputTargets.push_back(target);
1549 }
1550 return inputTargets;
1551}
1552
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001553bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001554 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001556 if (!entry->dispatchInProgress) {
1557 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1558 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1559 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1560 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001561 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562 // We have seen two identical key downs in a row which indicates that the device
1563 // driver is automatically generating key repeats itself. We take note of the
1564 // repeat here, but we disable our own next key repeat timer since it is clear that
1565 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001566 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1567 // Make sure we don't get key down from a different device. If a different
1568 // device Id has same key pressed down, the new device Id will replace the
1569 // current one to hold the key repeat with repeat count reset.
1570 // In the future when got a KEY_UP on the device id, drop it and do not
1571 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1573 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001574 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575 } else {
1576 // Not a repeat. Save key down state in case we do see a repeat later.
1577 resetKeyRepeatLocked();
1578 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1579 }
1580 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001581 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1582 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001583 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001584 if (DEBUG_INBOUND_EVENT_DETAILS) {
1585 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1586 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001587 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001588 resetKeyRepeatLocked();
1589 }
1590
1591 if (entry->repeatCount == 1) {
1592 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1593 } else {
1594 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1595 }
1596
1597 entry->dispatchInProgress = true;
1598
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001599 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 }
1601
1602 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001603 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604 if (currentTime < entry->interceptKeyWakeupTime) {
1605 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1606 *nextWakeupTime = entry->interceptKeyWakeupTime;
1607 }
1608 return false; // wait until next wakeup
1609 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001610 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001611 entry->interceptKeyWakeupTime = 0;
1612 }
1613
1614 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001615 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001616 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001617 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001618 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001619
1620 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1621 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1622 };
1623 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001624 return false; // wait for the command to run
1625 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001626 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001627 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001628 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001629 if (*dropReason == DropReason::NOT_DROPPED) {
1630 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001631 }
1632 }
1633
1634 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001635 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001636 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001637 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1638 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001639 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001640 return true;
1641 }
1642
1643 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001644 InputEventInjectionResult injectionResult;
1645 sp<WindowInfoHandle> focusedWindow =
1646 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1647 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001648 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 return false;
1650 }
1651
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001652 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001653 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 return true;
1655 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001656 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1657
1658 std::vector<InputTarget> inputTargets;
1659 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001660 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001661 BitSet32(0), getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001662
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001663 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001664 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665
1666 // Dispatch the key.
1667 dispatchEventLocked(currentTime, entry, inputTargets);
1668 return true;
1669}
1670
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001671void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001672 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1673 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1674 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1675 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1676 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1677 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1678 entry.metaState, entry.repeatCount, entry.downTime);
1679 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680}
1681
Prabir Pradhancef936d2021-07-21 16:17:52 +00001682void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1683 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001684 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001685 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1686 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1687 "source=0x%x, sensorType=%s",
1688 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001689 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001690 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001691 auto command = [this, entry]() REQUIRES(mLock) {
1692 scoped_unlock unlock(mLock);
1693
1694 if (entry->accuracyChanged) {
1695 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1696 }
1697 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1698 entry->hwTimestamp, entry->values);
1699 };
1700 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001701}
1702
1703bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001704 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1705 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001706 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001707 }
Chris Yef59a2f42020-10-16 12:55:26 -07001708 { // acquire lock
1709 std::scoped_lock _l(mLock);
1710
1711 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1712 std::shared_ptr<EventEntry> entry = *it;
1713 if (entry->type == EventEntry::Type::SENSOR) {
1714 it = mInboundQueue.erase(it);
1715 releaseInboundEventLocked(entry);
1716 }
1717 }
1718 }
1719 return true;
1720}
1721
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001722bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001723 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001724 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001725 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001726 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001727 entry->dispatchInProgress = true;
1728
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001729 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 }
1731
1732 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001733 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001734 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001735 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1736 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 return true;
1738 }
1739
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001740 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741
1742 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001743 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744
1745 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001746 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 if (isPointerEvent) {
1748 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001749
1750 if (mDragState &&
1751 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1752 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1753 pilferPointersLocked(mDragState->dragWindow->getToken());
1754 }
1755
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001756 std::vector<TouchedWindow> touchedWindows =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001757 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001758 /*byref*/ injectionResult);
1759 for (const TouchedWindow& touchedWindow : touchedWindows) {
1760 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED,
1761 "Shouldn't be adding window if the injection didn't succeed.");
1762 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1763 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
1764 inputTargets);
1765 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766 } else {
1767 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001768 sp<WindowInfoHandle> focusedWindow =
1769 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1770 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1771 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1772 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001773 InputTarget::Flags::FOREGROUND |
1774 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001775 BitSet32(0), getDownTime(*entry), inputTargets);
1776 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001778 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001779 return false;
1780 }
1781
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001782 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001783 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001784 return true;
1785 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001786 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001787 CancelationOptions::Mode mode(
1788 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1789 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001790 CancelationOptions options(mode, "input event injection failed");
1791 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792 return true;
1793 }
1794
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001795 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001796 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797
1798 // Dispatch the motion.
1799 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001800 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001801 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802 synthesizeCancelationEventsForAllConnectionsLocked(options);
1803 }
1804 dispatchEventLocked(currentTime, entry, inputTargets);
1805 return true;
1806}
1807
chaviw98318de2021-05-19 16:45:23 -05001808void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001809 bool isExiting, const int32_t rawX,
1810 const int32_t rawY) {
1811 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001812 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001813 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1814 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001815
1816 enqueueInboundEventLocked(std::move(dragEntry));
1817}
1818
1819void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1820 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1821 if (channel == nullptr) {
1822 return; // Window has gone away
1823 }
1824 InputTarget target;
1825 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001826 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001827 entry->dispatchInProgress = true;
1828 dispatchEventLocked(currentTime, entry, {target});
1829}
1830
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001831void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001832 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001833 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001834 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001835 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001836 "metaState=0x%x, buttonState=0x%x,"
1837 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001838 prefix, entry.eventTime, entry.deviceId,
1839 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1840 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1841 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1842 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001844 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1845 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1846 "x=%f, y=%f, pressure=%f, size=%f, "
1847 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1848 "orientation=%f",
1849 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1850 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1851 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1852 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1853 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1854 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1855 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1856 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1857 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1858 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1859 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861}
1862
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001863void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1864 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001865 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001866 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001867 if (DEBUG_DISPATCH_CYCLE) {
1868 ALOGD("dispatchEventToCurrentInputTargets");
1869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001871 updateInteractionTokensLocked(*eventEntry, inputTargets);
1872
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1874
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001875 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001877 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001878 sp<Connection> connection =
1879 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001880 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001881 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001883 if (DEBUG_FOCUS) {
1884 ALOGD("Dropping event delivery to target with channel '%s' because it "
1885 "is no longer registered with the input dispatcher.",
1886 inputTarget.inputChannel->getName().c_str());
1887 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 }
1889 }
1890}
1891
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001892void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1893 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1894 // If the policy decides to close the app, we will get a channel removal event via
1895 // unregisterInputChannel, and will clean up the connection that way. We are already not
1896 // sending new pointers to the connection when it blocked, but focused events will continue to
1897 // pile up.
1898 ALOGW("Canceling events for %s because it is unresponsive",
1899 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001900 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001901 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001902 "application not responding");
1903 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 }
1905}
1906
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001907void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001908 if (DEBUG_FOCUS) {
1909 ALOGD("Resetting ANR timeouts.");
1910 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911
1912 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001913 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001914 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915}
1916
Tiger Huang721e26f2018-07-24 22:26:19 +08001917/**
1918 * Get the display id that the given event should go to. If this event specifies a valid display id,
1919 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1920 * Focused display is the display that the user most recently interacted with.
1921 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001922int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001923 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001924 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001925 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001926 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1927 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001928 break;
1929 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001930 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001931 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1932 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001933 break;
1934 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001935 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001936 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001937 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001938 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001939 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001940 case EventEntry::Type::SENSOR:
1941 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001942 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001943 return ADISPLAY_ID_NONE;
1944 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001945 }
1946 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1947}
1948
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001949bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1950 const char* focusedWindowName) {
1951 if (mAnrTracker.empty()) {
1952 // already processed all events that we waited for
1953 mKeyIsWaitingForEventsTimeout = std::nullopt;
1954 return false;
1955 }
1956
1957 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1958 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001959 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001960 mKeyIsWaitingForEventsTimeout = currentTime +
1961 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1962 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001963 return true;
1964 }
1965
1966 // We still have pending events, and already started the timer
1967 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1968 return true; // Still waiting
1969 }
1970
1971 // Waited too long, and some connection still hasn't processed all motions
1972 // Just send the key to the focused window
1973 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1974 focusedWindowName);
1975 mKeyIsWaitingForEventsTimeout = std::nullopt;
1976 return false;
1977}
1978
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001979sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
1980 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
1981 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001982 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001983 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984
Tiger Huang721e26f2018-07-24 22:26:19 +08001985 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001986 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001987 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001988 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1989
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990 // If there is no currently focused window and no focused application
1991 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001992 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1993 ALOGI("Dropping %s event because there is no focused window or focused application in "
1994 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001995 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001996 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997 }
1998
Vishnu Nair062a8672021-09-03 16:07:44 -07001999 // Drop key events if requested by input feature
2000 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002001 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002002 }
2003
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002004 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2005 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2006 // start interacting with another application via touch (app switch). This code can be removed
2007 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2008 // an app is expected to have a focused window.
2009 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2010 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2011 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002012 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2013 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2014 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002015 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002016 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002017 ALOGW("Waiting because no window has focus but %s may eventually add a "
2018 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002019 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002020 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002021 outInjectionResult = InputEventInjectionResult::PENDING;
2022 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002023 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2024 // Already raised ANR. Drop the event
2025 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002026 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002027 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002028 } else {
2029 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002030 outInjectionResult = InputEventInjectionResult::PENDING;
2031 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002032 }
2033 }
2034
2035 // we have a valid, non-null focused window
2036 resetNoFocusedWindowTimeoutLocked();
2037
Prabir Pradhan5735a322022-04-11 17:23:34 +00002038 // Verify targeted injection.
2039 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2040 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002041 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2042 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043 }
2044
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002045 if (focusedWindowHandle->getInfo()->inputConfig.test(
2046 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002047 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002048 outInjectionResult = InputEventInjectionResult::PENDING;
2049 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002050 }
2051
2052 // If the event is a key event, then we must wait for all previous events to
2053 // complete before delivering it because previous events may have the
2054 // side-effect of transferring focus to a different window and we want to
2055 // ensure that the following keys are sent to the new window.
2056 //
2057 // Suppose the user touches a button in a window then immediately presses "A".
2058 // If the button causes a pop-up window to appear then we want to ensure that
2059 // the "A" key is delivered to the new pop-up window. This is because users
2060 // often anticipate pending UI changes when typing on a keyboard.
2061 // To obtain this behavior, we must serialize key events with respect to all
2062 // prior input events.
2063 if (entry.type == EventEntry::Type::KEY) {
2064 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2065 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002066 outInjectionResult = InputEventInjectionResult::PENDING;
2067 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069 }
2070
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002071 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2072 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073}
2074
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002075/**
2076 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2077 * that are currently unresponsive.
2078 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002079std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2080 const std::vector<Monitor>& monitors) const {
2081 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002082 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002083 [this](const Monitor& monitor) REQUIRES(mLock) {
2084 sp<Connection> connection =
2085 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002086 if (connection == nullptr) {
2087 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002088 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002089 return false;
2090 }
2091 if (!connection->responsive) {
2092 ALOGW("Unresponsive monitor %s will not get the new gesture",
2093 connection->inputChannel->getName().c_str());
2094 return false;
2095 }
2096 return true;
2097 });
2098 return responsiveMonitors;
2099}
2100
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002101/**
2102 * In general, touch should be always split between windows. Some exceptions:
2103 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2104 * from the same device, *and* the window that's receiving the current pointer does not support
2105 * split touch.
2106 * 2. Don't split mouse events
2107 */
2108bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2109 const MotionEntry& entry) const {
2110 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2111 // We should never split mouse events
2112 return false;
2113 }
2114 for (const TouchedWindow& touchedWindow : touchState.windows) {
2115 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2116 // Spy windows should not affect whether or not touch is split.
2117 continue;
2118 }
2119 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2120 continue;
2121 }
2122 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2123 // being sent there. For now, use deviceId from touch state.
2124 if (entry.deviceId == touchState.deviceId && !touchedWindow.pointerIds.isEmpty()) {
2125 return false;
2126 }
2127 }
2128 return true;
2129}
2130
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002131std::vector<TouchedWindow> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002132 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2133 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002134 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002136 std::vector<TouchedWindow> touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137 // For security reasons, we defer updating the touch state until we are sure that
2138 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002139 const int32_t displayId = entry.displayId;
2140 const int32_t action = entry.action;
2141 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142
2143 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002144 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002146 // Copy current touch state into tempTouchState.
2147 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2148 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002149 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002150 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002151 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2152 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002153 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002154 }
2155
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002156 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002157 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002158 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002159
2160 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2161 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2162 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2163 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2164 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002165 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002166
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167 if (newGesture) {
2168 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002169 if (switchedDevice && tempTouchState.isDown() && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002170 ALOGI("Dropping event because a pointer for a different device is already down "
2171 "in display %" PRId32,
2172 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002173 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002174 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakouf0ab2c82022-10-25 18:15:28 -07002175 return touchedWindows; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176 }
Siarhei Vishniakoud57302f2022-11-08 11:12:29 -08002177 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002178 tempTouchState.deviceId = entry.deviceId;
2179 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002181 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002182 ALOGI("Dropping move event because a pointer for a different device is already active "
2183 "in display %" PRId32,
2184 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002185 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002186 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakouf0ab2c82022-10-25 18:15:28 -07002187 return touchedWindows; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188 }
2189
Siarhei Vishniakoud57302f2022-11-08 11:12:29 -08002190 if (isHoverAction) {
2191 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2192 // all of the existing hovering pointers and recompute.
2193 tempTouchState.clearHoveringPointers();
2194 }
2195
Michael Wrightd02c5b62014-02-10 15:10:22 -08002196 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2197 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002198 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002199 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002200 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002201 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoud57302f2022-11-08 11:12:29 -08002202 sp<WindowInfoHandle> newTouchedWindowHandle =
2203 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus,
2204 isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002205
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002207 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002208 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2209 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002211 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002212 }
2213
Prabir Pradhan5735a322022-04-11 17:23:34 +00002214 // Verify targeted injection.
2215 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2216 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002217 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002218 newTouchedWindowHandle = nullptr;
2219 goto Failed;
2220 }
2221
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002222 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002223 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002224 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2225 // New window supports splitting, but we should never split mouse events.
2226 isSplit = !isFromMouse;
2227 } else if (isSplit) {
2228 // New window does not support splitting but we have already split events.
2229 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002230 newTouchedWindowHandle = nullptr;
2231 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002232 } else {
2233 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002234 // be delivered to a new window which supports split touch. Pointers from a mouse device
2235 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002236 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002237 }
2238
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002239 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002240 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002241 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002242 // Process the foreground window first so that it is the first to receive the event.
2243 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002244 }
2245
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002246 if (newTouchedWindows.empty()) {
2247 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2248 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002249 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002250 goto Failed;
2251 }
2252
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002253 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002254 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002255 continue;
2256 }
2257
Siarhei Vishniakoud57302f2022-11-08 11:12:29 -08002258 if (isHoverAction) {
2259 const int32_t pointerId = entry.pointerProperties[0].id;
2260 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2261 // Pointer left. Remove it
2262 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2263 } else {
2264 // The "windowHandle" is the target of this hovering pointer.
2265 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId,
2266 pointerId);
2267 }
2268 }
2269
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002270 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002271 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002272
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002273 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2274 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002275 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002276 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002277
2278 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002279 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002280 }
2281 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002282 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002283 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002284 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002285 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002286
2287 // Update the temporary touch state.
2288 BitSet32 pointerIds;
Siarhei Vishniakoud57302f2022-11-08 11:12:29 -08002289 if (!isHoverAction) {
2290 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2291 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002292
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002293 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
2294 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002296
2297 // If any existing window is pilfering pointers from newly added window, remove it
2298 BitSet32 canceledPointers = BitSet32(0);
2299 for (const TouchedWindow& window : tempTouchState.windows) {
2300 if (window.isPilferingPointers) {
2301 canceledPointers |= window.pointerIds;
2302 }
2303 }
2304 tempTouchState.cancelPointersForNonPilferingWindows(canceledPointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 } else {
2306 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2307
2308 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002309 if (!tempTouchState.isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002310 ALOGD_IF(DEBUG_FOCUS,
2311 "Dropping event because the pointer is not down or we previously "
2312 "dropped the pointer down event in display %" PRId32 ": %s",
2313 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002314 outInjectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 goto Failed;
2316 }
2317
arthurhung6d4bed92021-03-17 11:59:33 +08002318 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002319
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002321 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002322 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002323 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07002324 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002325 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002326 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakoud57302f2022-11-08 11:12:29 -08002327 sp<WindowInfoHandle> newTouchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002328 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002329
Prabir Pradhan5735a322022-04-11 17:23:34 +00002330 // Verify targeted injection.
2331 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2332 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002333 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002334 newTouchedWindowHandle = nullptr;
2335 goto Failed;
2336 }
2337
Vishnu Nair062a8672021-09-03 16:07:44 -07002338 // Drop touch events if requested by input feature
2339 if (newTouchedWindowHandle != nullptr &&
2340 shouldDropInput(entry, newTouchedWindowHandle)) {
2341 newTouchedWindowHandle = nullptr;
2342 }
2343
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002344 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2345 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002346 if (DEBUG_FOCUS) {
2347 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2348 oldTouchedWindowHandle->getName().c_str(),
2349 newTouchedWindowHandle->getName().c_str(), displayId);
2350 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002352 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002353 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002354 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355
2356 // Make a slippery entrance into the new window.
2357 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002358 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359 }
2360
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002361 ftl::Flags<InputTarget::Flags> targetFlags =
2362 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002363 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002364 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002367 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368 }
2369 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002370 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002371 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002372 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002373 }
2374
2375 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002376 pointerIds.markBit(entry.pointerProperties[0].id);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002377 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2378 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002379 }
2380 }
Arthur Hung96483742022-11-15 03:30:48 +00002381
2382 // Update the pointerIds for non-splittable when it received pointer down.
2383 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2384 // If no split, we suppose all touched windows should receive pointer down.
2385 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2386 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2387 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2388 // Ignore drag window for it should just track one pointer.
2389 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2390 continue;
2391 }
2392 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2393 }
2394 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395 }
2396
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002397 // Update dispatching for hover enter and exit.
Siarhei Vishniakoud57302f2022-11-08 11:12:29 -08002398 {
2399 std::vector<TouchedWindow> hoveringWindows =
2400 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2401 touchedWindows.insert(touchedWindows.end(), hoveringWindows.begin(), hoveringWindows.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002402 }
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002403 // Ensure that we have at least one foreground window or at least one window that cannot be a
2404 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2405 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2406 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002407 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2408 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002409 return !canReceiveForegroundTouches(
2410 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002411 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002412 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002413 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2414 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002415 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002416 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417 }
2418
Prabir Pradhan5735a322022-04-11 17:23:34 +00002419 // Ensure that all touched windows are valid for injection.
2420 if (entry.injectionState != nullptr) {
2421 std::string errs;
2422 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002423 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002424 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2425 // dispatched to any uid, since the coords will be zeroed out later.
2426 continue;
2427 }
2428 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2429 if (err) errs += "\n - " + *err;
2430 }
2431 if (!errs.empty()) {
2432 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2433 "%d:%s",
2434 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002435 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002436 goto Failed;
2437 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002438 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002439
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440 // Check whether windows listening for outside touches are owned by the same UID. If it is
2441 // set the policy flag that we will not reveal coordinate information to this window.
2442 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002443 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002444 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002445 if (foregroundWindowHandle) {
2446 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002447 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002448 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
chaviw98318de2021-05-19 16:45:23 -05002449 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2450 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2451 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002452 InputTarget::Flags::ZERO_COORDS,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002453 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002454 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002455 }
2456 }
2457 }
2458 }
2459
Michael Wrightd02c5b62014-02-10 15:10:22 -08002460 // If this is the first pointer going down and the touched window has a wallpaper
2461 // then also add the touched wallpaper windows so they are locked in for the duration
2462 // of the touch gesture.
2463 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2464 // engine only supports touch events. We would need to add a mechanism similar
2465 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2466 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002467 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002468 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002469 if (foregroundWindowHandle &&
2470 foregroundWindowHandle->getInfo()->inputConfig.test(
2471 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002472 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002473 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002474 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2475 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002476 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002477 windowHandle->getInfo()->inputConfig.test(
2478 WindowInfo::InputConfig::IS_WALLPAPER)) {
Arthur Hung74c248d2022-11-23 07:09:59 +00002479 BitSet32 pointerIds;
2480 pointerIds.markBit(entry.pointerProperties[0].id);
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002481 tempTouchState.addOrUpdateWindow(windowHandle,
2482 InputTarget::Flags::WINDOW_IS_OBSCURED |
2483 InputTarget::Flags::
2484 WINDOW_IS_PARTIALLY_OBSCURED |
2485 InputTarget::Flags::DISPATCH_AS_IS,
Arthur Hung74c248d2022-11-23 07:09:59 +00002486 pointerIds, entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002487 }
2488 }
2489 }
2490 }
2491
Siarhei Vishniakoud57302f2022-11-08 11:12:29 -08002492 // Success! Output targets for everything except hovers.
2493 if (!isHoverAction) {
2494 touchedWindows.insert(touchedWindows.end(), tempTouchState.windows.begin(),
2495 tempTouchState.windows.end());
2496 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002497
Siarhei Vishniakoud57302f2022-11-08 11:12:29 -08002498 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002499 // Drop the outside or hover touch windows since we will not care about them
2500 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002501 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002502
2503Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002505 if (switchedDevice) {
2506 if (DEBUG_FOCUS) {
2507 ALOGD("Conflicting pointer actions: Switched to a different device.");
2508 }
2509 *outConflictingPointerActions = true;
2510 }
2511
2512 if (isHoverAction) {
2513 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002514 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002515 ALOGD_IF(DEBUG_FOCUS,
2516 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002517 *outConflictingPointerActions = true;
2518 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002519 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2520 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2521 tempTouchState.deviceId = entry.deviceId;
2522 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002523 }
Siarhei Vishniakoud57302f2022-11-08 11:12:29 -08002524 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2525 // Pointer went up.
2526 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
2527 tempTouchState.clearWindowsWithoutPointers();
2528 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002529 // All pointers up or canceled.
2530 tempTouchState.reset();
2531 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2532 // First pointer went down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002533 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002534 ALOGD("Conflicting pointer actions: Down received while already down.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002535 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002536 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002537 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2538 // One pointer went up.
2539 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2540 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002542 for (size_t i = 0; i < tempTouchState.windows.size();) {
2543 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2544 touchedWindow.pointerIds.clearBit(pointerId);
2545 if (touchedWindow.pointerIds.isEmpty()) {
2546 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2547 continue;
2548 }
2549 i += 1;
2550 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002551 }
2552
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002553 // Save changes unless the action was scroll in which case the temporary touch
2554 // state was only valid for this one action.
2555 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002556 if (displayId >= 0) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002557 mTouchStatesByDisplay[displayId] = tempTouchState;
2558 } else {
2559 mTouchStatesByDisplay.erase(displayId);
2560 }
2561 }
2562
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002563 if (tempTouchState.windows.empty()) {
2564 mTouchStatesByDisplay.erase(displayId);
2565 }
2566
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002567 return touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568}
2569
arthurhung6d4bed92021-03-17 11:59:33 +08002570void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002571 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2572 // have an explicit reason to support it.
2573 constexpr bool isStylus = false;
2574
chaviw98318de2021-05-19 16:45:23 -05002575 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002576 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002577 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002578 if (dropWindow) {
2579 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002580 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002581 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002582 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002583 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002584 }
2585 mDragState.reset();
2586}
2587
2588void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002589 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002590 return;
2591 }
2592
arthurhung6d4bed92021-03-17 11:59:33 +08002593 if (!mDragState->isStartDrag) {
2594 mDragState->isStartDrag = true;
2595 mDragState->isStylusButtonDownAtStart =
2596 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2597 }
2598
Arthur Hung54745652022-04-20 07:17:41 +00002599 // Find the pointer index by id.
2600 int32_t pointerIndex = 0;
2601 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2602 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2603 if (pointerProperties.id == mDragState->pointerId) {
2604 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002605 }
Arthur Hung54745652022-04-20 07:17:41 +00002606 }
arthurhung6d4bed92021-03-17 11:59:33 +08002607
Arthur Hung54745652022-04-20 07:17:41 +00002608 if (uint32_t(pointerIndex) == entry.pointerCount) {
2609 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002610 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002611 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002612 return;
2613 }
2614
2615 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2616 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2617 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2618
2619 switch (maskedAction) {
2620 case AMOTION_EVENT_ACTION_MOVE: {
2621 // Handle the special case : stylus button no longer pressed.
2622 bool isStylusButtonDown =
2623 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2624 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2625 finishDragAndDrop(entry.displayId, x, y);
2626 return;
2627 }
2628
2629 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2630 // until we have an explicit reason to support it.
2631 constexpr bool isStylus = false;
2632
2633 const sp<WindowInfoHandle> hoverWindowHandle =
2634 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2635 isStylus, false /*addOutsideTargets*/,
2636 true /*ignoreDragWindow*/);
2637 // enqueue drag exit if needed.
2638 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2639 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2640 if (mDragState->dragHoverWindowHandle != nullptr) {
2641 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2642 y);
2643 }
2644 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2645 }
2646 // enqueue drag location if needed.
2647 if (hoverWindowHandle != nullptr) {
2648 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2649 }
2650 break;
2651 }
2652
2653 case AMOTION_EVENT_ACTION_POINTER_UP:
2654 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2655 break;
2656 }
2657 // The drag pointer is up.
2658 [[fallthrough]];
2659 case AMOTION_EVENT_ACTION_UP:
2660 finishDragAndDrop(entry.displayId, x, y);
2661 break;
2662 case AMOTION_EVENT_ACTION_CANCEL: {
2663 ALOGD("Receiving cancel when drag and drop.");
2664 sendDropWindowCommandLocked(nullptr, 0, 0);
2665 mDragState.reset();
2666 break;
2667 }
arthurhungb89ccb02020-12-30 16:19:01 +08002668 }
2669}
2670
chaviw98318de2021-05-19 16:45:23 -05002671void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002672 ftl::Flags<InputTarget::Flags> targetFlags,
2673 BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002674 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002675 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002676 std::vector<InputTarget>::iterator it =
2677 std::find_if(inputTargets.begin(), inputTargets.end(),
2678 [&windowHandle](const InputTarget& inputTarget) {
2679 return inputTarget.inputChannel->getConnectionToken() ==
2680 windowHandle->getToken();
2681 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002682
chaviw98318de2021-05-19 16:45:23 -05002683 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002684
2685 if (it == inputTargets.end()) {
2686 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002687 std::shared_ptr<InputChannel> inputChannel =
2688 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002689 if (inputChannel == nullptr) {
2690 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2691 return;
2692 }
2693 inputTarget.inputChannel = inputChannel;
2694 inputTarget.flags = targetFlags;
2695 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002696 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002697 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2698 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002699 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002700 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002701 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002702 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002703 inputTargets.push_back(inputTarget);
2704 it = inputTargets.end() - 1;
2705 }
2706
2707 ALOG_ASSERT(it->flags == targetFlags);
2708 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2709
chaviw1ff3d1e2020-07-01 15:53:47 -07002710 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711}
2712
Michael Wright3dd60e22019-03-27 22:06:44 +00002713void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002714 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002715 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2716 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002717
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002718 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2719 InputTarget target;
2720 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002721 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002722 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2723 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002724 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2725 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002726 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002727 target.setDefaultPointerTransform(target.displayTransform);
2728 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002729 }
2730}
2731
Robert Carrc9bf1d32020-04-13 17:21:08 -07002732/**
2733 * Indicate whether one window handle should be considered as obscuring
2734 * another window handle. We only check a few preconditions. Actually
2735 * checking the bounds is left to the caller.
2736 */
chaviw98318de2021-05-19 16:45:23 -05002737static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2738 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002739 // Compare by token so cloned layers aren't counted
2740 if (haveSameToken(windowHandle, otherHandle)) {
2741 return false;
2742 }
2743 auto info = windowHandle->getInfo();
2744 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002745 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002746 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002747 } else if (otherInfo->alpha == 0 &&
2748 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002749 // Those act as if they were invisible, so we don't need to flag them.
2750 // We do want to potentially flag touchable windows even if they have 0
2751 // opacity, since they can consume touches and alter the effects of the
2752 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002753 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002754 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2755 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002756 } else if (info->ownerUid == otherInfo->ownerUid) {
2757 // If ownerUid is the same we don't generate occlusion events as there
2758 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002759 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002760 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002761 return false;
2762 } else if (otherInfo->displayId != info->displayId) {
2763 return false;
2764 }
2765 return true;
2766}
2767
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002768/**
2769 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2770 * untrusted, one should check:
2771 *
2772 * 1. If result.hasBlockingOcclusion is true.
2773 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2774 * BLOCK_UNTRUSTED.
2775 *
2776 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2777 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2778 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2779 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2780 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2781 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2782 *
2783 * If neither of those is true, then it means the touch can be allowed.
2784 */
2785InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002786 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2787 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002788 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002789 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002790 TouchOcclusionInfo info;
2791 info.hasBlockingOcclusion = false;
2792 info.obscuringOpacity = 0;
2793 info.obscuringUid = -1;
2794 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002795 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002796 if (windowHandle == otherHandle) {
2797 break; // All future windows are below us. Exit early.
2798 }
chaviw98318de2021-05-19 16:45:23 -05002799 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002800 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2801 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002802 if (DEBUG_TOUCH_OCCLUSION) {
2803 info.debugInfo.push_back(
2804 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2805 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002806 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2807 // we perform the checks below to see if the touch can be propagated or not based on the
2808 // window's touch occlusion mode
2809 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2810 info.hasBlockingOcclusion = true;
2811 info.obscuringUid = otherInfo->ownerUid;
2812 info.obscuringPackage = otherInfo->packageName;
2813 break;
2814 }
2815 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2816 uint32_t uid = otherInfo->ownerUid;
2817 float opacity =
2818 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2819 // Given windows A and B:
2820 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2821 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2822 opacityByUid[uid] = opacity;
2823 if (opacity > info.obscuringOpacity) {
2824 info.obscuringOpacity = opacity;
2825 info.obscuringUid = uid;
2826 info.obscuringPackage = otherInfo->packageName;
2827 }
2828 }
2829 }
2830 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002831 if (DEBUG_TOUCH_OCCLUSION) {
2832 info.debugInfo.push_back(
2833 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2834 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002835 return info;
2836}
2837
chaviw98318de2021-05-19 16:45:23 -05002838std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002839 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002840 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2841 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2842 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2843 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002844 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2845 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2846 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2847 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2848 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002849 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002850 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002851}
2852
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002853bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2854 if (occlusionInfo.hasBlockingOcclusion) {
2855 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2856 occlusionInfo.obscuringUid);
2857 return false;
2858 }
2859 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2860 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2861 "%.2f, maximum allowed = %.2f)",
2862 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2863 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2864 return false;
2865 }
2866 return true;
2867}
2868
chaviw98318de2021-05-19 16:45:23 -05002869bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002870 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002871 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002872 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2873 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002874 if (windowHandle == otherHandle) {
2875 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002876 }
chaviw98318de2021-05-19 16:45:23 -05002877 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002878 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002879 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002880 return true;
2881 }
2882 }
2883 return false;
2884}
2885
chaviw98318de2021-05-19 16:45:23 -05002886bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002887 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002888 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2889 const WindowInfo* windowInfo = windowHandle->getInfo();
2890 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002891 if (windowHandle == otherHandle) {
2892 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002893 }
chaviw98318de2021-05-19 16:45:23 -05002894 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002895 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002896 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002897 return true;
2898 }
2899 }
2900 return false;
2901}
2902
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002903std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002904 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002905 if (applicationHandle != nullptr) {
2906 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002907 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002908 } else {
2909 return applicationHandle->getName();
2910 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002911 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002912 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002913 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002914 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002915 }
2916}
2917
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002918void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002919 if (!isUserActivityEvent(eventEntry)) {
2920 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002921 return;
2922 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002923 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002924 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002925 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002926 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002927 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002928 if (DEBUG_DISPATCH_CYCLE) {
2929 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2930 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931 return;
2932 }
2933 }
2934
2935 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002936 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002937 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002938 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2939 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002940 return;
2941 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002943 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002944 eventType = USER_ACTIVITY_EVENT_TOUCH;
2945 }
2946 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002947 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002948 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002949 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2950 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002951 return;
2952 }
2953 eventType = USER_ACTIVITY_EVENT_BUTTON;
2954 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002955 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002956 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002957 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002958 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002959 break;
2960 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002961 }
2962
Prabir Pradhancef936d2021-07-21 16:17:52 +00002963 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2964 REQUIRES(mLock) {
2965 scoped_unlock unlock(mLock);
2966 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2967 };
2968 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002969}
2970
2971void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002972 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002973 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002974 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002975 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002976 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002977 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002978 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002979 ATRACE_NAME(message.c_str());
2980 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002981 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002982 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002983 "globalScaleFactor=%f, pointerIds=0x%x %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002984 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002985 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2986 inputTarget.getPointerInfoString().c_str());
2987 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002988
2989 // Skip this event if the connection status is not normal.
2990 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002991 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002992 if (DEBUG_DISPATCH_CYCLE) {
2993 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002994 connection->getInputChannelName().c_str(),
2995 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002996 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002997 return;
2998 }
2999
3000 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003001 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003002 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003003 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003004 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003005
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003006 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003007 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003008 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
3009 "Splitting motion events requires a down time to be set for the "
3010 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003011 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003012 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3013 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014 if (!splitMotionEntry) {
3015 return; // split event was dropped
3016 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003017 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3018 std::string reason = std::string("reason=pointer cancel on split window");
3019 android_log_event_list(LOGTAG_INPUT_CANCEL)
3020 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3021 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003022 if (DEBUG_FOCUS) {
3023 ALOGD("channel '%s' ~ Split motion event.",
3024 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003025 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003026 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003027 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3028 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029 return;
3030 }
3031 }
3032
3033 // Not splitting. Enqueue dispatch entries for the event as is.
3034 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3035}
3036
3037void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003038 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003039 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003040 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003041 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003042 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003043 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003044 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003045 ATRACE_NAME(message.c_str());
3046 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003047 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3048 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003049
hongzuo liu95785e22022-09-06 02:51:35 +00003050 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003051
3052 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003053 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003054 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003055 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003056 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003057 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003058 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003059 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003060 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003061 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003062 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003063 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003064 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003065
3066 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003067 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003068 startDispatchCycleLocked(currentTime, connection);
3069 }
3070}
3071
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003072void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003073 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003074 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003075 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003076 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003077 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3078 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003079 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003080 ATRACE_NAME(message.c_str());
3081 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003082 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3083 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084 return;
3085 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003086
3087 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3088 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003089
3090 // This is a new event.
3091 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003092 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003093 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003095 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3096 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003097 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003099 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003100 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003101 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003102 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003103 dispatchEntry->resolvedAction = keyEntry.action;
3104 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003106 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3107 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003108 if (DEBUG_DISPATCH_CYCLE) {
3109 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3110 "event",
3111 connection->getInputChannelName().c_str());
3112 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003113 return; // skip the inconsistent event
3114 }
3115 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003116 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003118 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003119 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003120 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3121 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3122 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3123 static_cast<int32_t>(IdGenerator::Source::OTHER);
3124 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003125 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003126 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003127 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003128 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003129 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003130 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003131 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003132 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003133 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003134 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3135 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003136 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003137 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003138 }
3139 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003140 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3141 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003142 if (DEBUG_DISPATCH_CYCLE) {
3143 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3144 "enter event",
3145 connection->getInputChannelName().c_str());
3146 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003147 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3148 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003149 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3150 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003152 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003153 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003154 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3155 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003156 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003157 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3158 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003160 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3161 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003162 if (DEBUG_DISPATCH_CYCLE) {
3163 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3164 "event",
3165 connection->getInputChannelName().c_str());
3166 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003167 return; // skip the inconsistent event
3168 }
3169
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003170 dispatchEntry->resolvedEventId =
3171 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3172 ? mIdGenerator.nextId()
3173 : motionEntry.id;
3174 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3175 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3176 ") to MotionEvent(id=0x%" PRIx32 ").",
3177 motionEntry.id, dispatchEntry->resolvedEventId);
3178 ATRACE_NAME(message.c_str());
3179 }
3180
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003181 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3182 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3183 // Skip reporting pointer down outside focus to the policy.
3184 break;
3185 }
3186
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003187 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003188 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003189
3190 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003192 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003193 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003194 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3195 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003196 break;
3197 }
Chris Yef59a2f42020-10-16 12:55:26 -07003198 case EventEntry::Type::SENSOR: {
3199 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3200 break;
3201 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003202 case EventEntry::Type::CONFIGURATION_CHANGED:
3203 case EventEntry::Type::DEVICE_RESET: {
3204 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003205 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003206 break;
3207 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003208 }
3209
3210 // Remember that we are waiting for this dispatch to complete.
3211 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003212 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213 }
3214
3215 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003216 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003217 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003218}
3219
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003220/**
3221 * This function is purely for debugging. It helps us understand where the user interaction
3222 * was taking place. For example, if user is touching launcher, we will see a log that user
3223 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3224 * We will see both launcher and wallpaper in that list.
3225 * Once the interaction with a particular set of connections starts, no new logs will be printed
3226 * until the set of interacted connections changes.
3227 *
3228 * The following items are skipped, to reduce the logspam:
3229 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3230 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3231 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3232 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3233 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003234 */
3235void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3236 const std::vector<InputTarget>& targets) {
3237 // Skip ACTION_UP events, and all events other than keys and motions
3238 if (entry.type == EventEntry::Type::KEY) {
3239 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3240 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3241 return;
3242 }
3243 } else if (entry.type == EventEntry::Type::MOTION) {
3244 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3245 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3246 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3247 return;
3248 }
3249 } else {
3250 return; // Not a key or a motion
3251 }
3252
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003253 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003254 std::vector<sp<Connection>> newConnections;
3255 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003256 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003257 continue; // Skip windows that receive ACTION_OUTSIDE
3258 }
3259
3260 sp<IBinder> token = target.inputChannel->getConnectionToken();
3261 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003262 if (connection == nullptr) {
3263 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003264 }
3265 newConnectionTokens.insert(std::move(token));
3266 newConnections.emplace_back(connection);
3267 }
3268 if (newConnectionTokens == mInteractionConnectionTokens) {
3269 return; // no change
3270 }
3271 mInteractionConnectionTokens = newConnectionTokens;
3272
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003273 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003274 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003275 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003276 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003277 std::string message = "Interaction with: " + targetList;
3278 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003279 message += "<none>";
3280 }
3281 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3282}
3283
chaviwfd6d3512019-03-25 13:23:49 -07003284void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003285 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003286 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003287 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3288 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003289 return;
3290 }
3291
Vishnu Nairc519ff72021-01-21 08:23:08 -08003292 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003293 if (focusedToken == token) {
3294 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003295 return;
3296 }
3297
Prabir Pradhancef936d2021-07-21 16:17:52 +00003298 auto command = [this, token]() REQUIRES(mLock) {
3299 scoped_unlock unlock(mLock);
3300 mPolicy->onPointerDownOutsideFocus(token);
3301 };
3302 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303}
3304
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003305status_t InputDispatcher::publishMotionEvent(Connection& connection,
3306 DispatchEntry& dispatchEntry) const {
3307 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3308 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3309
3310 PointerCoords scaledCoords[MAX_POINTERS];
3311 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3312
3313 // Set the X and Y offset and X and Y scale depending on the input source.
3314 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003315 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003316 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3317 if (globalScaleFactor != 1.0f) {
3318 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3319 scaledCoords[i] = motionEntry.pointerCoords[i];
3320 // Don't apply window scale here since we don't want scale to affect raw
3321 // coordinates. The scale will be sent back to the client and applied
3322 // later when requesting relative coordinates.
3323 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3324 1 /* windowYScale */);
3325 }
3326 usingCoords = scaledCoords;
3327 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003328 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003329 // We don't want the dispatch target to know the coordinates
3330 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3331 scaledCoords[i].clear();
3332 }
3333 usingCoords = scaledCoords;
3334 }
3335
3336 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3337
3338 // Publish the motion event.
3339 return connection.inputPublisher
3340 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3341 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3342 std::move(hmac), dispatchEntry.resolvedAction,
3343 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3344 motionEntry.edgeFlags, motionEntry.metaState,
3345 motionEntry.buttonState, motionEntry.classification,
3346 dispatchEntry.transform, motionEntry.xPrecision,
3347 motionEntry.yPrecision, motionEntry.xCursorPosition,
3348 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3349 motionEntry.downTime, motionEntry.eventTime,
3350 motionEntry.pointerCount, motionEntry.pointerProperties,
3351 usingCoords);
3352}
3353
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003355 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003356 if (ATRACE_ENABLED()) {
3357 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003358 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003359 ATRACE_NAME(message.c_str());
3360 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003361 if (DEBUG_DISPATCH_CYCLE) {
3362 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003364
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003365 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003366 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003367 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003368 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003369 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003370
3371 // Publish the event.
3372 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003373 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3374 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003375 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003376 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3377 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003378
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003379 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003380 status = connection->inputPublisher
3381 .publishKeyEvent(dispatchEntry->seq,
3382 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3383 keyEntry.source, keyEntry.displayId,
3384 std::move(hmac), dispatchEntry->resolvedAction,
3385 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3386 keyEntry.scanCode, keyEntry.metaState,
3387 keyEntry.repeatCount, keyEntry.downTime,
3388 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003389 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390 }
3391
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003392 case EventEntry::Type::MOTION: {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003393 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003394 break;
3395 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003396
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003397 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003398 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003399 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003400 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003401 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003402 break;
3403 }
3404
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003405 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3406 const TouchModeEntry& touchModeEntry =
3407 static_cast<const TouchModeEntry&>(eventEntry);
3408 status = connection->inputPublisher
3409 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3410 touchModeEntry.inTouchMode);
3411
3412 break;
3413 }
3414
Prabir Pradhan99987712020-11-10 18:43:05 -08003415 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3416 const auto& captureEntry =
3417 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3418 status = connection->inputPublisher
3419 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003420 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003421 break;
3422 }
3423
arthurhungb89ccb02020-12-30 16:19:01 +08003424 case EventEntry::Type::DRAG: {
3425 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3426 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3427 dragEntry.id, dragEntry.x,
3428 dragEntry.y,
3429 dragEntry.isExiting);
3430 break;
3431 }
3432
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003433 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003434 case EventEntry::Type::DEVICE_RESET:
3435 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003436 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003437 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003438 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003439 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003440 }
3441
3442 // Check the result.
3443 if (status) {
3444 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003445 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003446 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003447 "This is unexpected because the wait queue is empty, so the pipe "
3448 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003449 "event to it, status=%s(%d)",
3450 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3451 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003452 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3453 } else {
3454 // Pipe is full and we are waiting for the app to finish process some events
3455 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003456 if (DEBUG_DISPATCH_CYCLE) {
3457 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3458 "waiting for the application to catch up",
3459 connection->getInputChannelName().c_str());
3460 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461 }
3462 } else {
3463 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003464 "status=%s(%d)",
3465 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3466 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003467 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3468 }
3469 return;
3470 }
3471
3472 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003473 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3474 connection->outboundQueue.end(),
3475 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003476 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003477 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003478 if (connection->responsive) {
3479 mAnrTracker.insert(dispatchEntry->timeoutTime,
3480 connection->inputChannel->getConnectionToken());
3481 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003482 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483 }
3484}
3485
chaviw09c8d2d2020-08-24 15:48:26 -07003486std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3487 size_t size;
3488 switch (event.type) {
3489 case VerifiedInputEvent::Type::KEY: {
3490 size = sizeof(VerifiedKeyEvent);
3491 break;
3492 }
3493 case VerifiedInputEvent::Type::MOTION: {
3494 size = sizeof(VerifiedMotionEvent);
3495 break;
3496 }
3497 }
3498 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3499 return mHmacKeyManager.sign(start, size);
3500}
3501
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003502const std::array<uint8_t, 32> InputDispatcher::getSignature(
3503 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003504 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3505 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003506 // Only sign events up and down events as the purely move events
3507 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003508 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003509 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003510
3511 VerifiedMotionEvent verifiedEvent =
3512 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3513 verifiedEvent.actionMasked = actionMasked;
3514 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3515 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003516}
3517
3518const std::array<uint8_t, 32> InputDispatcher::getSignature(
3519 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3520 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3521 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3522 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003523 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003524}
3525
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003527 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003528 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003529 if (DEBUG_DISPATCH_CYCLE) {
3530 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3531 connection->getInputChannelName().c_str(), seq, toString(handled));
3532 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003534 if (connection->status == Connection::Status::BROKEN ||
3535 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003536 return;
3537 }
3538
3539 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003540 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3541 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3542 };
3543 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003544}
3545
3546void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003547 const sp<Connection>& connection,
3548 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003549 if (DEBUG_DISPATCH_CYCLE) {
3550 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3551 connection->getInputChannelName().c_str(), toString(notify));
3552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003553
3554 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003555 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003556 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003557 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003558 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559
3560 // The connection appears to be unrecoverably broken.
3561 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003562 if (connection->status == Connection::Status::NORMAL) {
3563 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003564
3565 if (notify) {
3566 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003567 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3568 connection->getInputChannelName().c_str());
3569
3570 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003571 scoped_unlock unlock(mLock);
3572 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3573 };
3574 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003575 }
3576 }
3577}
3578
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003579void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3580 while (!queue.empty()) {
3581 DispatchEntry* dispatchEntry = queue.front();
3582 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003583 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584 }
3585}
3586
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003587void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003589 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003590 }
3591 delete dispatchEntry;
3592}
3593
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003594int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3595 std::scoped_lock _l(mLock);
3596 sp<Connection> connection = getConnectionLocked(connectionToken);
3597 if (connection == nullptr) {
3598 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3599 connectionToken.get(), events);
3600 return 0; // remove the callback
3601 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003603 bool notify;
3604 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3605 if (!(events & ALOOPER_EVENT_INPUT)) {
3606 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3607 "events=0x%x",
3608 connection->getInputChannelName().c_str(), events);
3609 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 }
3611
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003612 nsecs_t currentTime = now();
3613 bool gotOne = false;
3614 status_t status = OK;
3615 for (;;) {
3616 Result<InputPublisher::ConsumerResponse> result =
3617 connection->inputPublisher.receiveConsumerResponse();
3618 if (!result.ok()) {
3619 status = result.error().code();
3620 break;
3621 }
3622
3623 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3624 const InputPublisher::Finished& finish =
3625 std::get<InputPublisher::Finished>(*result);
3626 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3627 finish.consumeTime);
3628 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003629 if (shouldReportMetricsForConnection(*connection)) {
3630 const InputPublisher::Timeline& timeline =
3631 std::get<InputPublisher::Timeline>(*result);
3632 mLatencyTracker
3633 .trackGraphicsLatency(timeline.inputEventId,
3634 connection->inputChannel->getConnectionToken(),
3635 std::move(timeline.graphicsTimeline));
3636 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003637 }
3638 gotOne = true;
3639 }
3640 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003641 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003642 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643 return 1;
3644 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003645 }
3646
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003647 notify = status != DEAD_OBJECT || !connection->monitor;
3648 if (notify) {
3649 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3650 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3651 status);
3652 }
3653 } else {
3654 // Monitor channels are never explicitly unregistered.
3655 // We do it automatically when the remote endpoint is closed so don't warn about them.
3656 const bool stillHaveWindowHandle =
3657 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3658 notify = !connection->monitor && stillHaveWindowHandle;
3659 if (notify) {
3660 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3661 connection->getInputChannelName().c_str(), events);
3662 }
3663 }
3664
3665 // Remove the channel.
3666 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3667 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003668}
3669
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003670void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003671 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003672 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003673 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674 }
3675}
3676
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003677void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003678 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003679 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003680 for (const Monitor& monitor : monitors) {
3681 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003682 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003683 }
3684}
3685
Michael Wrightd02c5b62014-02-10 15:10:22 -08003686void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003687 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003688 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003689 if (connection == nullptr) {
3690 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003692
3693 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694}
3695
3696void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3697 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003698 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003699 return;
3700 }
3701
3702 nsecs_t currentTime = now();
3703
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003704 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003705 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003707 if (cancelationEvents.empty()) {
3708 return;
3709 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003710 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3711 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3712 "with reality: %s, mode=%d.",
3713 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3714 options.mode);
3715 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003716
Arthur Hungb3307ee2021-10-14 10:57:37 +00003717 std::string reason = std::string("reason=").append(options.reason);
3718 android_log_event_list(LOGTAG_INPUT_CANCEL)
3719 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3720
Svet Ganov5d3bc372020-01-26 23:11:07 -08003721 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003722 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003723 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3724 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003725 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003726 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003727 target.globalScaleFactor = windowInfo->globalScaleFactor;
3728 }
3729 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003730 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003731
hongzuo liu95785e22022-09-06 02:51:35 +00003732 const bool wasEmpty = connection->outboundQueue.empty();
3733
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003734 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003735 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003736 switch (cancelationEventEntry->type) {
3737 case EventEntry::Type::KEY: {
3738 logOutboundKeyDetails("cancel - ",
3739 static_cast<const KeyEntry&>(*cancelationEventEntry));
3740 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003741 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003742 case EventEntry::Type::MOTION: {
3743 logOutboundMotionDetails("cancel - ",
3744 static_cast<const MotionEntry&>(*cancelationEventEntry));
3745 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003746 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003747 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003748 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003749 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3750 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003751 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003752 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003753 break;
3754 }
3755 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003756 case EventEntry::Type::DEVICE_RESET:
3757 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003758 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003759 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003760 break;
3761 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762 }
3763
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003764 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003765 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003767
hongzuo liu95785e22022-09-06 02:51:35 +00003768 // If the outbound queue was previously empty, start the dispatch cycle going.
3769 if (wasEmpty && !connection->outboundQueue.empty()) {
3770 startDispatchCycleLocked(currentTime, connection);
3771 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772}
3773
Svet Ganov5d3bc372020-01-26 23:11:07 -08003774void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003775 const nsecs_t downTime, const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003776 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003777 return;
3778 }
3779
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003780 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003781 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003782
3783 if (downEvents.empty()) {
3784 return;
3785 }
3786
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003787 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003788 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3789 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003790 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003791
3792 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003793 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003794 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3795 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003796 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003797 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003798 target.globalScaleFactor = windowInfo->globalScaleFactor;
3799 }
3800 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003801 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003802
hongzuo liu95785e22022-09-06 02:51:35 +00003803 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003804 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003805 switch (downEventEntry->type) {
3806 case EventEntry::Type::MOTION: {
3807 logOutboundMotionDetails("down - ",
3808 static_cast<const MotionEntry&>(*downEventEntry));
3809 break;
3810 }
3811
3812 case EventEntry::Type::KEY:
3813 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003814 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003815 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003816 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003817 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003818 case EventEntry::Type::SENSOR:
3819 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003820 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003821 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003822 break;
3823 }
3824 }
3825
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003826 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003827 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003828 }
3829
hongzuo liu95785e22022-09-06 02:51:35 +00003830 // If the outbound queue was previously empty, start the dispatch cycle going.
3831 if (wasEmpty && !connection->outboundQueue.empty()) {
3832 startDispatchCycleLocked(downTime, connection);
3833 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003834}
3835
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003836std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003837 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838 ALOG_ASSERT(pointerIds.value != 0);
3839
3840 uint32_t splitPointerIndexMap[MAX_POINTERS];
3841 PointerProperties splitPointerProperties[MAX_POINTERS];
3842 PointerCoords splitPointerCoords[MAX_POINTERS];
3843
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003844 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003845 uint32_t splitPointerCount = 0;
3846
3847 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003848 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003849 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003850 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003851 uint32_t pointerId = uint32_t(pointerProperties.id);
3852 if (pointerIds.hasBit(pointerId)) {
3853 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3854 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3855 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003856 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003857 splitPointerCount += 1;
3858 }
3859 }
3860
3861 if (splitPointerCount != pointerIds.count()) {
3862 // This is bad. We are missing some of the pointers that we expected to deliver.
3863 // Most likely this indicates that we received an ACTION_MOVE events that has
3864 // different pointer ids than we expected based on the previous ACTION_DOWN
3865 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3866 // in this way.
3867 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003868 "we expected there to be %d pointers. This probably means we received "
3869 "a broken sequence of pointer ids from the input device.",
3870 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003871 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872 }
3873
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003874 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003876 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3877 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3879 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003880 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881 uint32_t pointerId = uint32_t(pointerProperties.id);
3882 if (pointerIds.hasBit(pointerId)) {
3883 if (pointerIds.count() == 1) {
3884 // The first/last pointer went down/up.
3885 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003886 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003887 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3888 ? AMOTION_EVENT_ACTION_CANCEL
3889 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003890 } else {
3891 // A secondary pointer went down/up.
3892 uint32_t splitPointerIndex = 0;
3893 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3894 splitPointerIndex += 1;
3895 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003896 action = maskedAction |
3897 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898 }
3899 } else {
3900 // An unrelated pointer changed.
3901 action = AMOTION_EVENT_ACTION_MOVE;
3902 }
3903 }
3904
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003905 if (action == AMOTION_EVENT_ACTION_DOWN) {
3906 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3907 "Split motion event has mismatching downTime and eventTime for "
3908 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3909 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3910 }
3911
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003912 int32_t newId = mIdGenerator.nextId();
3913 if (ATRACE_ENABLED()) {
3914 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3915 ") to MotionEvent(id=0x%" PRIx32 ").",
3916 originalMotionEntry.id, newId);
3917 ATRACE_NAME(message.c_str());
3918 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003919 std::unique_ptr<MotionEntry> splitMotionEntry =
3920 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3921 originalMotionEntry.deviceId, originalMotionEntry.source,
3922 originalMotionEntry.displayId,
3923 originalMotionEntry.policyFlags, action,
3924 originalMotionEntry.actionButton,
3925 originalMotionEntry.flags, originalMotionEntry.metaState,
3926 originalMotionEntry.buttonState,
3927 originalMotionEntry.classification,
3928 originalMotionEntry.edgeFlags,
3929 originalMotionEntry.xPrecision,
3930 originalMotionEntry.yPrecision,
3931 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003932 originalMotionEntry.yCursorPosition, splitDownTime,
3933 splitPointerCount, splitPointerProperties,
3934 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003936 if (originalMotionEntry.injectionState) {
3937 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938 splitMotionEntry->injectionState->refCount += 1;
3939 }
3940
3941 return splitMotionEntry;
3942}
3943
3944void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003945 if (DEBUG_INBOUND_EVENT_DETAILS) {
3946 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003948
Antonio Kantekf16f2832021-09-28 04:39:20 +00003949 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003951 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003953 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3954 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3955 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956 } // release lock
3957
3958 if (needWake) {
3959 mLooper->wake();
3960 }
3961}
3962
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003963/**
3964 * If one of the meta shortcuts is detected, process them here:
3965 * Meta + Backspace -> generate BACK
3966 * Meta + Enter -> generate HOME
3967 * This will potentially overwrite keyCode and metaState.
3968 */
3969void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003970 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003971 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3972 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3973 if (keyCode == AKEYCODE_DEL) {
3974 newKeyCode = AKEYCODE_BACK;
3975 } else if (keyCode == AKEYCODE_ENTER) {
3976 newKeyCode = AKEYCODE_HOME;
3977 }
3978 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003979 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003980 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003981 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003982 keyCode = newKeyCode;
3983 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3984 }
3985 } else if (action == AKEY_EVENT_ACTION_UP) {
3986 // In order to maintain a consistent stream of up and down events, check to see if the key
3987 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3988 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003989 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003990 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003991 auto replacementIt = mReplacedKeys.find(replacement);
3992 if (replacementIt != mReplacedKeys.end()) {
3993 keyCode = replacementIt->second;
3994 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003995 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3996 }
3997 }
3998}
3999
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004001 if (DEBUG_INBOUND_EVENT_DETAILS) {
4002 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
4003 "policyFlags=0x%x, action=0x%x, "
4004 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
4005 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
4006 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
4007 args->downTime);
4008 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009 if (!validateKeyEvent(args->action)) {
4010 return;
4011 }
4012
4013 uint32_t policyFlags = args->policyFlags;
4014 int32_t flags = args->flags;
4015 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004016 // InputDispatcher tracks and generates key repeats on behalf of
4017 // whatever notifies it, so repeatCount should always be set to 0
4018 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4020 policyFlags |= POLICY_FLAG_VIRTUAL;
4021 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4022 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004023 if (policyFlags & POLICY_FLAG_FUNCTION) {
4024 metaState |= AMETA_FUNCTION_ON;
4025 }
4026
4027 policyFlags |= POLICY_FLAG_TRUSTED;
4028
Michael Wright78f24442014-08-06 15:55:28 -07004029 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004030 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004031
Michael Wrightd02c5b62014-02-10 15:10:22 -08004032 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004033 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08004034 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
4035 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004036
Michael Wright2b3c3302018-03-02 17:19:13 +00004037 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004038 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004039 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4040 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004041 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004043
Antonio Kantekf16f2832021-09-28 04:39:20 +00004044 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045 { // acquire lock
4046 mLock.lock();
4047
4048 if (shouldSendKeyToInputFilterLocked(args)) {
4049 mLock.unlock();
4050
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004051 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004052 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4053 return; // event was consumed by the filter
4054 }
4055
4056 mLock.lock();
4057 }
4058
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004059 std::unique_ptr<KeyEntry> newEntry =
4060 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4061 args->displayId, policyFlags, args->action, flags,
4062 keyCode, args->scanCode, metaState, repeatCount,
4063 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004065 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004066 mLock.unlock();
4067 } // release lock
4068
4069 if (needWake) {
4070 mLooper->wake();
4071 }
4072}
4073
4074bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4075 return mInputFilterEnabled;
4076}
4077
4078void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004079 if (DEBUG_INBOUND_EVENT_DETAILS) {
4080 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4081 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004082 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004083 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4084 "yCursorPosition=%f, downTime=%" PRId64,
4085 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004086 args->policyFlags, MotionEvent::actionToString(args->action).c_str(),
4087 args->actionButton, args->flags, args->metaState, args->buttonState, args->edgeFlags,
4088 args->xPrecision, args->yPrecision, args->xCursorPosition, args->yCursorPosition,
4089 args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004090 for (uint32_t i = 0; i < args->pointerCount; i++) {
4091 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4092 "x=%f, y=%f, pressure=%f, size=%f, "
4093 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4094 "orientation=%f",
4095 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4096 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4097 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4098 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4099 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4100 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4101 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4102 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4103 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4104 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4105 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004106 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -08004107 LOG_ALWAYS_FATAL_IF(!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4108 args->pointerProperties),
4109 "Invalid event: %s", args->dump().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110
4111 uint32_t policyFlags = args->policyFlags;
4112 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004113
4114 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004115 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004116 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4117 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004118 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004119 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120
Antonio Kantekf16f2832021-09-28 04:39:20 +00004121 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122 { // acquire lock
4123 mLock.lock();
4124
4125 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004126 ui::Transform displayTransform;
4127 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4128 displayTransform = it->second.transform;
4129 }
4130
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131 mLock.unlock();
4132
4133 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004134 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4135 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004136 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004137 displayTransform, args->xPrecision, args->yPrecision,
4138 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004139 args->downTime, args->eventTime, args->pointerCount,
4140 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141
4142 policyFlags |= POLICY_FLAG_FILTERED;
4143 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4144 return; // event was consumed by the filter
4145 }
4146
4147 mLock.lock();
4148 }
4149
4150 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004151 std::unique_ptr<MotionEntry> newEntry =
4152 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4153 args->source, args->displayId, policyFlags,
4154 args->action, args->actionButton, args->flags,
4155 args->metaState, args->buttonState,
4156 args->classification, args->edgeFlags,
4157 args->xPrecision, args->yPrecision,
4158 args->xCursorPosition, args->yCursorPosition,
4159 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004160 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004162 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4163 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4164 !mInputFilterEnabled) {
4165 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4166 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4167 }
4168
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004169 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 mLock.unlock();
4171 } // release lock
4172
4173 if (needWake) {
4174 mLooper->wake();
4175 }
4176}
4177
Chris Yef59a2f42020-10-16 12:55:26 -07004178void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004179 if (DEBUG_INBOUND_EVENT_DETAILS) {
4180 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4181 " sensorType=%s",
4182 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004183 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004184 }
Chris Yef59a2f42020-10-16 12:55:26 -07004185
Antonio Kantekf16f2832021-09-28 04:39:20 +00004186 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004187 { // acquire lock
4188 mLock.lock();
4189
4190 // Just enqueue a new sensor event.
4191 std::unique_ptr<SensorEntry> newEntry =
4192 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4193 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4194 args->sensorType, args->accuracy,
4195 args->accuracyChanged, args->values);
4196
4197 needWake = enqueueInboundEventLocked(std::move(newEntry));
4198 mLock.unlock();
4199 } // release lock
4200
4201 if (needWake) {
4202 mLooper->wake();
4203 }
4204}
4205
Chris Yefb552902021-02-03 17:18:37 -08004206void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004207 if (DEBUG_INBOUND_EVENT_DETAILS) {
4208 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4209 args->deviceId, args->isOn);
4210 }
Chris Yefb552902021-02-03 17:18:37 -08004211 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4212}
4213
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004215 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004216}
4217
4218void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004219 if (DEBUG_INBOUND_EVENT_DETAILS) {
4220 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4221 "switchMask=0x%08x",
4222 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4223 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224
4225 uint32_t policyFlags = args->policyFlags;
4226 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004227 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228}
4229
4230void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004231 if (DEBUG_INBOUND_EVENT_DETAILS) {
4232 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4233 args->deviceId);
4234 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235
Antonio Kantekf16f2832021-09-28 04:39:20 +00004236 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004237 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004238 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004239
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004240 std::unique_ptr<DeviceResetEntry> newEntry =
4241 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4242 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243 } // release lock
4244
4245 if (needWake) {
4246 mLooper->wake();
4247 }
4248}
4249
Prabir Pradhan7e186182020-11-10 13:56:45 -08004250void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004251 if (DEBUG_INBOUND_EVENT_DETAILS) {
4252 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004253 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004254 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004255
Antonio Kantekf16f2832021-09-28 04:39:20 +00004256 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004257 { // acquire lock
4258 std::scoped_lock _l(mLock);
4259 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004260 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004261 needWake = enqueueInboundEventLocked(std::move(entry));
4262 } // release lock
4263
4264 if (needWake) {
4265 mLooper->wake();
4266 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004267}
4268
Prabir Pradhan5735a322022-04-11 17:23:34 +00004269InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4270 std::optional<int32_t> targetUid,
4271 InputEventInjectionSync syncMode,
4272 std::chrono::milliseconds timeout,
4273 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004274 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004275 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4276 "policyFlags=0x%08x",
4277 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4278 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004279 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004280 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281
Prabir Pradhan5735a322022-04-11 17:23:34 +00004282 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004284 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004285 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4286 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4287 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4288 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4289 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004290 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004291 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004292 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004293 }
4294
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004295 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004297 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004298 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4299 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004300 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004301 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004302 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004304 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004305 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4306 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4307 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004308 int32_t keyCode = incomingKey.getKeyCode();
4309 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004310 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004311 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004312 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004313 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004314 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4315 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4316 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004318 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4319 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004320 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004321
4322 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4323 android::base::Timer t;
4324 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4325 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4326 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4327 std::to_string(t.duration().count()).c_str());
4328 }
4329 }
4330
4331 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004332 std::unique_ptr<KeyEntry> injectedEntry =
4333 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004334 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004335 incomingKey.getDisplayId(), policyFlags, action,
4336 flags, keyCode, incomingKey.getScanCode(), metaState,
4337 incomingKey.getRepeatCount(),
4338 incomingKey.getDownTime());
4339 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004340 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341 }
4342
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004343 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004344 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004345 const int32_t action = motionEvent.getAction();
4346 const bool isPointerEvent =
4347 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4348 // If a pointer event has no displayId specified, inject it to the default display.
4349 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4350 ? ADISPLAY_ID_DEFAULT
4351 : event->getDisplayId();
4352 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004353 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004354 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004355 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004356 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004357 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004358 }
4359
4360 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004361 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004362 android::base::Timer t;
4363 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4364 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4365 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4366 std::to_string(t.duration().count()).c_str());
4367 }
4368 }
4369
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004370 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4371 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4372 }
4373
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004374 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004375 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4376 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004377 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004378 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4379 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004380 displayId, policyFlags, action, actionButton,
4381 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004382 motionEvent.getButtonState(),
4383 motionEvent.getClassification(),
4384 motionEvent.getEdgeFlags(),
4385 motionEvent.getXPrecision(),
4386 motionEvent.getYPrecision(),
4387 motionEvent.getRawXCursorPosition(),
4388 motionEvent.getRawYCursorPosition(),
4389 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004390 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004391 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004392 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004393 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004394 sampleEventTimes += 1;
4395 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004396 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004397 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4398 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004399 displayId, policyFlags, action, actionButton,
4400 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004401 motionEvent.getButtonState(),
4402 motionEvent.getClassification(),
4403 motionEvent.getEdgeFlags(),
4404 motionEvent.getXPrecision(),
4405 motionEvent.getYPrecision(),
4406 motionEvent.getRawXCursorPosition(),
4407 motionEvent.getRawYCursorPosition(),
4408 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004409 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004410 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004411 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4412 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004413 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004414 }
4415 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004418 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004419 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004420 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421 }
4422
Prabir Pradhan5735a322022-04-11 17:23:34 +00004423 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004424 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004425 injectionState->injectionIsAsync = true;
4426 }
4427
4428 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004429 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004430
4431 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004432 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004433 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004434 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004435 }
4436
4437 mLock.unlock();
4438
4439 if (needWake) {
4440 mLooper->wake();
4441 }
4442
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004443 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004444 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004445 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004446
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004447 if (syncMode == InputEventInjectionSync::NONE) {
4448 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449 } else {
4450 for (;;) {
4451 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004452 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004453 break;
4454 }
4455
4456 nsecs_t remainingTimeout = endTime - now();
4457 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004458 if (DEBUG_INJECTION) {
4459 ALOGD("injectInputEvent - Timed out waiting for injection result "
4460 "to become available.");
4461 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004462 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004463 break;
4464 }
4465
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004466 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004467 }
4468
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004469 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4470 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004472 if (DEBUG_INJECTION) {
4473 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4474 injectionState->pendingForegroundDispatches);
4475 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004476 nsecs_t remainingTimeout = endTime - now();
4477 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004478 if (DEBUG_INJECTION) {
4479 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4480 "dispatches to finish.");
4481 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004482 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004483 break;
4484 }
4485
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004486 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004487 }
4488 }
4489 }
4490
4491 injectionState->release();
4492 } // release lock
4493
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004494 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004495 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004496 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004497
4498 return injectionResult;
4499}
4500
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004501std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004502 std::array<uint8_t, 32> calculatedHmac;
4503 std::unique_ptr<VerifiedInputEvent> result;
4504 switch (event.getType()) {
4505 case AINPUT_EVENT_TYPE_KEY: {
4506 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4507 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4508 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004509 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004510 break;
4511 }
4512 case AINPUT_EVENT_TYPE_MOTION: {
4513 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4514 VerifiedMotionEvent verifiedMotionEvent =
4515 verifiedMotionEventFromMotionEvent(motionEvent);
4516 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004517 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004518 break;
4519 }
4520 default: {
4521 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4522 return nullptr;
4523 }
4524 }
4525 if (calculatedHmac == INVALID_HMAC) {
4526 return nullptr;
4527 }
4528 if (calculatedHmac != event.getHmac()) {
4529 return nullptr;
4530 }
4531 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004532}
4533
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004534void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004535 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004536 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004537 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004538 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004539 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004540 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004541
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004542 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543 // Log the outcome since the injector did not wait for the injection result.
4544 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004545 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004546 ALOGV("Asynchronous input event injection succeeded.");
4547 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004548 case InputEventInjectionResult::TARGET_MISMATCH:
4549 ALOGV("Asynchronous input event injection target mismatch.");
4550 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004551 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004552 ALOGW("Asynchronous input event injection failed.");
4553 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004554 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004555 ALOGW("Asynchronous input event injection timed out.");
4556 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004557 case InputEventInjectionResult::PENDING:
4558 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4559 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004560 }
4561 }
4562
4563 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004564 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565 }
4566}
4567
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004568void InputDispatcher::transformMotionEntryForInjectionLocked(
4569 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004570 // Input injection works in the logical display coordinate space, but the input pipeline works
4571 // display space, so we need to transform the injected events accordingly.
4572 const auto it = mDisplayInfos.find(entry.displayId);
4573 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004574 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004575
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004576 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4577 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4578 const vec2 cursor =
4579 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4580 {entry.xCursorPosition, entry.yCursorPosition});
4581 entry.xCursorPosition = cursor.x;
4582 entry.yCursorPosition = cursor.y;
4583 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004584 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004585 entry.pointerCoords[i] =
4586 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4587 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004588 }
4589}
4590
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004591void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4592 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004593 if (injectionState) {
4594 injectionState->pendingForegroundDispatches += 1;
4595 }
4596}
4597
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004598void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4599 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004600 if (injectionState) {
4601 injectionState->pendingForegroundDispatches -= 1;
4602
4603 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004604 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605 }
4606 }
4607}
4608
chaviw98318de2021-05-19 16:45:23 -05004609const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004610 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004611 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004612 auto it = mWindowHandlesByDisplay.find(displayId);
4613 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004614}
4615
chaviw98318de2021-05-19 16:45:23 -05004616sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004617 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004618 if (windowHandleToken == nullptr) {
4619 return nullptr;
4620 }
4621
Arthur Hungb92218b2018-08-14 12:00:21 +08004622 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004623 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4624 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004625 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004626 return windowHandle;
4627 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628 }
4629 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004630 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004631}
4632
chaviw98318de2021-05-19 16:45:23 -05004633sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4634 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004635 if (windowHandleToken == nullptr) {
4636 return nullptr;
4637 }
4638
chaviw98318de2021-05-19 16:45:23 -05004639 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004640 if (windowHandle->getToken() == windowHandleToken) {
4641 return windowHandle;
4642 }
4643 }
4644 return nullptr;
4645}
4646
chaviw98318de2021-05-19 16:45:23 -05004647sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4648 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004649 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004650 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4651 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004652 if (handle->getId() == windowHandle->getId() &&
4653 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004654 if (windowHandle->getInfo()->displayId != it.first) {
4655 ALOGE("Found window %s in display %" PRId32
4656 ", but it should belong to display %" PRId32,
4657 windowHandle->getName().c_str(), it.first,
4658 windowHandle->getInfo()->displayId);
4659 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004660 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004661 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004662 }
4663 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004664 return nullptr;
4665}
4666
chaviw98318de2021-05-19 16:45:23 -05004667sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004668 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4669 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004670}
4671
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004672bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4673 const MotionEntry& motionEntry) const {
4674 const WindowInfo& info = *window->getInfo();
4675
4676 // Skip spy window targets that are not valid for targeted injection.
4677 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004678 return false;
4679 }
4680
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004681 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4682 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4683 return false;
4684 }
4685
4686 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4687 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4688 window->getName().c_str());
4689 return false;
4690 }
4691
4692 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004693 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004694 ALOGW("Not sending touch to %s because there's no corresponding connection",
4695 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004696 return false;
4697 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004698
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004699 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004700 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004701 return false;
4702 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004703
4704 // Drop events that can't be trusted due to occlusion
4705 const auto [x, y] = resolveTouchedPosition(motionEntry);
4706 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4707 if (!isTouchTrustedLocked(occlusionInfo)) {
4708 if (DEBUG_TOUCH_OCCLUSION) {
4709 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4710 for (const auto& log : occlusionInfo.debugInfo) {
4711 ALOGD("%s", log.c_str());
4712 }
4713 }
4714 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4715 occlusionInfo.obscuringUid);
4716 return false;
4717 }
4718
4719 // Drop touch events if requested by input feature
4720 if (shouldDropInput(motionEntry, window)) {
4721 return false;
4722 }
4723
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004724 return true;
4725}
4726
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004727std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4728 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004729 auto connectionIt = mConnectionsByToken.find(token);
4730 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004731 return nullptr;
4732 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004733 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004734}
4735
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004736void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004737 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4738 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004739 // Remove all handles on a display if there are no windows left.
4740 mWindowHandlesByDisplay.erase(displayId);
4741 return;
4742 }
4743
4744 // Since we compare the pointer of input window handles across window updates, we need
4745 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004746 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4747 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4748 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004749 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004750 }
4751
chaviw98318de2021-05-19 16:45:23 -05004752 std::vector<sp<WindowInfoHandle>> newHandles;
4753 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004754 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004755 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004756 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004757 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004758 const bool canReceiveInput =
4759 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4760 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004761 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004762 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004763 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004764 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004765 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004766 }
4767
4768 if (info->displayId != displayId) {
4769 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4770 handle->getName().c_str(), displayId, info->displayId);
4771 continue;
4772 }
4773
Robert Carredd13602020-04-13 17:24:34 -07004774 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4775 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004776 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004777 oldHandle->updateFrom(handle);
4778 newHandles.push_back(oldHandle);
4779 } else {
4780 newHandles.push_back(handle);
4781 }
4782 }
4783
4784 // Insert or replace
4785 mWindowHandlesByDisplay[displayId] = newHandles;
4786}
4787
Arthur Hung72d8dc32020-03-28 00:48:39 +00004788void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004789 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004790 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004791 { // acquire lock
4792 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004793 for (const auto& [displayId, handles] : handlesPerDisplay) {
4794 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004795 }
4796 }
4797 // Wake up poll loop since it may need to make new input dispatching choices.
4798 mLooper->wake();
4799}
4800
Arthur Hungb92218b2018-08-14 12:00:21 +08004801/**
4802 * Called from InputManagerService, update window handle list by displayId that can receive input.
4803 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4804 * If set an empty list, remove all handles from the specific display.
4805 * For focused handle, check if need to change and send a cancel event to previous one.
4806 * For removed handle, check if need to send a cancel event if already in touch.
4807 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004808void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004809 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004810 if (DEBUG_FOCUS) {
4811 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004812 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004813 windowList += iwh->getName() + " ";
4814 }
4815 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4816 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004817
Prabir Pradhand65552b2021-10-07 11:23:50 -07004818 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004819 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004820 const WindowInfo& info = *window->getInfo();
4821
4822 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004823 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004824 if (noInputWindow && window->getToken() != nullptr) {
4825 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4826 window->getName().c_str());
4827 window->releaseChannel();
4828 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004829
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004830 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004831 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4832 !info.inputConfig.test(
4833 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004834 "%s has feature SPY, but is not a trusted overlay.",
4835 window->getName().c_str());
4836
Prabir Pradhand65552b2021-10-07 11:23:50 -07004837 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004838 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4839 !info.inputConfig.test(
4840 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004841 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4842 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004843 }
4844
Arthur Hung72d8dc32020-03-28 00:48:39 +00004845 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004846 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004848 // Save the old windows' orientation by ID before it gets updated.
4849 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004850 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004851 oldWindowOrientations.emplace(handle->getId(),
4852 handle->getInfo()->transform.getOrientation());
4853 }
4854
chaviw98318de2021-05-19 16:45:23 -05004855 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004856
chaviw98318de2021-05-19 16:45:23 -05004857 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004858
Vishnu Nairc519ff72021-01-21 08:23:08 -08004859 std::optional<FocusResolver::FocusChanges> changes =
4860 mFocusResolver.setInputWindows(displayId, windowHandles);
4861 if (changes) {
4862 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004863 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004864
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004865 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4866 mTouchStatesByDisplay.find(displayId);
4867 if (stateIt != mTouchStatesByDisplay.end()) {
4868 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004869 for (size_t i = 0; i < state.windows.size();) {
4870 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004871 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004872 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004873 ALOGD("Touched window was removed: %s in display %" PRId32,
4874 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004875 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004876 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004877 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4878 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004879 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00004880 "touched window was removed");
4881 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004882 // Since we are about to drop the touch, cancel the events for the wallpaper as
4883 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004884 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004885 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4886 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004887 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4888 if (wallpaper != nullptr) {
4889 sp<Connection> wallpaperConnection =
4890 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004891 if (wallpaperConnection != nullptr) {
4892 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4893 options);
4894 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004895 }
4896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004898 state.windows.erase(state.windows.begin() + i);
4899 } else {
4900 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901 }
4902 }
arthurhungb89ccb02020-12-30 16:19:01 +08004903
arthurhung6d4bed92021-03-17 11:59:33 +08004904 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004905 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004906 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004907 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004908 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004909 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4910 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004911 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004912 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004913 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004914
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004915 // Determine if the orientation of any of the input windows have changed, and cancel all
4916 // pointer events if necessary.
4917 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4918 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4919 if (newWindowHandle != nullptr &&
4920 newWindowHandle->getInfo()->transform.getOrientation() !=
4921 oldWindowOrientations[oldWindowHandle->getId()]) {
4922 std::shared_ptr<InputChannel> inputChannel =
4923 getInputChannelLocked(newWindowHandle->getToken());
4924 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004925 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004926 "touched window's orientation changed");
4927 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004928 }
4929 }
4930 }
4931
Arthur Hung72d8dc32020-03-28 00:48:39 +00004932 // Release information for windows that are no longer present.
4933 // This ensures that unused input channels are released promptly.
4934 // Otherwise, they might stick around until the window handle is destroyed
4935 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004936 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004937 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004938 if (DEBUG_FOCUS) {
4939 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004940 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004941 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004942 }
chaviw291d88a2019-02-14 10:33:58 -08004943 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944}
4945
4946void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004947 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004948 if (DEBUG_FOCUS) {
4949 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4950 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4951 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004952 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004953 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004954 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955 } // release lock
4956
4957 // Wake up poll loop since it may need to make new input dispatching choices.
4958 mLooper->wake();
4959}
4960
Vishnu Nair599f1412021-06-21 10:39:58 -07004961void InputDispatcher::setFocusedApplicationLocked(
4962 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4963 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4964 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4965
4966 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4967 return; // This application is already focused. No need to wake up or change anything.
4968 }
4969
4970 // Set the new application handle.
4971 if (inputApplicationHandle != nullptr) {
4972 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4973 } else {
4974 mFocusedApplicationHandlesByDisplay.erase(displayId);
4975 }
4976
4977 // No matter what the old focused application was, stop waiting on it because it is
4978 // no longer focused.
4979 resetNoFocusedWindowTimeoutLocked();
4980}
4981
Tiger Huang721e26f2018-07-24 22:26:19 +08004982/**
4983 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4984 * the display not specified.
4985 *
4986 * We track any unreleased events for each window. If a window loses the ability to receive the
4987 * released event, we will send a cancel event to it. So when the focused display is changed, we
4988 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4989 * display. The display-specified events won't be affected.
4990 */
4991void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004992 if (DEBUG_FOCUS) {
4993 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4994 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004995 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004996 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004997
4998 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004999 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005000 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005001 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005002 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005003 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005004 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005005 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005006 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005007 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005008 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005009 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5010 }
5011 }
5012 mFocusedDisplayId = displayId;
5013
Chris Ye3c2d6f52020-08-09 10:39:48 -07005014 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005015 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005016 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005017
Vishnu Nairad321cd2020-08-20 16:40:21 -07005018 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005019 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005020 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005021 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005022 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005023 }
5024 }
5025 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005026 } // release lock
5027
5028 // Wake up poll loop since it may need to make new input dispatching choices.
5029 mLooper->wake();
5030}
5031
Michael Wrightd02c5b62014-02-10 15:10:22 -08005032void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005033 if (DEBUG_FOCUS) {
5034 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005036
5037 bool changed;
5038 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005039 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005040
5041 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5042 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005043 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005044 }
5045
5046 if (mDispatchEnabled && !enabled) {
5047 resetAndDropEverythingLocked("dispatcher is being disabled");
5048 }
5049
5050 mDispatchEnabled = enabled;
5051 mDispatchFrozen = frozen;
5052 changed = true;
5053 } else {
5054 changed = false;
5055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005056 } // release lock
5057
5058 if (changed) {
5059 // Wake up poll loop since it may need to make new input dispatching choices.
5060 mLooper->wake();
5061 }
5062}
5063
5064void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005065 if (DEBUG_FOCUS) {
5066 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005068
5069 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005070 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005071
5072 if (mInputFilterEnabled == enabled) {
5073 return;
5074 }
5075
5076 mInputFilterEnabled = enabled;
5077 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5078 } // release lock
5079
5080 // Wake up poll loop since there might be work to do to drop everything.
5081 mLooper->wake();
5082}
5083
Antonio Kanteka042c022022-07-06 16:51:07 -07005084bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5085 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005086 bool needWake = false;
5087 {
5088 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005089 ALOGD_IF(DEBUG_TOUCH_MODE,
5090 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5091 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5092 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5093 mTouchModePerDisplay.count(displayId) == 0
5094 ? "not set"
5095 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5096
Antonio Kantek15beb512022-06-13 22:35:41 +00005097 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5098 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005099 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005100 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005101 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005102 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5103 !recentWindowsAreOwnedByLocked(pid, uid)) {
5104 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5105 "window nor none of the previously interacted window",
5106 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005107 return false;
5108 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005109 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005110 mTouchModePerDisplay[displayId] = inTouchMode;
5111 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5112 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005113 needWake = enqueueInboundEventLocked(std::move(entry));
5114 } // release lock
5115
5116 if (needWake) {
5117 mLooper->wake();
5118 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005119 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005120}
5121
Antonio Kantek48710e42022-03-24 14:19:30 -07005122bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5123 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5124 if (focusedToken == nullptr) {
5125 return false;
5126 }
5127 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5128 return isWindowOwnedBy(windowHandle, pid, uid);
5129}
5130
5131bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5132 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5133 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5134 const sp<WindowInfoHandle> windowHandle =
5135 getWindowHandleLocked(connectionToken);
5136 return isWindowOwnedBy(windowHandle, pid, uid);
5137 }) != mInteractionConnectionTokens.end();
5138}
5139
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005140void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5141 if (opacity < 0 || opacity > 1) {
5142 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5143 return;
5144 }
5145
5146 std::scoped_lock lock(mLock);
5147 mMaximumObscuringOpacityForTouch = opacity;
5148}
5149
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005150std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5151InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005152 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5153 for (TouchedWindow& w : state.windows) {
5154 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005155 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005156 }
5157 }
5158 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005159 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005160}
5161
arthurhungb89ccb02020-12-30 16:19:01 +08005162bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5163 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005164 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005165 if (DEBUG_FOCUS) {
5166 ALOGD("Trivial transfer to same window.");
5167 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005168 return true;
5169 }
5170
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005172 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173
Arthur Hungabbb9d82021-09-01 14:52:30 +00005174 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005175 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005176 if (state == nullptr || touchedWindow == nullptr) {
5177 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005178 return false;
5179 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005180
Arthur Hungabbb9d82021-09-01 14:52:30 +00005181 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5182 if (toWindowHandle == nullptr) {
5183 ALOGW("Cannot transfer focus because to window not found.");
5184 return false;
5185 }
5186
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005187 if (DEBUG_FOCUS) {
5188 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005189 touchedWindow->windowHandle->getName().c_str(),
5190 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005191 }
5192
Arthur Hungabbb9d82021-09-01 14:52:30 +00005193 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005194 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005195 BitSet32 pointerIds = touchedWindow->pointerIds;
5196 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005197
Arthur Hungabbb9d82021-09-01 14:52:30 +00005198 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005199 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005200 ftl::Flags<InputTarget::Flags> newTargetFlags =
5201 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005202 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005203 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005204 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005205 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005206
Arthur Hungabbb9d82021-09-01 14:52:30 +00005207 // Store the dragging window.
5208 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005209 if (pointerIds.count() != 1) {
5210 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5211 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005212 return false;
5213 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005214 // Track the pointer id for drag window and generate the drag state.
5215 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005216 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005217 }
5218
Arthur Hungabbb9d82021-09-01 14:52:30 +00005219 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005220 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5221 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005222 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005223 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005224 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005225 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005226 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005227 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005228 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005229 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005230 } // release lock
5231
5232 // Wake up poll loop since it may need to make new input dispatching choices.
5233 mLooper->wake();
5234 return true;
5235}
5236
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005237/**
5238 * Get the touched foreground window on the given display.
5239 * Return null if there are no windows touched on that display, or if more than one foreground
5240 * window is being touched.
5241 */
5242sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5243 auto stateIt = mTouchStatesByDisplay.find(displayId);
5244 if (stateIt == mTouchStatesByDisplay.end()) {
5245 ALOGI("No touch state on display %" PRId32, displayId);
5246 return nullptr;
5247 }
5248
5249 const TouchState& state = stateIt->second;
5250 sp<WindowInfoHandle> touchedForegroundWindow;
5251 // If multiple foreground windows are touched, return nullptr
5252 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005253 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005254 if (touchedForegroundWindow != nullptr) {
5255 ALOGI("Two or more foreground windows: %s and %s",
5256 touchedForegroundWindow->getName().c_str(),
5257 window.windowHandle->getName().c_str());
5258 return nullptr;
5259 }
5260 touchedForegroundWindow = window.windowHandle;
5261 }
5262 }
5263 return touchedForegroundWindow;
5264}
5265
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005266// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005267bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005268 sp<IBinder> fromToken;
5269 { // acquire lock
5270 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005271 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005272 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005273 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5274 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005275 return false;
5276 }
5277
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005278 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5279 if (from == nullptr) {
5280 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5281 return false;
5282 }
5283
5284 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005285 } // release lock
5286
5287 return transferTouchFocus(fromToken, destChannelToken);
5288}
5289
Michael Wrightd02c5b62014-02-10 15:10:22 -08005290void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005291 if (DEBUG_FOCUS) {
5292 ALOGD("Resetting and dropping all events (%s).", reason);
5293 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005294
Michael Wrightfb04fd52022-11-24 22:31:11 +00005295 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005296 synthesizeCancelationEventsForAllConnectionsLocked(options);
5297
5298 resetKeyRepeatLocked();
5299 releasePendingEventLocked();
5300 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005301 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005302
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005303 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005304 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005305 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005306}
5307
5308void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005309 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005310 dumpDispatchStateLocked(dump);
5311
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005312 std::istringstream stream(dump);
5313 std::string line;
5314
5315 while (std::getline(stream, line, '\n')) {
5316 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005317 }
5318}
5319
Prabir Pradhan99987712020-11-10 18:43:05 -08005320std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5321 std::string dump;
5322
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005323 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5324 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005325
5326 std::string windowName = "None";
5327 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005328 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005329 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5330 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5331 : "token has capture without window";
5332 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005333 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005334
5335 return dump;
5336}
5337
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005338void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005339 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5340 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5341 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005342 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005343
Tiger Huang721e26f2018-07-24 22:26:19 +08005344 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5345 dump += StringPrintf(INDENT "FocusedApplications:\n");
5346 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5347 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005348 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005349 const std::chrono::duration timeout =
5350 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005351 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005352 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005353 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005355 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005356 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005357 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005358
Vishnu Nairc519ff72021-01-21 08:23:08 -08005359 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005360 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005361
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005362 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005363 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005364 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005365 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5366 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005367 }
5368 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005369 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005370 }
5371
arthurhung6d4bed92021-03-17 11:59:33 +08005372 if (mDragState) {
5373 dump += StringPrintf(INDENT "DragState:\n");
5374 mDragState->dump(dump, INDENT2);
5375 }
5376
Arthur Hungb92218b2018-08-14 12:00:21 +08005377 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005378 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5379 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5380 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5381 const auto& displayInfo = it->second;
5382 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5383 displayInfo.logicalHeight);
5384 displayInfo.transform.dump(dump, "transform", INDENT4);
5385 } else {
5386 dump += INDENT2 "No DisplayInfo found!\n";
5387 }
5388
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005389 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005390 dump += INDENT2 "Windows:\n";
5391 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005392 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5393 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005394
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005395 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005396 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005397 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005398 "applicationInfo.name=%s, "
5399 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005400 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005401 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005402 windowInfo->displayId,
5403 windowInfo->inputConfig.string().c_str(),
5404 windowInfo->alpha, windowInfo->frameLeft,
5405 windowInfo->frameTop, windowInfo->frameRight,
5406 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005407 windowInfo->applicationInfo.name.c_str(),
5408 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005409 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005410 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005411 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005412 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005413 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005414 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005415 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005416 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005417 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005418 }
5419 } else {
5420 dump += INDENT2 "Windows: <none>\n";
5421 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005422 }
5423 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005424 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005425 }
5426
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005427 if (!mGlobalMonitorsByDisplay.empty()) {
5428 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5429 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005430 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005431 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005432 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005433 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005434 }
5435
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005436 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005437
5438 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005439 if (!mRecentQueue.empty()) {
5440 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005441 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005442 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005443 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005444 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005445 }
5446 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005447 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005448 }
5449
5450 // Dump event currently being dispatched.
5451 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005452 dump += INDENT "PendingEvent:\n";
5453 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005454 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005455 dump += StringPrintf(", age=%" PRId64 "ms\n",
5456 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005457 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005458 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005459 }
5460
5461 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005462 if (!mInboundQueue.empty()) {
5463 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005464 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005465 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005466 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005467 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005468 }
5469 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005470 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005471 }
5472
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005473 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005474 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005475 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005476 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005477 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005478 }
5479 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005480 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005481 }
5482
Prabir Pradhancef936d2021-07-21 16:17:52 +00005483 if (!mCommandQueue.empty()) {
5484 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5485 } else {
5486 dump += INDENT "CommandQueue: <empty>\n";
5487 }
5488
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005489 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005490 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005491 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005492 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005493 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005494 connection->inputChannel->getFd().get(),
5495 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005496 connection->getWindowName().c_str(),
5497 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005498 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005499
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005500 if (!connection->outboundQueue.empty()) {
5501 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5502 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005503 dump += dumpQueue(connection->outboundQueue, currentTime);
5504
Michael Wrightd02c5b62014-02-10 15:10:22 -08005505 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005506 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005507 }
5508
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005509 if (!connection->waitQueue.empty()) {
5510 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5511 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005512 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005513 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005514 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005515 }
5516 }
5517 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005518 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005519 }
5520
5521 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005522 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5523 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005524 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005525 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005526 }
5527
Antonio Kantek15beb512022-06-13 22:35:41 +00005528 if (!mTouchModePerDisplay.empty()) {
5529 dump += INDENT "TouchModePerDisplay:\n";
5530 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5531 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5532 std::to_string(touchMode).c_str());
5533 }
5534 } else {
5535 dump += INDENT "TouchModePerDisplay: <none>\n";
5536 }
5537
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005538 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005539 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5540 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5541 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005542 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005543 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005544}
5545
Michael Wright3dd60e22019-03-27 22:06:44 +00005546void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5547 const size_t numMonitors = monitors.size();
5548 for (size_t i = 0; i < numMonitors; i++) {
5549 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005550 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005551 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5552 dump += "\n";
5553 }
5554}
5555
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005556class LooperEventCallback : public LooperCallback {
5557public:
5558 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5559 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5560
5561private:
5562 std::function<int(int events)> mCallback;
5563};
5564
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005565Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005566 if (DEBUG_CHANNEL_CREATION) {
5567 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5568 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005569
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005570 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005571 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005572 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005573
5574 if (result) {
5575 return base::Error(result) << "Failed to open input channel pair with name " << name;
5576 }
5577
Michael Wrightd02c5b62014-02-10 15:10:22 -08005578 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005579 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005580 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005581 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005582 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005583 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005584
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005585 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5586 ALOGE("Created a new connection, but the token %p is already known", token.get());
5587 }
5588 mConnectionsByToken.emplace(token, connection);
5589
5590 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5591 this, std::placeholders::_1, token);
5592
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005593 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5594 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005595 } // release lock
5596
5597 // Wake the looper because some connections have changed.
5598 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005599 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005600}
5601
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005602Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005603 const std::string& name,
5604 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005605 std::shared_ptr<InputChannel> serverChannel;
5606 std::unique_ptr<InputChannel> clientChannel;
5607 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5608 if (result) {
5609 return base::Error(result) << "Failed to open input channel pair with name " << name;
5610 }
5611
Michael Wright3dd60e22019-03-27 22:06:44 +00005612 { // acquire lock
5613 std::scoped_lock _l(mLock);
5614
5615 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005616 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5617 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005618 }
5619
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005620 sp<Connection> connection =
5621 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005622 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005623 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005624
5625 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5626 ALOGE("Created a new connection, but the token %p is already known", token.get());
5627 }
5628 mConnectionsByToken.emplace(token, connection);
5629 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5630 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005631
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005632 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005633
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005634 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5635 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005636 }
Garfield Tan15601662020-09-22 15:32:38 -07005637
Michael Wright3dd60e22019-03-27 22:06:44 +00005638 // Wake the looper because some connections have changed.
5639 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005640 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005641}
5642
Garfield Tan15601662020-09-22 15:32:38 -07005643status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005644 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005645 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005646
Garfield Tan15601662020-09-22 15:32:38 -07005647 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005648 if (status) {
5649 return status;
5650 }
5651 } // release lock
5652
5653 // Wake the poll loop because removing the connection may have changed the current
5654 // synchronization state.
5655 mLooper->wake();
5656 return OK;
5657}
5658
Garfield Tan15601662020-09-22 15:32:38 -07005659status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5660 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005661 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005662 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005663 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005664 return BAD_VALUE;
5665 }
5666
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005667 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005668
Michael Wrightd02c5b62014-02-10 15:10:22 -08005669 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005670 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005671 }
5672
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005673 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005674
5675 nsecs_t currentTime = now();
5676 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5677
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005678 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005679 return OK;
5680}
5681
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005682void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005683 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5684 auto& [displayId, monitors] = *it;
5685 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5686 return monitor.inputChannel->getConnectionToken() == connectionToken;
5687 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005688
Michael Wright3dd60e22019-03-27 22:06:44 +00005689 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005690 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005691 } else {
5692 ++it;
5693 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005694 }
5695}
5696
Michael Wright3dd60e22019-03-27 22:06:44 +00005697status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005698 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005699 return pilferPointersLocked(token);
5700}
Michael Wright3dd60e22019-03-27 22:06:44 +00005701
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005702status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005703 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5704 if (!requestingChannel) {
5705 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5706 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005707 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005708
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005709 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07005710 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.isEmpty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005711 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5712 " Ignoring.");
5713 return BAD_VALUE;
5714 }
5715
5716 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005717 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005718 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005719 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005720 "input channel stole pointer stream");
5721 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005722 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005723 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005724 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005725 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005726 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005727 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005728 if (channel != nullptr && channel->getConnectionToken() != token) {
5729 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5730 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5731 canceledWindows += channel->getName();
5732 }
5733 }
5734 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5735 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5736 canceledWindows.c_str());
5737
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005738 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005739 // This only blocks relevant pointers to be sent to other windows
5740 window.isPilferingPointers = true;
5741
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005742 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005743 return OK;
5744}
5745
Prabir Pradhan99987712020-11-10 18:43:05 -08005746void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5747 { // acquire lock
5748 std::scoped_lock _l(mLock);
5749 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005750 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005751 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5752 windowHandle != nullptr ? windowHandle->getName().c_str()
5753 : "token without window");
5754 }
5755
Vishnu Nairc519ff72021-01-21 08:23:08 -08005756 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005757 if (focusedToken != windowToken) {
5758 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5759 enabled ? "enable" : "disable");
5760 return;
5761 }
5762
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005763 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005764 ALOGW("Ignoring request to %s Pointer Capture: "
5765 "window has %s requested pointer capture.",
5766 enabled ? "enable" : "disable", enabled ? "already" : "not");
5767 return;
5768 }
5769
Christine Franksb768bb42021-11-29 12:11:31 -08005770 if (enabled) {
5771 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5772 mIneligibleDisplaysForPointerCapture.end(),
5773 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5774 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5775 return;
5776 }
5777 }
5778
Prabir Pradhan99987712020-11-10 18:43:05 -08005779 setPointerCaptureLocked(enabled);
5780 } // release lock
5781
5782 // Wake the thread to process command entries.
5783 mLooper->wake();
5784}
5785
Christine Franksb768bb42021-11-29 12:11:31 -08005786void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5787 { // acquire lock
5788 std::scoped_lock _l(mLock);
5789 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5790 if (!isEligible) {
5791 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5792 }
5793 } // release lock
5794}
5795
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005796std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5797 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005798 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005799 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005800 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005801 }
5802 }
5803 }
5804 return std::nullopt;
5805}
5806
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005807sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005808 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005809 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005810 }
5811
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005812 for (const auto& [token, connection] : mConnectionsByToken) {
5813 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005814 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005815 }
5816 }
Robert Carr4e670e52018-08-15 13:26:12 -07005817
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005818 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005819}
5820
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005821std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5822 sp<Connection> connection = getConnectionLocked(connectionToken);
5823 if (connection == nullptr) {
5824 return "<nullptr>";
5825 }
5826 return connection->getInputChannelName();
5827}
5828
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005829void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005830 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005831 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005832}
5833
Prabir Pradhancef936d2021-07-21 16:17:52 +00005834void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5835 const sp<Connection>& connection, uint32_t seq,
5836 bool handled, nsecs_t consumeTime) {
5837 // Handle post-event policy actions.
5838 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5839 if (dispatchEntryIt == connection->waitQueue.end()) {
5840 return;
5841 }
5842 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5843 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5844 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5845 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5846 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5847 }
5848 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5849 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5850 connection->inputChannel->getConnectionToken(),
5851 dispatchEntry->deliveryTime, consumeTime, finishTime);
5852 }
5853
5854 bool restartEvent;
5855 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5856 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5857 restartEvent =
5858 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5859 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5860 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5861 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5862 handled);
5863 } else {
5864 restartEvent = false;
5865 }
5866
5867 // Dequeue the event and start the next cycle.
5868 // Because the lock might have been released, it is possible that the
5869 // contents of the wait queue to have been drained, so we need to double-check
5870 // a few things.
5871 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5872 if (dispatchEntryIt != connection->waitQueue.end()) {
5873 dispatchEntry = *dispatchEntryIt;
5874 connection->waitQueue.erase(dispatchEntryIt);
5875 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5876 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5877 if (!connection->responsive) {
5878 connection->responsive = isConnectionResponsive(*connection);
5879 if (connection->responsive) {
5880 // The connection was unresponsive, and now it's responsive.
5881 processConnectionResponsiveLocked(*connection);
5882 }
5883 }
5884 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005885 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005886 connection->outboundQueue.push_front(dispatchEntry);
5887 traceOutboundQueueLength(*connection);
5888 } else {
5889 releaseDispatchEntry(dispatchEntry);
5890 }
5891 }
5892
5893 // Start the next dispatch cycle for this connection.
5894 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005895}
5896
Prabir Pradhancef936d2021-07-21 16:17:52 +00005897void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5898 const sp<IBinder>& newToken) {
5899 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5900 scoped_unlock unlock(mLock);
5901 mPolicy->notifyFocusChanged(oldToken, newToken);
5902 };
5903 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005904}
5905
Prabir Pradhancef936d2021-07-21 16:17:52 +00005906void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5907 auto command = [this, token, x, y]() REQUIRES(mLock) {
5908 scoped_unlock unlock(mLock);
5909 mPolicy->notifyDropWindow(token, x, y);
5910 };
5911 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005912}
5913
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005914void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5915 if (connection == nullptr) {
5916 LOG_ALWAYS_FATAL("Caller must check for nullness");
5917 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005918 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5919 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005920 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005921 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005922 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005923 return;
5924 }
5925 /**
5926 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5927 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5928 * has changed. This could cause newer entries to time out before the already dispatched
5929 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5930 * processes the events linearly. So providing information about the oldest entry seems to be
5931 * most useful.
5932 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005933 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005934 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5935 std::string reason =
5936 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005937 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005938 ns2ms(currentWait),
5939 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005940 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005941 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005942
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005943 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5944
5945 // Stop waking up for events on this connection, it is already unresponsive
5946 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005947}
5948
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005949void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5950 std::string reason =
5951 StringPrintf("%s does not have a focused window", application->getName().c_str());
5952 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005953
Prabir Pradhancef936d2021-07-21 16:17:52 +00005954 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5955 scoped_unlock unlock(mLock);
5956 mPolicy->notifyNoFocusedWindowAnr(application);
5957 };
5958 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005959}
5960
chaviw98318de2021-05-19 16:45:23 -05005961void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005962 const std::string& reason) {
5963 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5964 updateLastAnrStateLocked(windowLabel, reason);
5965}
5966
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005967void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5968 const std::string& reason) {
5969 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005970 updateLastAnrStateLocked(windowLabel, reason);
5971}
5972
5973void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5974 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005975 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005976 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005977 struct tm tm;
5978 localtime_r(&t, &tm);
5979 char timestr[64];
5980 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005981 mLastAnrState.clear();
5982 mLastAnrState += INDENT "ANR:\n";
5983 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005984 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5985 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005986 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005987}
5988
Prabir Pradhancef936d2021-07-21 16:17:52 +00005989void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5990 KeyEntry& entry) {
5991 const KeyEvent event = createKeyEvent(entry);
5992 nsecs_t delay = 0;
5993 { // release lock
5994 scoped_unlock unlock(mLock);
5995 android::base::Timer t;
5996 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5997 entry.policyFlags);
5998 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5999 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6000 std::to_string(t.duration().count()).c_str());
6001 }
6002 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006003
6004 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006005 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006006 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006007 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006008 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006009 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006010 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006012}
6013
Prabir Pradhancef936d2021-07-21 16:17:52 +00006014void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006015 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006016 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006017 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006018 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006019 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006020 };
6021 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006022}
6023
Prabir Pradhanedd96402022-02-15 01:46:16 -08006024void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6025 std::optional<int32_t> pid) {
6026 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006027 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006028 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006029 };
6030 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006031}
6032
6033/**
6034 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6035 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6036 * command entry to the command queue.
6037 */
6038void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6039 std::string reason) {
6040 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006041 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006042 if (connection.monitor) {
6043 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6044 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006045 pid = findMonitorPidByTokenLocked(connectionToken);
6046 } else {
6047 // The connection is a window
6048 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6049 reason.c_str());
6050 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6051 if (handle != nullptr) {
6052 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006053 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006054 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006055 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006056}
6057
6058/**
6059 * Tell the policy that a connection has become responsive so that it can stop ANR.
6060 */
6061void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6062 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006063 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006064 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006065 pid = findMonitorPidByTokenLocked(connectionToken);
6066 } else {
6067 // The connection is a window
6068 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6069 if (handle != nullptr) {
6070 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006071 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006072 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006073 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006074}
6075
Prabir Pradhancef936d2021-07-21 16:17:52 +00006076bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006077 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006078 KeyEntry& keyEntry, bool handled) {
6079 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006080 if (!handled) {
6081 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006082 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006083 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006084 return false;
6085 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006086
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006087 // Get the fallback key state.
6088 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006089 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006090 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006091 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006092 connection->inputState.removeFallbackKey(originalKeyCode);
6093 }
6094
6095 if (handled || !dispatchEntry->hasForegroundTarget()) {
6096 // If the application handles the original key for which we previously
6097 // generated a fallback or if the window is not a foreground window,
6098 // then cancel the associated fallback key, if any.
6099 if (fallbackKeyCode != -1) {
6100 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006101 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6102 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6103 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6104 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6105 keyEntry.policyFlags);
6106 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006107 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006108 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006109
6110 mLock.unlock();
6111
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006112 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006113 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006114
6115 mLock.lock();
6116
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006117 // Cancel the fallback key.
6118 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006119 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006120 "application handled the original non-fallback key "
6121 "or is no longer a foreground target, "
6122 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006123 options.keyCode = fallbackKeyCode;
6124 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006125 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006126 connection->inputState.removeFallbackKey(originalKeyCode);
6127 }
6128 } else {
6129 // If the application did not handle a non-fallback key, first check
6130 // that we are in a good state to perform unhandled key event processing
6131 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006132 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006133 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006134 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6135 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6136 "since this is not an initial down. "
6137 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6138 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6139 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006140 return false;
6141 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006142
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006143 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006144 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6145 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6146 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6147 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6148 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006149 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006150
6151 mLock.unlock();
6152
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006153 bool fallback =
6154 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006155 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006156
6157 mLock.lock();
6158
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006159 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006160 connection->inputState.removeFallbackKey(originalKeyCode);
6161 return false;
6162 }
6163
6164 // Latch the fallback keycode for this key on an initial down.
6165 // The fallback keycode cannot change at any other point in the lifecycle.
6166 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006167 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006168 fallbackKeyCode = event.getKeyCode();
6169 } else {
6170 fallbackKeyCode = AKEYCODE_UNKNOWN;
6171 }
6172 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6173 }
6174
6175 ALOG_ASSERT(fallbackKeyCode != -1);
6176
6177 // Cancel the fallback key if the policy decides not to send it anymore.
6178 // We will continue to dispatch the key to the policy but we will no
6179 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006180 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6181 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006182 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6183 if (fallback) {
6184 ALOGD("Unhandled key event: Policy requested to send key %d"
6185 "as a fallback for %d, but on the DOWN it had requested "
6186 "to send %d instead. Fallback canceled.",
6187 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6188 } else {
6189 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6190 "but on the DOWN it had requested to send %d. "
6191 "Fallback canceled.",
6192 originalKeyCode, fallbackKeyCode);
6193 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006194 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006195
Michael Wrightfb04fd52022-11-24 22:31:11 +00006196 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006197 "canceling fallback, policy no longer desires it");
6198 options.keyCode = fallbackKeyCode;
6199 synthesizeCancelationEventsForConnectionLocked(connection, options);
6200
6201 fallback = false;
6202 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006203 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006204 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006205 }
6206 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006207
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006208 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6209 {
6210 std::string msg;
6211 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6212 connection->inputState.getFallbackKeys();
6213 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6214 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6215 }
6216 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6217 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006218 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006219 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006220
6221 if (fallback) {
6222 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006223 keyEntry.eventTime = event.getEventTime();
6224 keyEntry.deviceId = event.getDeviceId();
6225 keyEntry.source = event.getSource();
6226 keyEntry.displayId = event.getDisplayId();
6227 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6228 keyEntry.keyCode = fallbackKeyCode;
6229 keyEntry.scanCode = event.getScanCode();
6230 keyEntry.metaState = event.getMetaState();
6231 keyEntry.repeatCount = event.getRepeatCount();
6232 keyEntry.downTime = event.getDownTime();
6233 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006234
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006235 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6236 ALOGD("Unhandled key event: Dispatching fallback key. "
6237 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6238 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6239 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006240 return true; // restart the event
6241 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006242 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6243 ALOGD("Unhandled key event: No fallback key.");
6244 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006245
6246 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006247 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006248 }
6249 }
6250 return false;
6251}
6252
Prabir Pradhancef936d2021-07-21 16:17:52 +00006253bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006254 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006255 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006256 return false;
6257}
6258
Michael Wrightd02c5b62014-02-10 15:10:22 -08006259void InputDispatcher::traceInboundQueueLengthLocked() {
6260 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006261 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006262 }
6263}
6264
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006265void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006266 if (ATRACE_ENABLED()) {
6267 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006268 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6269 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006270 }
6271}
6272
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006273void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006274 if (ATRACE_ENABLED()) {
6275 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006276 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6277 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006278 }
6279}
6280
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006281void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006282 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006283
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006284 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006285 dumpDispatchStateLocked(dump);
6286
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006287 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006288 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006289 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006290 }
6291}
6292
6293void InputDispatcher::monitor() {
6294 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006295 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006296 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006297 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006298}
6299
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006300/**
6301 * Wake up the dispatcher and wait until it processes all events and commands.
6302 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6303 * this method can be safely called from any thread, as long as you've ensured that
6304 * the work you are interested in completing has already been queued.
6305 */
6306bool InputDispatcher::waitForIdle() {
6307 /**
6308 * Timeout should represent the longest possible time that a device might spend processing
6309 * events and commands.
6310 */
6311 constexpr std::chrono::duration TIMEOUT = 100ms;
6312 std::unique_lock lock(mLock);
6313 mLooper->wake();
6314 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6315 return result == std::cv_status::no_timeout;
6316}
6317
Vishnu Naire798b472020-07-23 13:52:21 -07006318/**
6319 * Sets focus to the window identified by the token. This must be called
6320 * after updating any input window handles.
6321 *
6322 * Params:
6323 * request.token - input channel token used to identify the window that should gain focus.
6324 * request.focusedToken - the token that the caller expects currently to be focused. If the
6325 * specified token does not match the currently focused window, this request will be dropped.
6326 * If the specified focused token matches the currently focused window, the call will succeed.
6327 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6328 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6329 * when requesting the focus change. This determines which request gets
6330 * precedence if there is a focus change request from another source such as pointer down.
6331 */
Vishnu Nair958da932020-08-21 17:12:37 -07006332void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6333 { // acquire lock
6334 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006335 std::optional<FocusResolver::FocusChanges> changes =
6336 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6337 if (changes) {
6338 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006339 }
6340 } // release lock
6341 // Wake up poll loop since it may need to make new input dispatching choices.
6342 mLooper->wake();
6343}
6344
Vishnu Nairc519ff72021-01-21 08:23:08 -08006345void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6346 if (changes.oldFocus) {
6347 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006348 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006349 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006350 "focus left window");
6351 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006352 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006353 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006354 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006355 if (changes.newFocus) {
6356 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006357 }
6358
Prabir Pradhan99987712020-11-10 18:43:05 -08006359 // If a window has pointer capture, then it must have focus. We need to ensure that this
6360 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6361 // If the window loses focus before it loses pointer capture, then the window can be in a state
6362 // where it has pointer capture but not focus, violating the contract. Therefore we must
6363 // dispatch the pointer capture event before the focus event. Since focus events are added to
6364 // the front of the queue (above), we add the pointer capture event to the front of the queue
6365 // after the focus events are added. This ensures the pointer capture event ends up at the
6366 // front.
6367 disablePointerCaptureForcedLocked();
6368
Vishnu Nairc519ff72021-01-21 08:23:08 -08006369 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006370 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006371 }
6372}
Vishnu Nair958da932020-08-21 17:12:37 -07006373
Prabir Pradhan99987712020-11-10 18:43:05 -08006374void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006375 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006376 return;
6377 }
6378
6379 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6380
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006381 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006382 setPointerCaptureLocked(false);
6383 }
6384
6385 if (!mWindowTokenWithPointerCapture) {
6386 // No need to send capture changes because no window has capture.
6387 return;
6388 }
6389
6390 if (mPendingEvent != nullptr) {
6391 // Move the pending event to the front of the queue. This will give the chance
6392 // for the pending event to be dropped if it is a captured event.
6393 mInboundQueue.push_front(mPendingEvent);
6394 mPendingEvent = nullptr;
6395 }
6396
6397 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006398 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006399 mInboundQueue.push_front(std::move(entry));
6400}
6401
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006402void InputDispatcher::setPointerCaptureLocked(bool enable) {
6403 mCurrentPointerCaptureRequest.enable = enable;
6404 mCurrentPointerCaptureRequest.seq++;
6405 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006406 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006407 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006408 };
6409 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006410}
6411
Vishnu Nair599f1412021-06-21 10:39:58 -07006412void InputDispatcher::displayRemoved(int32_t displayId) {
6413 { // acquire lock
6414 std::scoped_lock _l(mLock);
6415 // Set an empty list to remove all handles from the specific display.
6416 setInputWindowsLocked(/* window handles */ {}, displayId);
6417 setFocusedApplicationLocked(displayId, nullptr);
6418 // Call focus resolver to clean up stale requests. This must be called after input windows
6419 // have been removed for the removed display.
6420 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006421 // Reset pointer capture eligibility, regardless of previous state.
6422 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006423 // Remove the associated touch mode state.
6424 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006425 } // release lock
6426
6427 // Wake up poll loop since it may need to make new input dispatching choices.
6428 mLooper->wake();
6429}
6430
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006431void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6432 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006433 // The listener sends the windows as a flattened array. Separate the windows by display for
6434 // more convenient parsing.
6435 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006436 for (const auto& info : windowInfos) {
6437 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006438 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006439 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006440
6441 { // acquire lock
6442 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006443
6444 // Ensure that we have an entry created for all existing displays so that if a displayId has
6445 // no windows, we can tell that the windows were removed from the display.
6446 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6447 handlesPerDisplay[displayId];
6448 }
6449
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006450 mDisplayInfos.clear();
6451 for (const auto& displayInfo : displayInfos) {
6452 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6453 }
6454
6455 for (const auto& [displayId, handles] : handlesPerDisplay) {
6456 setInputWindowsLocked(handles, displayId);
6457 }
6458 }
6459 // Wake up poll loop since it may need to make new input dispatching choices.
6460 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006461}
6462
Vishnu Nair062a8672021-09-03 16:07:44 -07006463bool InputDispatcher::shouldDropInput(
6464 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006465 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6466 (windowHandle->getInfo()->inputConfig.test(
6467 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006468 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006469 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6470 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006471 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006472 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006473 windowHandle->getInfo()->displayId);
6474 return true;
6475 }
6476 return false;
6477}
6478
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006479void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6480 const std::vector<gui::WindowInfo>& windowInfos,
6481 const std::vector<DisplayInfo>& displayInfos) {
6482 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6483}
6484
Arthur Hungdfd528e2021-12-08 13:23:04 +00006485void InputDispatcher::cancelCurrentTouch() {
6486 {
6487 std::scoped_lock _l(mLock);
6488 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006489 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006490 "cancel current touch");
6491 synthesizeCancelationEventsForAllConnectionsLocked(options);
6492
6493 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006494 }
6495 // Wake up poll loop since there might be work to do.
6496 mLooper->wake();
6497}
6498
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006499void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6500 std::scoped_lock _l(mLock);
6501 mMonitorDispatchingTimeout = timeout;
6502}
6503
Garfield Tane84e6f92019-08-29 17:28:41 -07006504} // namespace android::inputdispatcher