blob: 37a451b3dd7472c0d356a26d341e1abc2ae7eae1 [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 Vishniakoub581f7f2022-12-07 20:23:06 +0000557/**
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 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
612 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
613 }
614 out.push_back(touchedWindow);
615 }
616 return out;
617}
618
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000619} // namespace
620
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621// --- InputDispatcher ---
622
Garfield Tan00f511d2019-06-12 16:55:40 -0700623InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800624 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
625
626InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
627 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700628 : mPolicy(policy),
629 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700630 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800631 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700632 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700633 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700634 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800635 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700636 mDispatchEnabled(false),
637 mDispatchFrozen(false),
638 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100639 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000640 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800641 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800642 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000643 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000644 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700645 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800646 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800647
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700648 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700649#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700650 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700651#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700652 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800653 policy->getDispatcherConfiguration(&mConfig);
654}
655
656InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000657 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800658
Prabir Pradhancef936d2021-07-21 16:17:52 +0000659 resetKeyRepeatLocked();
660 releasePendingEventLocked();
661 drainInboundQueueLocked();
662 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800663
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000664 while (!mConnectionsByToken.empty()) {
665 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000666 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
667 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668 }
669}
670
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700671status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700672 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700673 return ALREADY_EXISTS;
674 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700675 mThread = std::make_unique<InputThread>(
676 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
677 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700678}
679
680status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700681 if (mThread && mThread->isCallingThread()) {
682 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700683 return INVALID_OPERATION;
684 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700685 mThread.reset();
686 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700687}
688
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700690 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800691 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800692 std::scoped_lock _l(mLock);
693 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800694
695 // Run a dispatch loop if there are no pending commands.
696 // The dispatch loop might enqueue commands to run afterwards.
697 if (!haveCommandsLocked()) {
698 dispatchOnceInnerLocked(&nextWakeupTime);
699 }
700
701 // Run all pending commands if there are any.
702 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000703 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700704 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800705 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800706
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700707 // If we are still waiting for ack on some events,
708 // we might have to wake up earlier to check if an app is anr'ing.
709 const nsecs_t nextAnrCheck = processAnrsLocked();
710 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
711
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800712 // We are about to enter an infinitely long sleep, because we have no commands or
713 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700714 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800715 mDispatcherEnteredIdle.notify_all();
716 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800717 } // release lock
718
719 // Wait for callback or timeout or wake. (make sure we round up, not down)
720 nsecs_t currentTime = now();
721 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
722 mLooper->pollOnce(timeoutMillis);
723}
724
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700725/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500726 * Raise ANR if there is no focused window.
727 * Before the ANR is raised, do a final state check:
728 * 1. The currently focused application must be the same one we are waiting for.
729 * 2. Ensure we still don't have a focused window.
730 */
731void InputDispatcher::processNoFocusedWindowAnrLocked() {
732 // Check if the application that we are waiting for is still focused.
733 std::shared_ptr<InputApplicationHandle> focusedApplication =
734 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
735 if (focusedApplication == nullptr ||
736 focusedApplication->getApplicationToken() !=
737 mAwaitedFocusedApplication->getApplicationToken()) {
738 // Unexpected because we should have reset the ANR timer when focused application changed
739 ALOGE("Waited for a focused window, but focused application has already changed to %s",
740 focusedApplication->getName().c_str());
741 return; // The focused application has changed.
742 }
743
chaviw98318de2021-05-19 16:45:23 -0500744 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500745 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
746 if (focusedWindowHandle != nullptr) {
747 return; // We now have a focused window. No need for ANR.
748 }
749 onAnrLocked(mAwaitedFocusedApplication);
750}
751
752/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700753 * Check if any of the connections' wait queues have events that are too old.
754 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
755 * Return the time at which we should wake up next.
756 */
757nsecs_t InputDispatcher::processAnrsLocked() {
758 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700759 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700760 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
761 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
762 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500763 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700764 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500765 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700766 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700767 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500768 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700769 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
770 }
771 }
772
773 // Check if any connection ANRs are due
774 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
775 if (currentTime < nextAnrCheck) { // most likely scenario
776 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
777 }
778
779 // If we reached here, we have an unresponsive connection.
780 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
781 if (connection == nullptr) {
782 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
783 return nextAnrCheck;
784 }
785 connection->responsive = false;
786 // Stop waking up for this unresponsive connection
787 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000788 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700789 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700790}
791
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800792std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
793 const sp<Connection>& connection) {
794 if (connection->monitor) {
795 return mMonitorDispatchingTimeout;
796 }
797 const sp<WindowInfoHandle> window =
798 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700799 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500800 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700801 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500802 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700803}
804
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
806 nsecs_t currentTime = now();
807
Jeff Browndc5992e2014-04-11 01:27:26 -0700808 // Reset the key repeat timer whenever normal dispatch is suspended while the
809 // device is in a non-interactive state. This is to ensure that we abort a key
810 // repeat if the device is just coming out of sleep.
811 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812 resetKeyRepeatLocked();
813 }
814
815 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
816 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100817 if (DEBUG_FOCUS) {
818 ALOGD("Dispatch frozen. Waiting some more.");
819 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800820 return;
821 }
822
823 // Optimize latency of app switches.
824 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
825 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
826 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
827 if (mAppSwitchDueTime < *nextWakeupTime) {
828 *nextWakeupTime = mAppSwitchDueTime;
829 }
830
831 // Ready to start a new event.
832 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700833 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700834 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800835 if (isAppSwitchDue) {
836 // The inbound queue is empty so the app switch key we were waiting
837 // for will never arrive. Stop waiting for it.
838 resetPendingAppSwitchLocked(false);
839 isAppSwitchDue = false;
840 }
841
842 // Synthesize a key repeat if appropriate.
843 if (mKeyRepeatState.lastKeyEntry) {
844 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
845 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
846 } else {
847 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
848 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
849 }
850 }
851 }
852
853 // Nothing to do if there is no pending event.
854 if (!mPendingEvent) {
855 return;
856 }
857 } else {
858 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700859 mPendingEvent = mInboundQueue.front();
860 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861 traceInboundQueueLengthLocked();
862 }
863
864 // Poke user activity for this event.
865 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700866 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868 }
869
870 // Now we have an event to dispatch.
871 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700872 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700874 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700876 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700878 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800879 }
880
881 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700882 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883 }
884
885 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700886 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700887 const ConfigurationChangedEntry& typedEntry =
888 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700889 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700890 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700891 break;
892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700894 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700895 const DeviceResetEntry& typedEntry =
896 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700897 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700898 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700899 break;
900 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100902 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700903 std::shared_ptr<FocusEntry> typedEntry =
904 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100905 dispatchFocusLocked(currentTime, typedEntry);
906 done = true;
907 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
908 break;
909 }
910
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700911 case EventEntry::Type::TOUCH_MODE_CHANGED: {
912 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
913 dispatchTouchModeChangeLocked(currentTime, typedEntry);
914 done = true;
915 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
916 break;
917 }
918
Prabir Pradhan99987712020-11-10 18:43:05 -0800919 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
920 const auto typedEntry =
921 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
922 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
923 done = true;
924 break;
925 }
926
arthurhungb89ccb02020-12-30 16:19:01 +0800927 case EventEntry::Type::DRAG: {
928 std::shared_ptr<DragEntry> typedEntry =
929 std::static_pointer_cast<DragEntry>(mPendingEvent);
930 dispatchDragLocked(currentTime, typedEntry);
931 done = true;
932 break;
933 }
934
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700935 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700936 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700937 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700938 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700939 resetPendingAppSwitchLocked(true);
940 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700941 } else if (dropReason == DropReason::NOT_DROPPED) {
942 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700943 }
944 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700945 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700946 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700947 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700948 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
949 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700950 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700951 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700952 break;
953 }
954
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700955 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700956 std::shared_ptr<MotionEntry> motionEntry =
957 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700958 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
959 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700961 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700962 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700963 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700964 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
965 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700966 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700967 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700968 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 }
Chris Yef59a2f42020-10-16 12:55:26 -0700970
971 case EventEntry::Type::SENSOR: {
972 std::shared_ptr<SensorEntry> sensorEntry =
973 std::static_pointer_cast<SensorEntry>(mPendingEvent);
974 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
975 dropReason = DropReason::APP_SWITCH;
976 }
977 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
978 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
979 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
980 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
981 dropReason = DropReason::STALE;
982 }
983 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
984 done = true;
985 break;
986 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987 }
988
989 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700990 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700991 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992 }
Michael Wright3a981722015-06-10 15:26:13 +0100993 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994
995 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -0700996 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997 }
998}
999
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001000bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1001 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1002}
1003
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001004/**
1005 * Return true if the events preceding this incoming motion event should be dropped
1006 * Return false otherwise (the default behaviour)
1007 */
1008bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001009 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001010 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001011
1012 // Optimize case where the current application is unresponsive and the user
1013 // decides to touch a window in a different application.
1014 // If the application takes too long to catch up then we drop all events preceding
1015 // the touch into the other window.
1016 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001017 const int32_t displayId = motionEntry.displayId;
1018 const auto [x, y] = resolveTouchedPosition(motionEntry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07001019 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001020
chaviw98318de2021-05-19 16:45:23 -05001021 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -07001022 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001023 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001024 touchedWindowHandle->getApplicationToken() !=
1025 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001026 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001027 ALOGI("Pruning input queue because user touched a different application while waiting "
1028 "for %s",
1029 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001030 return true;
1031 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001032
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001033 // Alternatively, maybe there's a spy window that could handle this event.
1034 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1035 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1036 for (const auto& windowHandle : touchedSpies) {
1037 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001038 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001039 // This spy window could take more input. Drop all events preceding this
1040 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001041 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001042 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001043 mAwaitedFocusedApplication->getName().c_str());
1044 return true;
1045 }
1046 }
1047 }
1048
1049 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1050 // yet been processed by some connections, the dispatcher will wait for these motion
1051 // events to be processed before dispatching the key event. This is because these motion events
1052 // may cause a new window to be launched, which the user might expect to receive focus.
1053 // To prevent waiting forever for such events, just send the key to the currently focused window
1054 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1055 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1056 "just send the pending key event to the focused window.");
1057 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001058 }
1059 return false;
1060}
1061
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001062bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001063 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001064 mInboundQueue.push_back(std::move(newEntry));
1065 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066 traceInboundQueueLengthLocked();
1067
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001068 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001069 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001070 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1071 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001072 // Optimize app switch latency.
1073 // If the application takes too long to catch up then we drop all events preceding
1074 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001075 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001076 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001077 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001079 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001080 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001081 if (DEBUG_APP_SWITCH) {
1082 ALOGD("App switch is pending!");
1083 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001084 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001085 mAppSwitchSawKeyDown = false;
1086 needWake = true;
1087 }
1088 }
1089 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001090
1091 // If a new up event comes in, and the pending event with same key code has been asked
1092 // to try again later because of the policy. We have to reset the intercept key wake up
1093 // time for it may have been handled in the policy and could be dropped.
1094 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1095 mPendingEvent->type == EventEntry::Type::KEY) {
1096 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1097 if (pendingKey.keyCode == keyEntry.keyCode &&
1098 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001099 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1100 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001101 pendingKey.interceptKeyWakeupTime = 0;
1102 needWake = true;
1103 }
1104 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001105 break;
1106 }
1107
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001108 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001109 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1110 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001111 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1112 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001113 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001115 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001116 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001117 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001118 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1119 break;
1120 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001121 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001122 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001123 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001124 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001125 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1126 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001127 // nothing to do
1128 break;
1129 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130 }
1131
1132 return needWake;
1133}
1134
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001135void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001136 // Do not store sensor event in recent queue to avoid flooding the queue.
1137 if (entry->type != EventEntry::Type::SENSOR) {
1138 mRecentQueue.push_back(entry);
1139 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001140 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001141 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142 }
1143}
1144
chaviw98318de2021-05-19 16:45:23 -05001145sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1146 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001147 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001148 bool addOutsideTargets,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07001149 bool ignoreDragWindow) const {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001150 if (addOutsideTargets && touchState == nullptr) {
1151 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001152 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001154 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001155 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001156 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001157 continue;
1158 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001160 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001161 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001162 return windowHandle;
1163 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001164
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001165 if (addOutsideTargets &&
1166 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001167 touchState->addOrUpdateWindow(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001168 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169 }
1170 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001171 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001172}
1173
Prabir Pradhand65552b2021-10-07 11:23:50 -07001174std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1175 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001176 // Traverse windows from front to back and gather the touched spy windows.
1177 std::vector<sp<WindowInfoHandle>> spyWindows;
1178 const auto& windowHandles = getWindowHandlesLocked(displayId);
1179 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1180 const WindowInfo& info = *windowHandle->getInfo();
1181
Prabir Pradhand65552b2021-10-07 11:23:50 -07001182 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001183 continue;
1184 }
1185 if (!info.isSpy()) {
1186 // The first touched non-spy window was found, so return the spy windows touched so far.
1187 return spyWindows;
1188 }
1189 spyWindows.push_back(windowHandle);
1190 }
1191 return spyWindows;
1192}
1193
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001194void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195 const char* reason;
1196 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001197 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001198 if (DEBUG_INBOUND_EVENT_DETAILS) {
1199 ALOGD("Dropped event because policy consumed it.");
1200 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001201 reason = "inbound event was dropped because the policy consumed it";
1202 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001203 case DropReason::DISABLED:
1204 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001205 ALOGI("Dropped event because input dispatch is disabled.");
1206 }
1207 reason = "inbound event was dropped because input dispatch is disabled";
1208 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001209 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001210 ALOGI("Dropped event because of pending overdue app switch.");
1211 reason = "inbound event was dropped because of pending overdue app switch";
1212 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001213 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001214 ALOGI("Dropped event because the current application is not responding and the user "
1215 "has started interacting with a different application.");
1216 reason = "inbound event was dropped because the current application is not responding "
1217 "and the user has started interacting with a different application";
1218 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001219 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001220 ALOGI("Dropped event because it is stale.");
1221 reason = "inbound event was dropped because it is stale";
1222 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001223 case DropReason::NO_POINTER_CAPTURE:
1224 ALOGI("Dropped event because there is no window with Pointer Capture.");
1225 reason = "inbound event was dropped because there is no window with Pointer Capture";
1226 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001227 case DropReason::NOT_DROPPED: {
1228 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001229 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001230 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001231 }
1232
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001233 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001234 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001235 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001237 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001239 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001240 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1241 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001242 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001243 synthesizeCancelationEventsForAllConnectionsLocked(options);
1244 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001245 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1246 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001247 synthesizeCancelationEventsForAllConnectionsLocked(options);
1248 }
1249 break;
1250 }
Chris Yef59a2f42020-10-16 12:55:26 -07001251 case EventEntry::Type::SENSOR: {
1252 break;
1253 }
arthurhungb89ccb02020-12-30 16:19:01 +08001254 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1255 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001256 break;
1257 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001258 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001259 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001260 case EventEntry::Type::CONFIGURATION_CHANGED:
1261 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001262 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001263 break;
1264 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 }
1266}
1267
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001268static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001269 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1270 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271}
1272
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001273bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1274 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1275 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1276 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277}
1278
1279bool InputDispatcher::isAppSwitchPendingLocked() {
Colin Cross5b799302022-10-18 21:52:41 -07001280 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001281}
1282
1283void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001284 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001285
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001286 if (DEBUG_APP_SWITCH) {
1287 if (handled) {
1288 ALOGD("App switch has arrived.");
1289 } else {
1290 ALOGD("App switch was abandoned.");
1291 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001292 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293}
1294
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001296 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001297}
1298
Prabir Pradhancef936d2021-07-21 16:17:52 +00001299bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001300 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001301 return false;
1302 }
1303
1304 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001305 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001306 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001307 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1308 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001309 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310 return true;
1311}
1312
Prabir Pradhancef936d2021-07-21 16:17:52 +00001313void InputDispatcher::postCommandLocked(Command&& command) {
1314 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315}
1316
1317void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001318 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001319 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001320 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321 releaseInboundEventLocked(entry);
1322 }
1323 traceInboundQueueLengthLocked();
1324}
1325
1326void InputDispatcher::releasePendingEventLocked() {
1327 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001329 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330 }
1331}
1332
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001333void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001334 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001335 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001336 if (DEBUG_DISPATCH_CYCLE) {
1337 ALOGD("Injected inbound event was dropped.");
1338 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001339 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 }
1341 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001342 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343 }
1344 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345}
1346
1347void InputDispatcher::resetKeyRepeatLocked() {
1348 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001349 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001350 }
1351}
1352
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001353std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1354 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355
Michael Wright2e732952014-09-24 13:26:59 -07001356 uint32_t policyFlags = entry->policyFlags &
1357 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001359 std::shared_ptr<KeyEntry> newEntry =
1360 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1361 entry->source, entry->displayId, policyFlags, entry->action,
1362 entry->flags, entry->keyCode, entry->scanCode,
1363 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001365 newEntry->syntheticRepeat = true;
1366 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001367 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001368 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369}
1370
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001371bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001372 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001373 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1374 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1375 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376
1377 // Reset key repeating in case a keyboard device was added or removed or something.
1378 resetKeyRepeatLocked();
1379
1380 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001381 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1382 scoped_unlock unlock(mLock);
1383 mPolicy->notifyConfigurationChanged(eventTime);
1384 };
1385 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386 return true;
1387}
1388
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001389bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1390 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001391 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1392 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1393 entry.deviceId);
1394 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395
liushenxiang42232912021-05-21 20:24:09 +08001396 // Reset key repeating in case a keyboard device was disabled or enabled.
1397 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1398 resetKeyRepeatLocked();
1399 }
1400
Michael Wrightfb04fd52022-11-24 22:31:11 +00001401 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001402 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001403 synthesizeCancelationEventsForAllConnectionsLocked(options);
1404 return true;
1405}
1406
Vishnu Nairad321cd2020-08-20 16:40:21 -07001407void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001408 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001409 if (mPendingEvent != nullptr) {
1410 // Move the pending event to the front of the queue. This will give the chance
1411 // for the pending event to get dispatched to the newly focused window
1412 mInboundQueue.push_front(mPendingEvent);
1413 mPendingEvent = nullptr;
1414 }
1415
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001416 std::unique_ptr<FocusEntry> focusEntry =
1417 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1418 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001419
1420 // This event should go to the front of the queue, but behind all other focus events
1421 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001422 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001423 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001424 [](const std::shared_ptr<EventEntry>& event) {
1425 return event->type == EventEntry::Type::FOCUS;
1426 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001427
1428 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001429 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001430}
1431
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001432void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001433 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001434 if (channel == nullptr) {
1435 return; // Window has gone away
1436 }
1437 InputTarget target;
1438 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001439 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001440 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001441 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1442 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001443 std::string reason = std::string("reason=").append(entry->reason);
1444 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001445 dispatchEventLocked(currentTime, entry, {target});
1446}
1447
Prabir Pradhan99987712020-11-10 18:43:05 -08001448void InputDispatcher::dispatchPointerCaptureChangedLocked(
1449 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1450 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001451 dropReason = DropReason::NOT_DROPPED;
1452
Prabir Pradhan99987712020-11-10 18:43:05 -08001453 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001454 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001455
1456 if (entry->pointerCaptureRequest.enable) {
1457 // Enable Pointer Capture.
1458 if (haveWindowWithPointerCapture &&
1459 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001460 // This can happen if pointer capture is disabled and re-enabled before we notify the
1461 // app of the state change, so there is no need to notify the app.
1462 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1463 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001464 }
1465 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001466 // This can happen if a window requests capture and immediately releases capture.
1467 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001468 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001469 return;
1470 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001471 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1472 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1473 return;
1474 }
1475
Vishnu Nairc519ff72021-01-21 08:23:08 -08001476 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001477 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1478 mWindowTokenWithPointerCapture = token;
1479 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001480 // Disable Pointer Capture.
1481 // We do not check if the sequence number matches for requests to disable Pointer Capture
1482 // for two reasons:
1483 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1484 // to disable capture with the same sequence number: one generated by
1485 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1486 // Capture being disabled in InputReader.
1487 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1488 // actual Pointer Capture state that affects events being generated by input devices is
1489 // in InputReader.
1490 if (!haveWindowWithPointerCapture) {
1491 // Pointer capture was already forcefully disabled because of focus change.
1492 dropReason = DropReason::NOT_DROPPED;
1493 return;
1494 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001495 token = mWindowTokenWithPointerCapture;
1496 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001497 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001498 setPointerCaptureLocked(false);
1499 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001500 }
1501
1502 auto channel = getInputChannelLocked(token);
1503 if (channel == nullptr) {
1504 // Window has gone away, clean up Pointer Capture state.
1505 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001506 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001507 setPointerCaptureLocked(false);
1508 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001509 return;
1510 }
1511 InputTarget target;
1512 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001513 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001514 entry->dispatchInProgress = true;
1515 dispatchEventLocked(currentTime, entry, {target});
1516
1517 dropReason = DropReason::NOT_DROPPED;
1518}
1519
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001520void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1521 const std::shared_ptr<TouchModeEntry>& entry) {
1522 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001523 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001524 if (windowHandles.empty()) {
1525 return;
1526 }
1527 const std::vector<InputTarget> inputTargets =
1528 getInputTargetsFromWindowHandlesLocked(windowHandles);
1529 if (inputTargets.empty()) {
1530 return;
1531 }
1532 entry->dispatchInProgress = true;
1533 dispatchEventLocked(currentTime, entry, inputTargets);
1534}
1535
1536std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1537 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1538 std::vector<InputTarget> inputTargets;
1539 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001540 const sp<IBinder>& token = handle->getToken();
1541 if (token == nullptr) {
1542 continue;
1543 }
1544 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1545 if (channel == nullptr) {
1546 continue; // Window has gone away
1547 }
1548 InputTarget target;
1549 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001550 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001551 inputTargets.push_back(target);
1552 }
1553 return inputTargets;
1554}
1555
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001556bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001557 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001559 if (!entry->dispatchInProgress) {
1560 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1561 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1562 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1563 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001564 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 // We have seen two identical key downs in a row which indicates that the device
1566 // driver is automatically generating key repeats itself. We take note of the
1567 // repeat here, but we disable our own next key repeat timer since it is clear that
1568 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001569 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1570 // Make sure we don't get key down from a different device. If a different
1571 // device Id has same key pressed down, the new device Id will replace the
1572 // current one to hold the key repeat with repeat count reset.
1573 // In the future when got a KEY_UP on the device id, drop it and do not
1574 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1576 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001577 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 } else {
1579 // Not a repeat. Save key down state in case we do see a repeat later.
1580 resetKeyRepeatLocked();
1581 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1582 }
1583 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001584 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1585 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001586 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001587 if (DEBUG_INBOUND_EVENT_DETAILS) {
1588 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1589 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001590 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591 resetKeyRepeatLocked();
1592 }
1593
1594 if (entry->repeatCount == 1) {
1595 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1596 } else {
1597 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1598 }
1599
1600 entry->dispatchInProgress = true;
1601
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001602 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603 }
1604
1605 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001606 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607 if (currentTime < entry->interceptKeyWakeupTime) {
1608 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1609 *nextWakeupTime = entry->interceptKeyWakeupTime;
1610 }
1611 return false; // wait until next wakeup
1612 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001613 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614 entry->interceptKeyWakeupTime = 0;
1615 }
1616
1617 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001618 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001619 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001620 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001621 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001622
1623 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1624 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1625 };
1626 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001627 return false; // wait for the command to run
1628 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001629 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001631 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001632 if (*dropReason == DropReason::NOT_DROPPED) {
1633 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001634 }
1635 }
1636
1637 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001638 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001639 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001640 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1641 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001642 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001643 return true;
1644 }
1645
1646 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001647 InputEventInjectionResult injectionResult;
1648 sp<WindowInfoHandle> focusedWindow =
1649 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1650 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001651 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 return false;
1653 }
1654
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001655 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001656 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657 return true;
1658 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001659 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1660
1661 std::vector<InputTarget> inputTargets;
1662 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001663 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001664 BitSet32(0), getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001666 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001667 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668
1669 // Dispatch the key.
1670 dispatchEventLocked(currentTime, entry, inputTargets);
1671 return true;
1672}
1673
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001674void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001675 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1676 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1677 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1678 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1679 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1680 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1681 entry.metaState, entry.repeatCount, entry.downTime);
1682 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683}
1684
Prabir Pradhancef936d2021-07-21 16:17:52 +00001685void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1686 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001687 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001688 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1689 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1690 "source=0x%x, sensorType=%s",
1691 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001692 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001693 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001694 auto command = [this, entry]() REQUIRES(mLock) {
1695 scoped_unlock unlock(mLock);
1696
1697 if (entry->accuracyChanged) {
1698 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1699 }
1700 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1701 entry->hwTimestamp, entry->values);
1702 };
1703 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001704}
1705
1706bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001707 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1708 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001709 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001710 }
Chris Yef59a2f42020-10-16 12:55:26 -07001711 { // acquire lock
1712 std::scoped_lock _l(mLock);
1713
1714 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1715 std::shared_ptr<EventEntry> entry = *it;
1716 if (entry->type == EventEntry::Type::SENSOR) {
1717 it = mInboundQueue.erase(it);
1718 releaseInboundEventLocked(entry);
1719 }
1720 }
1721 }
1722 return true;
1723}
1724
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001725bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001726 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001727 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001729 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 entry->dispatchInProgress = true;
1731
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001732 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733 }
1734
1735 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001736 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001737 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001738 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1739 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 return true;
1741 }
1742
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001743 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744
1745 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001746 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747
1748 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001749 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 if (isPointerEvent) {
1751 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001752
1753 if (mDragState &&
1754 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1755 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1756 pilferPointersLocked(mDragState->dragWindow->getToken());
1757 }
1758
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001759 std::vector<TouchedWindow> touchedWindows =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001760 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001761 /*byref*/ injectionResult);
1762 for (const TouchedWindow& touchedWindow : touchedWindows) {
1763 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED,
1764 "Shouldn't be adding window if the injection didn't succeed.");
1765 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1766 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
1767 inputTargets);
1768 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769 } else {
1770 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001771 sp<WindowInfoHandle> focusedWindow =
1772 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1773 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1774 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1775 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001776 InputTarget::Flags::FOREGROUND |
1777 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001778 BitSet32(0), getDownTime(*entry), inputTargets);
1779 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001781 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001782 return false;
1783 }
1784
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001785 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001786 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001787 return true;
1788 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001789 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001790 CancelationOptions::Mode mode(
1791 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1792 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001793 CancelationOptions options(mode, "input event injection failed");
1794 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795 return true;
1796 }
1797
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001798 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001799 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800
1801 // Dispatch the motion.
1802 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001803 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001804 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805 synthesizeCancelationEventsForAllConnectionsLocked(options);
1806 }
1807 dispatchEventLocked(currentTime, entry, inputTargets);
1808 return true;
1809}
1810
chaviw98318de2021-05-19 16:45:23 -05001811void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001812 bool isExiting, const int32_t rawX,
1813 const int32_t rawY) {
1814 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001815 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001816 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1817 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001818
1819 enqueueInboundEventLocked(std::move(dragEntry));
1820}
1821
1822void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1823 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1824 if (channel == nullptr) {
1825 return; // Window has gone away
1826 }
1827 InputTarget target;
1828 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001829 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001830 entry->dispatchInProgress = true;
1831 dispatchEventLocked(currentTime, entry, {target});
1832}
1833
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001834void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001835 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001836 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001837 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001838 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001839 "metaState=0x%x, buttonState=0x%x,"
1840 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001841 prefix, entry.eventTime, entry.deviceId,
1842 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1843 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1844 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1845 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001847 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1848 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1849 "x=%f, y=%f, pressure=%f, size=%f, "
1850 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1851 "orientation=%f",
1852 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1853 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1854 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1855 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1856 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1857 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1858 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1859 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1860 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1861 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1862 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864}
1865
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001866void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1867 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001868 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001869 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001870 if (DEBUG_DISPATCH_CYCLE) {
1871 ALOGD("dispatchEventToCurrentInputTargets");
1872 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001874 updateInteractionTokensLocked(*eventEntry, inputTargets);
1875
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1877
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001878 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001880 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001881 sp<Connection> connection =
1882 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001883 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001884 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001886 if (DEBUG_FOCUS) {
1887 ALOGD("Dropping event delivery to target with channel '%s' because it "
1888 "is no longer registered with the input dispatcher.",
1889 inputTarget.inputChannel->getName().c_str());
1890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001891 }
1892 }
1893}
1894
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001895void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1896 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1897 // If the policy decides to close the app, we will get a channel removal event via
1898 // unregisterInputChannel, and will clean up the connection that way. We are already not
1899 // sending new pointers to the connection when it blocked, but focused events will continue to
1900 // pile up.
1901 ALOGW("Canceling events for %s because it is unresponsive",
1902 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001903 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001904 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001905 "application not responding");
1906 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907 }
1908}
1909
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001910void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001911 if (DEBUG_FOCUS) {
1912 ALOGD("Resetting ANR timeouts.");
1913 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914
1915 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001916 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001917 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918}
1919
Tiger Huang721e26f2018-07-24 22:26:19 +08001920/**
1921 * Get the display id that the given event should go to. If this event specifies a valid display id,
1922 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1923 * Focused display is the display that the user most recently interacted with.
1924 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001925int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001926 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001927 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001928 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001929 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1930 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001931 break;
1932 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001933 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001934 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1935 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001936 break;
1937 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001938 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001939 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001940 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001941 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001942 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001943 case EventEntry::Type::SENSOR:
1944 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001945 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001946 return ADISPLAY_ID_NONE;
1947 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001948 }
1949 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1950}
1951
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001952bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1953 const char* focusedWindowName) {
1954 if (mAnrTracker.empty()) {
1955 // already processed all events that we waited for
1956 mKeyIsWaitingForEventsTimeout = std::nullopt;
1957 return false;
1958 }
1959
1960 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1961 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001962 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001963 mKeyIsWaitingForEventsTimeout = currentTime +
1964 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1965 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001966 return true;
1967 }
1968
1969 // We still have pending events, and already started the timer
1970 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1971 return true; // Still waiting
1972 }
1973
1974 // Waited too long, and some connection still hasn't processed all motions
1975 // Just send the key to the focused window
1976 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1977 focusedWindowName);
1978 mKeyIsWaitingForEventsTimeout = std::nullopt;
1979 return false;
1980}
1981
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001982sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
1983 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
1984 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001985 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001986 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987
Tiger Huang721e26f2018-07-24 22:26:19 +08001988 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001989 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001990 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001991 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1992
Michael Wrightd02c5b62014-02-10 15:10:22 -08001993 // If there is no currently focused window and no focused application
1994 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001995 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1996 ALOGI("Dropping %s event because there is no focused window or focused application in "
1997 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001998 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001999 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000 }
2001
Vishnu Nair062a8672021-09-03 16:07:44 -07002002 // Drop key events if requested by input feature
2003 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002004 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002005 }
2006
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002007 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2008 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2009 // start interacting with another application via touch (app switch). This code can be removed
2010 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2011 // an app is expected to have a focused window.
2012 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2013 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2014 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002015 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2016 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2017 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002018 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002019 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002020 ALOGW("Waiting because no window has focus but %s may eventually add a "
2021 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002022 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002023 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002024 outInjectionResult = InputEventInjectionResult::PENDING;
2025 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002026 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2027 // Already raised ANR. Drop the event
2028 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002029 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002030 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002031 } else {
2032 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002033 outInjectionResult = InputEventInjectionResult::PENDING;
2034 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002035 }
2036 }
2037
2038 // we have a valid, non-null focused window
2039 resetNoFocusedWindowTimeoutLocked();
2040
Prabir Pradhan5735a322022-04-11 17:23:34 +00002041 // Verify targeted injection.
2042 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2043 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002044 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2045 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002046 }
2047
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002048 if (focusedWindowHandle->getInfo()->inputConfig.test(
2049 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002050 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002051 outInjectionResult = InputEventInjectionResult::PENDING;
2052 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002053 }
2054
2055 // If the event is a key event, then we must wait for all previous events to
2056 // complete before delivering it because previous events may have the
2057 // side-effect of transferring focus to a different window and we want to
2058 // ensure that the following keys are sent to the new window.
2059 //
2060 // Suppose the user touches a button in a window then immediately presses "A".
2061 // If the button causes a pop-up window to appear then we want to ensure that
2062 // the "A" key is delivered to the new pop-up window. This is because users
2063 // often anticipate pending UI changes when typing on a keyboard.
2064 // To obtain this behavior, we must serialize key events with respect to all
2065 // prior input events.
2066 if (entry.type == EventEntry::Type::KEY) {
2067 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2068 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002069 outInjectionResult = InputEventInjectionResult::PENDING;
2070 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002071 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 }
2073
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002074 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2075 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076}
2077
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002078/**
2079 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2080 * that are currently unresponsive.
2081 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002082std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2083 const std::vector<Monitor>& monitors) const {
2084 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002085 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002086 [this](const Monitor& monitor) REQUIRES(mLock) {
2087 sp<Connection> connection =
2088 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002089 if (connection == nullptr) {
2090 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002091 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002092 return false;
2093 }
2094 if (!connection->responsive) {
2095 ALOGW("Unresponsive monitor %s will not get the new gesture",
2096 connection->inputChannel->getName().c_str());
2097 return false;
2098 }
2099 return true;
2100 });
2101 return responsiveMonitors;
2102}
2103
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002104/**
2105 * In general, touch should be always split between windows. Some exceptions:
2106 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2107 * from the same device, *and* the window that's receiving the current pointer does not support
2108 * split touch.
2109 * 2. Don't split mouse events
2110 */
2111bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2112 const MotionEntry& entry) const {
2113 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2114 // We should never split mouse events
2115 return false;
2116 }
2117 for (const TouchedWindow& touchedWindow : touchState.windows) {
2118 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2119 // Spy windows should not affect whether or not touch is split.
2120 continue;
2121 }
2122 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2123 continue;
2124 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002125 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2126 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2127 // Wallpaper window should not affect whether or not touch is split
2128 continue;
2129 }
2130
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002131 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2132 // being sent there. For now, use deviceId from touch state.
2133 if (entry.deviceId == touchState.deviceId && !touchedWindow.pointerIds.isEmpty()) {
2134 return false;
2135 }
2136 }
2137 return true;
2138}
2139
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002140std::vector<TouchedWindow> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002141 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2142 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002143 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002144
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002145 std::vector<TouchedWindow> touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002146 // For security reasons, we defer updating the touch state until we are sure that
2147 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002148 const int32_t displayId = entry.displayId;
2149 const int32_t action = entry.action;
2150 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002151
2152 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002153 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002155 // Copy current touch state into tempTouchState.
2156 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2157 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002158 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002159 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002160 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2161 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002162 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002163 }
2164
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002165 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002166 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002167 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002168
2169 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2170 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2171 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2172 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2173 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002174 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002175
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176 if (newGesture) {
2177 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002178 if (switchedDevice && tempTouchState.isDown() && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002179 ALOGI("Dropping event because a pointer for a different device is already down "
2180 "in display %" PRId32,
2181 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002182 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002183 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakouf0ab2c82022-10-25 18:15:28 -07002184 return touchedWindows; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002185 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002186 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002187 tempTouchState.deviceId = entry.deviceId;
2188 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002189 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002190 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002191 ALOGI("Dropping move event because a pointer for a different device is already active "
2192 "in display %" PRId32,
2193 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002194 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002195 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakouf0ab2c82022-10-25 18:15:28 -07002196 return touchedWindows; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197 }
2198
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002199 if (isHoverAction) {
2200 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2201 // all of the existing hovering pointers and recompute.
2202 tempTouchState.clearHoveringPointers();
2203 }
2204
Michael Wrightd02c5b62014-02-10 15:10:22 -08002205 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2206 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002207 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002208 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002209 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002210 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002211 sp<WindowInfoHandle> newTouchedWindowHandle =
2212 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus,
2213 isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002214
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002216 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002217 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2218 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002220 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002221 }
2222
Prabir Pradhan5735a322022-04-11 17:23:34 +00002223 // Verify targeted injection.
2224 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2225 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002226 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002227 newTouchedWindowHandle = nullptr;
2228 goto Failed;
2229 }
2230
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002231 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002232 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002233 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2234 // New window supports splitting, but we should never split mouse events.
2235 isSplit = !isFromMouse;
2236 } else if (isSplit) {
2237 // New window does not support splitting but we have already split events.
2238 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002239 newTouchedWindowHandle = nullptr;
2240 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002241 } else {
2242 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002243 // be delivered to a new window which supports split touch. Pointers from a mouse device
2244 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002245 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002246 }
2247
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002248 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002249 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002250 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002251 // Process the foreground window first so that it is the first to receive the event.
2252 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002253 }
2254
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002255 if (newTouchedWindows.empty()) {
2256 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2257 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002258 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002259 goto Failed;
2260 }
2261
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002262 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002263 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002264 continue;
2265 }
2266
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002267 if (isHoverAction) {
2268 const int32_t pointerId = entry.pointerProperties[0].id;
2269 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2270 // Pointer left. Remove it
2271 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2272 } else {
2273 // The "windowHandle" is the target of this hovering pointer.
2274 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId,
2275 pointerId);
2276 }
2277 }
2278
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002279 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002280 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002281
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002282 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2283 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002284 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002285 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002286
2287 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002288 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002289 }
2290 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002291 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002292 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002293 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002294 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002295
2296 // Update the temporary touch state.
2297 BitSet32 pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002298 if (!isHoverAction) {
2299 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2300 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002301
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002302 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
2303 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002304
2305 // If this is the pointer going down and the touched window has a wallpaper
2306 // then also add the touched wallpaper windows so they are locked in for the duration
2307 // of the touch gesture.
2308 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2309 // engine only supports touch events. We would need to add a mechanism similar
2310 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2311 if (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2312 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2313 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2314 windowHandle->getInfo()->inputConfig.test(
2315 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2316 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2317 if (wallpaper != nullptr) {
2318 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2319 InputTarget::Flags::WINDOW_IS_OBSCURED |
2320 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2321 InputTarget::Flags::DISPATCH_AS_IS;
2322 if (isSplit) {
2323 wallpaperFlags |= InputTarget::Flags::SPLIT;
2324 }
2325 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2326 entry.eventTime);
2327 }
2328 }
2329 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002331
2332 // If any existing window is pilfering pointers from newly added window, remove it
2333 BitSet32 canceledPointers = BitSet32(0);
2334 for (const TouchedWindow& window : tempTouchState.windows) {
2335 if (window.isPilferingPointers) {
2336 canceledPointers |= window.pointerIds;
2337 }
2338 }
2339 tempTouchState.cancelPointersForNonPilferingWindows(canceledPointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340 } else {
2341 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2342
2343 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002344 if (!tempTouchState.isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002345 ALOGD_IF(DEBUG_FOCUS,
2346 "Dropping event because the pointer is not down or we previously "
2347 "dropped the pointer down event in display %" PRId32 ": %s",
2348 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002349 outInjectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002350 goto Failed;
2351 }
2352
arthurhung6d4bed92021-03-17 11:59:33 +08002353 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002354
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002356 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002357 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002358 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07002359 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002360 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002361 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002362 sp<WindowInfoHandle> newTouchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002363 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002364
Prabir Pradhan5735a322022-04-11 17:23:34 +00002365 // Verify targeted injection.
2366 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2367 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002368 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002369 newTouchedWindowHandle = nullptr;
2370 goto Failed;
2371 }
2372
Vishnu Nair062a8672021-09-03 16:07:44 -07002373 // Drop touch events if requested by input feature
2374 if (newTouchedWindowHandle != nullptr &&
2375 shouldDropInput(entry, newTouchedWindowHandle)) {
2376 newTouchedWindowHandle = nullptr;
2377 }
2378
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002379 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2380 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002381 if (DEBUG_FOCUS) {
2382 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2383 oldTouchedWindowHandle->getName().c_str(),
2384 newTouchedWindowHandle->getName().c_str(), displayId);
2385 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002386 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002387 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002388 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002389 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002390
2391 // Make a slippery entrance into the new window.
2392 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002393 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 }
2395
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002396 ftl::Flags<InputTarget::Flags> targetFlags =
2397 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002398 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002399 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002400 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002401 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002402 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 }
2404 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002405 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002406 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002407 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002408 }
2409
2410 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002411 pointerIds.markBit(entry.pointerProperties[0].id);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002412 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2413 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002414
2415 // Check if the wallpaper window should deliver the corresponding event.
2416 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
2417 tempTouchState, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002418 }
2419 }
Arthur Hung96483742022-11-15 03:30:48 +00002420
2421 // Update the pointerIds for non-splittable when it received pointer down.
2422 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2423 // If no split, we suppose all touched windows should receive pointer down.
2424 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2425 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2426 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2427 // Ignore drag window for it should just track one pointer.
2428 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2429 continue;
2430 }
2431 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2432 }
2433 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002434 }
2435
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002436 // Update dispatching for hover enter and exit.
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002437 {
2438 std::vector<TouchedWindow> hoveringWindows =
2439 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2440 touchedWindows.insert(touchedWindows.end(), hoveringWindows.begin(), hoveringWindows.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441 }
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002442 // Ensure that we have at least one foreground window or at least one window that cannot be a
2443 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2444 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2445 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002446 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2447 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002448 return !canReceiveForegroundTouches(
2449 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002450 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002451 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002452 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2453 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002454 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002455 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002456 }
2457
Prabir Pradhan5735a322022-04-11 17:23:34 +00002458 // Ensure that all touched windows are valid for injection.
2459 if (entry.injectionState != nullptr) {
2460 std::string errs;
2461 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002462 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002463 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2464 // dispatched to any uid, since the coords will be zeroed out later.
2465 continue;
2466 }
2467 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2468 if (err) errs += "\n - " + *err;
2469 }
2470 if (!errs.empty()) {
2471 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2472 "%d:%s",
2473 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002474 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002475 goto Failed;
2476 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002477 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002478
Michael Wrightd02c5b62014-02-10 15:10:22 -08002479 // Check whether windows listening for outside touches are owned by the same UID. If it is
2480 // set the policy flag that we will not reveal coordinate information to this window.
2481 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002482 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002483 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002484 if (foregroundWindowHandle) {
2485 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002486 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002487 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
chaviw98318de2021-05-19 16:45:23 -05002488 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2489 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2490 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002491 InputTarget::Flags::ZERO_COORDS,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002492 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002493 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494 }
2495 }
2496 }
2497 }
2498
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002499 // Success! Output targets for everything except hovers.
2500 if (!isHoverAction) {
2501 touchedWindows.insert(touchedWindows.end(), tempTouchState.windows.begin(),
2502 tempTouchState.windows.end());
2503 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002504
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002505 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002506 // Drop the outside or hover touch windows since we will not care about them
2507 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002508 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002509
2510Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002512 if (switchedDevice) {
2513 if (DEBUG_FOCUS) {
2514 ALOGD("Conflicting pointer actions: Switched to a different device.");
2515 }
2516 *outConflictingPointerActions = true;
2517 }
2518
2519 if (isHoverAction) {
2520 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002521 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002522 ALOGD_IF(DEBUG_FOCUS,
2523 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002524 *outConflictingPointerActions = true;
2525 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002526 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2527 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2528 tempTouchState.deviceId = entry.deviceId;
2529 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002530 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002531 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2532 // Pointer went up.
2533 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
2534 tempTouchState.clearWindowsWithoutPointers();
2535 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002536 // All pointers up or canceled.
2537 tempTouchState.reset();
2538 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2539 // First pointer went down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002540 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002541 ALOGD("Conflicting pointer actions: Down received while already down.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002542 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002543 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002544 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2545 // One pointer went up.
2546 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2547 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002548
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002549 for (size_t i = 0; i < tempTouchState.windows.size();) {
2550 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2551 touchedWindow.pointerIds.clearBit(pointerId);
2552 if (touchedWindow.pointerIds.isEmpty()) {
2553 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2554 continue;
2555 }
2556 i += 1;
2557 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002558 }
2559
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002560 // Save changes unless the action was scroll in which case the temporary touch
2561 // state was only valid for this one action.
2562 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002563 if (displayId >= 0) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002564 mTouchStatesByDisplay[displayId] = tempTouchState;
2565 } else {
2566 mTouchStatesByDisplay.erase(displayId);
2567 }
2568 }
2569
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002570 if (tempTouchState.windows.empty()) {
2571 mTouchStatesByDisplay.erase(displayId);
2572 }
2573
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002574 return touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002575}
2576
arthurhung6d4bed92021-03-17 11:59:33 +08002577void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002578 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2579 // have an explicit reason to support it.
2580 constexpr bool isStylus = false;
2581
chaviw98318de2021-05-19 16:45:23 -05002582 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002583 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002584 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002585 if (dropWindow) {
2586 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002587 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002588 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002589 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002590 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002591 }
2592 mDragState.reset();
2593}
2594
2595void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002596 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002597 return;
2598 }
2599
arthurhung6d4bed92021-03-17 11:59:33 +08002600 if (!mDragState->isStartDrag) {
2601 mDragState->isStartDrag = true;
2602 mDragState->isStylusButtonDownAtStart =
2603 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2604 }
2605
Arthur Hung54745652022-04-20 07:17:41 +00002606 // Find the pointer index by id.
2607 int32_t pointerIndex = 0;
2608 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2609 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2610 if (pointerProperties.id == mDragState->pointerId) {
2611 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002612 }
Arthur Hung54745652022-04-20 07:17:41 +00002613 }
arthurhung6d4bed92021-03-17 11:59:33 +08002614
Arthur Hung54745652022-04-20 07:17:41 +00002615 if (uint32_t(pointerIndex) == entry.pointerCount) {
2616 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002617 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002618 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002619 return;
2620 }
2621
2622 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2623 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2624 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2625
2626 switch (maskedAction) {
2627 case AMOTION_EVENT_ACTION_MOVE: {
2628 // Handle the special case : stylus button no longer pressed.
2629 bool isStylusButtonDown =
2630 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2631 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2632 finishDragAndDrop(entry.displayId, x, y);
2633 return;
2634 }
2635
2636 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2637 // until we have an explicit reason to support it.
2638 constexpr bool isStylus = false;
2639
2640 const sp<WindowInfoHandle> hoverWindowHandle =
2641 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2642 isStylus, false /*addOutsideTargets*/,
2643 true /*ignoreDragWindow*/);
2644 // enqueue drag exit if needed.
2645 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2646 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2647 if (mDragState->dragHoverWindowHandle != nullptr) {
2648 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2649 y);
2650 }
2651 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2652 }
2653 // enqueue drag location if needed.
2654 if (hoverWindowHandle != nullptr) {
2655 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2656 }
2657 break;
2658 }
2659
2660 case AMOTION_EVENT_ACTION_POINTER_UP:
2661 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2662 break;
2663 }
2664 // The drag pointer is up.
2665 [[fallthrough]];
2666 case AMOTION_EVENT_ACTION_UP:
2667 finishDragAndDrop(entry.displayId, x, y);
2668 break;
2669 case AMOTION_EVENT_ACTION_CANCEL: {
2670 ALOGD("Receiving cancel when drag and drop.");
2671 sendDropWindowCommandLocked(nullptr, 0, 0);
2672 mDragState.reset();
2673 break;
2674 }
arthurhungb89ccb02020-12-30 16:19:01 +08002675 }
2676}
2677
chaviw98318de2021-05-19 16:45:23 -05002678void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002679 ftl::Flags<InputTarget::Flags> targetFlags,
2680 BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002681 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002682 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002683 std::vector<InputTarget>::iterator it =
2684 std::find_if(inputTargets.begin(), inputTargets.end(),
2685 [&windowHandle](const InputTarget& inputTarget) {
2686 return inputTarget.inputChannel->getConnectionToken() ==
2687 windowHandle->getToken();
2688 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002689
chaviw98318de2021-05-19 16:45:23 -05002690 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002691
2692 if (it == inputTargets.end()) {
2693 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002694 std::shared_ptr<InputChannel> inputChannel =
2695 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002696 if (inputChannel == nullptr) {
2697 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2698 return;
2699 }
2700 inputTarget.inputChannel = inputChannel;
2701 inputTarget.flags = targetFlags;
2702 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002703 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002704 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2705 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002706 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002707 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002708 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002709 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002710 inputTargets.push_back(inputTarget);
2711 it = inputTargets.end() - 1;
2712 }
2713
2714 ALOG_ASSERT(it->flags == targetFlags);
2715 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2716
chaviw1ff3d1e2020-07-01 15:53:47 -07002717 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002718}
2719
Michael Wright3dd60e22019-03-27 22:06:44 +00002720void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002721 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002722 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2723 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002724
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002725 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2726 InputTarget target;
2727 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002728 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002729 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2730 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002731 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2732 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002733 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002734 target.setDefaultPointerTransform(target.displayTransform);
2735 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002736 }
2737}
2738
Robert Carrc9bf1d32020-04-13 17:21:08 -07002739/**
2740 * Indicate whether one window handle should be considered as obscuring
2741 * another window handle. We only check a few preconditions. Actually
2742 * checking the bounds is left to the caller.
2743 */
chaviw98318de2021-05-19 16:45:23 -05002744static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2745 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002746 // Compare by token so cloned layers aren't counted
2747 if (haveSameToken(windowHandle, otherHandle)) {
2748 return false;
2749 }
2750 auto info = windowHandle->getInfo();
2751 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002752 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002753 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002754 } else if (otherInfo->alpha == 0 &&
2755 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002756 // Those act as if they were invisible, so we don't need to flag them.
2757 // We do want to potentially flag touchable windows even if they have 0
2758 // opacity, since they can consume touches and alter the effects of the
2759 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002760 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002761 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2762 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002763 } else if (info->ownerUid == otherInfo->ownerUid) {
2764 // If ownerUid is the same we don't generate occlusion events as there
2765 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002766 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002767 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002768 return false;
2769 } else if (otherInfo->displayId != info->displayId) {
2770 return false;
2771 }
2772 return true;
2773}
2774
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002775/**
2776 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2777 * untrusted, one should check:
2778 *
2779 * 1. If result.hasBlockingOcclusion is true.
2780 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2781 * BLOCK_UNTRUSTED.
2782 *
2783 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2784 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2785 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2786 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2787 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2788 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2789 *
2790 * If neither of those is true, then it means the touch can be allowed.
2791 */
2792InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002793 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2794 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002795 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002796 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002797 TouchOcclusionInfo info;
2798 info.hasBlockingOcclusion = false;
2799 info.obscuringOpacity = 0;
2800 info.obscuringUid = -1;
2801 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002802 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002803 if (windowHandle == otherHandle) {
2804 break; // All future windows are below us. Exit early.
2805 }
chaviw98318de2021-05-19 16:45:23 -05002806 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002807 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2808 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002809 if (DEBUG_TOUCH_OCCLUSION) {
2810 info.debugInfo.push_back(
2811 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2812 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002813 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2814 // we perform the checks below to see if the touch can be propagated or not based on the
2815 // window's touch occlusion mode
2816 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2817 info.hasBlockingOcclusion = true;
2818 info.obscuringUid = otherInfo->ownerUid;
2819 info.obscuringPackage = otherInfo->packageName;
2820 break;
2821 }
2822 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2823 uint32_t uid = otherInfo->ownerUid;
2824 float opacity =
2825 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2826 // Given windows A and B:
2827 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2828 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2829 opacityByUid[uid] = opacity;
2830 if (opacity > info.obscuringOpacity) {
2831 info.obscuringOpacity = opacity;
2832 info.obscuringUid = uid;
2833 info.obscuringPackage = otherInfo->packageName;
2834 }
2835 }
2836 }
2837 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002838 if (DEBUG_TOUCH_OCCLUSION) {
2839 info.debugInfo.push_back(
2840 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2841 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002842 return info;
2843}
2844
chaviw98318de2021-05-19 16:45:23 -05002845std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002846 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002847 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2848 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2849 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2850 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002851 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2852 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2853 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2854 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2855 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002856 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002857 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002858}
2859
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002860bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2861 if (occlusionInfo.hasBlockingOcclusion) {
2862 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2863 occlusionInfo.obscuringUid);
2864 return false;
2865 }
2866 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2867 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2868 "%.2f, maximum allowed = %.2f)",
2869 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2870 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2871 return false;
2872 }
2873 return true;
2874}
2875
chaviw98318de2021-05-19 16:45:23 -05002876bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002877 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002878 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002879 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2880 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002881 if (windowHandle == otherHandle) {
2882 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883 }
chaviw98318de2021-05-19 16:45:23 -05002884 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002885 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002886 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002887 return true;
2888 }
2889 }
2890 return false;
2891}
2892
chaviw98318de2021-05-19 16:45:23 -05002893bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002894 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002895 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2896 const WindowInfo* windowInfo = windowHandle->getInfo();
2897 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002898 if (windowHandle == otherHandle) {
2899 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002900 }
chaviw98318de2021-05-19 16:45:23 -05002901 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002902 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002903 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002904 return true;
2905 }
2906 }
2907 return false;
2908}
2909
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002910std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002911 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002912 if (applicationHandle != nullptr) {
2913 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002914 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002915 } else {
2916 return applicationHandle->getName();
2917 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002918 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002919 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002921 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922 }
2923}
2924
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002925void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002926 if (!isUserActivityEvent(eventEntry)) {
2927 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002928 return;
2929 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002930 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002931 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002932 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002933 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002934 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002935 if (DEBUG_DISPATCH_CYCLE) {
2936 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2937 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938 return;
2939 }
2940 }
2941
2942 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002943 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002944 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002945 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2946 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002947 return;
2948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002949
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002950 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002951 eventType = USER_ACTIVITY_EVENT_TOUCH;
2952 }
2953 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002954 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002955 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002956 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2957 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002958 return;
2959 }
2960 eventType = USER_ACTIVITY_EVENT_BUTTON;
2961 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002962 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002963 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002964 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002965 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002966 break;
2967 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002968 }
2969
Prabir Pradhancef936d2021-07-21 16:17:52 +00002970 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2971 REQUIRES(mLock) {
2972 scoped_unlock unlock(mLock);
2973 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2974 };
2975 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002976}
2977
2978void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002979 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002980 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002981 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002982 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002983 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002984 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002985 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002986 ATRACE_NAME(message.c_str());
2987 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002988 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002989 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002990 "globalScaleFactor=%f, pointerIds=0x%x %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002991 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002992 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2993 inputTarget.getPointerInfoString().c_str());
2994 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002995
2996 // Skip this event if the connection status is not normal.
2997 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002998 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002999 if (DEBUG_DISPATCH_CYCLE) {
3000 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003001 connection->getInputChannelName().c_str(),
3002 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004 return;
3005 }
3006
3007 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003008 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003009 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003010 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003011 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003012
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003013 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003014 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003015 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
3016 "Splitting motion events requires a down time to be set for the "
3017 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003018 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003019 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3020 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003021 if (!splitMotionEntry) {
3022 return; // split event was dropped
3023 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003024 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3025 std::string reason = std::string("reason=pointer cancel on split window");
3026 android_log_event_list(LOGTAG_INPUT_CANCEL)
3027 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3028 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003029 if (DEBUG_FOCUS) {
3030 ALOGD("channel '%s' ~ Split motion event.",
3031 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003032 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003033 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003034 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3035 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003036 return;
3037 }
3038 }
3039
3040 // Not splitting. Enqueue dispatch entries for the event as is.
3041 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3042}
3043
3044void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003045 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003046 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003047 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003048 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003049 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003050 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003051 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003052 ATRACE_NAME(message.c_str());
3053 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003054 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3055 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003056
hongzuo liu95785e22022-09-06 02:51:35 +00003057 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003058
3059 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003060 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003061 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003062 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003063 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003064 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003065 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003066 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003067 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003068 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003069 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003070 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003071 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003072
3073 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003074 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003075 startDispatchCycleLocked(currentTime, connection);
3076 }
3077}
3078
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003079void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003080 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003081 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003082 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003083 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003084 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3085 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003086 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003087 ATRACE_NAME(message.c_str());
3088 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003089 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3090 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003091 return;
3092 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003093
3094 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3095 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003096
3097 // This is a new event.
3098 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003099 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003100 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003102 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3103 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003104 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003106 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003107 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003108 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003109 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003110 dispatchEntry->resolvedAction = keyEntry.action;
3111 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003112
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003113 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3114 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003115 if (DEBUG_DISPATCH_CYCLE) {
3116 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3117 "event",
3118 connection->getInputChannelName().c_str());
3119 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003120 return; // skip the inconsistent event
3121 }
3122 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003123 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003124
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003125 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003126 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003127 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3128 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3129 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3130 static_cast<int32_t>(IdGenerator::Source::OTHER);
3131 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003132 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003133 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003134 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003135 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003136 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003137 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003138 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003139 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003140 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003141 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3142 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003143 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003144 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003145 }
3146 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003147 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3148 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003149 if (DEBUG_DISPATCH_CYCLE) {
3150 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3151 "enter event",
3152 connection->getInputChannelName().c_str());
3153 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003154 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3155 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003156 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003159 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003160 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003161 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3162 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003163 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003164 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3165 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003167 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3168 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003169 if (DEBUG_DISPATCH_CYCLE) {
3170 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3171 "event",
3172 connection->getInputChannelName().c_str());
3173 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003174 return; // skip the inconsistent event
3175 }
3176
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003177 dispatchEntry->resolvedEventId =
3178 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3179 ? mIdGenerator.nextId()
3180 : motionEntry.id;
3181 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3182 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3183 ") to MotionEvent(id=0x%" PRIx32 ").",
3184 motionEntry.id, dispatchEntry->resolvedEventId);
3185 ATRACE_NAME(message.c_str());
3186 }
3187
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003188 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3189 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3190 // Skip reporting pointer down outside focus to the policy.
3191 break;
3192 }
3193
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003194 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003195 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003196
3197 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003199 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003200 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003201 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3202 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003203 break;
3204 }
Chris Yef59a2f42020-10-16 12:55:26 -07003205 case EventEntry::Type::SENSOR: {
3206 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3207 break;
3208 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003209 case EventEntry::Type::CONFIGURATION_CHANGED:
3210 case EventEntry::Type::DEVICE_RESET: {
3211 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003212 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003213 break;
3214 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215 }
3216
3217 // Remember that we are waiting for this dispatch to complete.
3218 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003219 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003220 }
3221
3222 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003223 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003224 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003225}
3226
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003227/**
3228 * This function is purely for debugging. It helps us understand where the user interaction
3229 * was taking place. For example, if user is touching launcher, we will see a log that user
3230 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3231 * We will see both launcher and wallpaper in that list.
3232 * Once the interaction with a particular set of connections starts, no new logs will be printed
3233 * until the set of interacted connections changes.
3234 *
3235 * The following items are skipped, to reduce the logspam:
3236 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3237 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3238 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3239 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3240 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003241 */
3242void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3243 const std::vector<InputTarget>& targets) {
3244 // Skip ACTION_UP events, and all events other than keys and motions
3245 if (entry.type == EventEntry::Type::KEY) {
3246 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3247 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3248 return;
3249 }
3250 } else if (entry.type == EventEntry::Type::MOTION) {
3251 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3252 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3253 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3254 return;
3255 }
3256 } else {
3257 return; // Not a key or a motion
3258 }
3259
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003260 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003261 std::vector<sp<Connection>> newConnections;
3262 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003263 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003264 continue; // Skip windows that receive ACTION_OUTSIDE
3265 }
3266
3267 sp<IBinder> token = target.inputChannel->getConnectionToken();
3268 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003269 if (connection == nullptr) {
3270 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003271 }
3272 newConnectionTokens.insert(std::move(token));
3273 newConnections.emplace_back(connection);
3274 }
3275 if (newConnectionTokens == mInteractionConnectionTokens) {
3276 return; // no change
3277 }
3278 mInteractionConnectionTokens = newConnectionTokens;
3279
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003280 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003281 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003282 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003283 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003284 std::string message = "Interaction with: " + targetList;
3285 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003286 message += "<none>";
3287 }
3288 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3289}
3290
chaviwfd6d3512019-03-25 13:23:49 -07003291void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003292 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003293 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003294 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3295 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003296 return;
3297 }
3298
Vishnu Nairc519ff72021-01-21 08:23:08 -08003299 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003300 if (focusedToken == token) {
3301 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003302 return;
3303 }
3304
Prabir Pradhancef936d2021-07-21 16:17:52 +00003305 auto command = [this, token]() REQUIRES(mLock) {
3306 scoped_unlock unlock(mLock);
3307 mPolicy->onPointerDownOutsideFocus(token);
3308 };
3309 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310}
3311
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003312status_t InputDispatcher::publishMotionEvent(Connection& connection,
3313 DispatchEntry& dispatchEntry) const {
3314 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3315 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3316
3317 PointerCoords scaledCoords[MAX_POINTERS];
3318 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3319
3320 // Set the X and Y offset and X and Y scale depending on the input source.
3321 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003322 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003323 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3324 if (globalScaleFactor != 1.0f) {
3325 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3326 scaledCoords[i] = motionEntry.pointerCoords[i];
3327 // Don't apply window scale here since we don't want scale to affect raw
3328 // coordinates. The scale will be sent back to the client and applied
3329 // later when requesting relative coordinates.
3330 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3331 1 /* windowYScale */);
3332 }
3333 usingCoords = scaledCoords;
3334 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003335 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003336 // We don't want the dispatch target to know the coordinates
3337 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3338 scaledCoords[i].clear();
3339 }
3340 usingCoords = scaledCoords;
3341 }
3342
3343 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3344
3345 // Publish the motion event.
3346 return connection.inputPublisher
3347 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3348 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3349 std::move(hmac), dispatchEntry.resolvedAction,
3350 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3351 motionEntry.edgeFlags, motionEntry.metaState,
3352 motionEntry.buttonState, motionEntry.classification,
3353 dispatchEntry.transform, motionEntry.xPrecision,
3354 motionEntry.yPrecision, motionEntry.xCursorPosition,
3355 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3356 motionEntry.downTime, motionEntry.eventTime,
3357 motionEntry.pointerCount, motionEntry.pointerProperties,
3358 usingCoords);
3359}
3360
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003362 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003363 if (ATRACE_ENABLED()) {
3364 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003365 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003366 ATRACE_NAME(message.c_str());
3367 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003368 if (DEBUG_DISPATCH_CYCLE) {
3369 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003372 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003373 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003375 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003376 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003377
3378 // Publish the event.
3379 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003380 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3381 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003382 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003383 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3384 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003386 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003387 status = connection->inputPublisher
3388 .publishKeyEvent(dispatchEntry->seq,
3389 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3390 keyEntry.source, keyEntry.displayId,
3391 std::move(hmac), dispatchEntry->resolvedAction,
3392 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3393 keyEntry.scanCode, keyEntry.metaState,
3394 keyEntry.repeatCount, keyEntry.downTime,
3395 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003396 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003397 }
3398
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003399 case EventEntry::Type::MOTION: {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003400 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003401 break;
3402 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003403
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003404 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003405 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003406 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003407 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003408 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003409 break;
3410 }
3411
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003412 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3413 const TouchModeEntry& touchModeEntry =
3414 static_cast<const TouchModeEntry&>(eventEntry);
3415 status = connection->inputPublisher
3416 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3417 touchModeEntry.inTouchMode);
3418
3419 break;
3420 }
3421
Prabir Pradhan99987712020-11-10 18:43:05 -08003422 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3423 const auto& captureEntry =
3424 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3425 status = connection->inputPublisher
3426 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003427 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003428 break;
3429 }
3430
arthurhungb89ccb02020-12-30 16:19:01 +08003431 case EventEntry::Type::DRAG: {
3432 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3433 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3434 dragEntry.id, dragEntry.x,
3435 dragEntry.y,
3436 dragEntry.isExiting);
3437 break;
3438 }
3439
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003440 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003441 case EventEntry::Type::DEVICE_RESET:
3442 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003443 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003444 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003445 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003447 }
3448
3449 // Check the result.
3450 if (status) {
3451 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003452 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003453 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003454 "This is unexpected because the wait queue is empty, so the pipe "
3455 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003456 "event to it, status=%s(%d)",
3457 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3458 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3460 } else {
3461 // Pipe is full and we are waiting for the app to finish process some events
3462 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003463 if (DEBUG_DISPATCH_CYCLE) {
3464 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3465 "waiting for the application to catch up",
3466 connection->getInputChannelName().c_str());
3467 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468 }
3469 } else {
3470 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003471 "status=%s(%d)",
3472 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3473 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3475 }
3476 return;
3477 }
3478
3479 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003480 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3481 connection->outboundQueue.end(),
3482 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003483 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003484 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003485 if (connection->responsive) {
3486 mAnrTracker.insert(dispatchEntry->timeoutTime,
3487 connection->inputChannel->getConnectionToken());
3488 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003489 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490 }
3491}
3492
chaviw09c8d2d2020-08-24 15:48:26 -07003493std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3494 size_t size;
3495 switch (event.type) {
3496 case VerifiedInputEvent::Type::KEY: {
3497 size = sizeof(VerifiedKeyEvent);
3498 break;
3499 }
3500 case VerifiedInputEvent::Type::MOTION: {
3501 size = sizeof(VerifiedMotionEvent);
3502 break;
3503 }
3504 }
3505 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3506 return mHmacKeyManager.sign(start, size);
3507}
3508
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003509const std::array<uint8_t, 32> InputDispatcher::getSignature(
3510 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003511 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3512 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003513 // Only sign events up and down events as the purely move events
3514 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003515 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003516 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003517
3518 VerifiedMotionEvent verifiedEvent =
3519 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3520 verifiedEvent.actionMasked = actionMasked;
3521 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3522 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003523}
3524
3525const std::array<uint8_t, 32> InputDispatcher::getSignature(
3526 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3527 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3528 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3529 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003530 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003531}
3532
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003534 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003535 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003536 if (DEBUG_DISPATCH_CYCLE) {
3537 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3538 connection->getInputChannelName().c_str(), seq, toString(handled));
3539 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003541 if (connection->status == Connection::Status::BROKEN ||
3542 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003543 return;
3544 }
3545
3546 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003547 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3548 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3549 };
3550 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551}
3552
3553void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003554 const sp<Connection>& connection,
3555 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003556 if (DEBUG_DISPATCH_CYCLE) {
3557 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3558 connection->getInputChannelName().c_str(), toString(notify));
3559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560
3561 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003562 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003563 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003564 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003565 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566
3567 // The connection appears to be unrecoverably broken.
3568 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003569 if (connection->status == Connection::Status::NORMAL) {
3570 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003571
3572 if (notify) {
3573 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003574 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3575 connection->getInputChannelName().c_str());
3576
3577 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003578 scoped_unlock unlock(mLock);
3579 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3580 };
3581 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003582 }
3583 }
3584}
3585
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003586void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3587 while (!queue.empty()) {
3588 DispatchEntry* dispatchEntry = queue.front();
3589 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003590 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591 }
3592}
3593
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003594void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003596 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 }
3598 delete dispatchEntry;
3599}
3600
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003601int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3602 std::scoped_lock _l(mLock);
3603 sp<Connection> connection = getConnectionLocked(connectionToken);
3604 if (connection == nullptr) {
3605 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3606 connectionToken.get(), events);
3607 return 0; // remove the callback
3608 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003610 bool notify;
3611 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3612 if (!(events & ALOOPER_EVENT_INPUT)) {
3613 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3614 "events=0x%x",
3615 connection->getInputChannelName().c_str(), events);
3616 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 }
3618
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003619 nsecs_t currentTime = now();
3620 bool gotOne = false;
3621 status_t status = OK;
3622 for (;;) {
3623 Result<InputPublisher::ConsumerResponse> result =
3624 connection->inputPublisher.receiveConsumerResponse();
3625 if (!result.ok()) {
3626 status = result.error().code();
3627 break;
3628 }
3629
3630 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3631 const InputPublisher::Finished& finish =
3632 std::get<InputPublisher::Finished>(*result);
3633 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3634 finish.consumeTime);
3635 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003636 if (shouldReportMetricsForConnection(*connection)) {
3637 const InputPublisher::Timeline& timeline =
3638 std::get<InputPublisher::Timeline>(*result);
3639 mLatencyTracker
3640 .trackGraphicsLatency(timeline.inputEventId,
3641 connection->inputChannel->getConnectionToken(),
3642 std::move(timeline.graphicsTimeline));
3643 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003644 }
3645 gotOne = true;
3646 }
3647 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003648 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003649 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003650 return 1;
3651 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003652 }
3653
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003654 notify = status != DEAD_OBJECT || !connection->monitor;
3655 if (notify) {
3656 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3657 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3658 status);
3659 }
3660 } else {
3661 // Monitor channels are never explicitly unregistered.
3662 // We do it automatically when the remote endpoint is closed so don't warn about them.
3663 const bool stillHaveWindowHandle =
3664 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3665 notify = !connection->monitor && stillHaveWindowHandle;
3666 if (notify) {
3667 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3668 connection->getInputChannelName().c_str(), events);
3669 }
3670 }
3671
3672 // Remove the channel.
3673 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3674 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003675}
3676
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003677void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003679 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003680 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681 }
3682}
3683
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003684void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003685 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003686 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003687 for (const Monitor& monitor : monitors) {
3688 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003689 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003690 }
3691}
3692
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003694 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003695 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003696 if (connection == nullptr) {
3697 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003699
3700 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701}
3702
3703void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3704 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003705 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706 return;
3707 }
3708
3709 nsecs_t currentTime = now();
3710
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003711 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003712 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003714 if (cancelationEvents.empty()) {
3715 return;
3716 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003717 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3718 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3719 "with reality: %s, mode=%d.",
3720 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3721 options.mode);
3722 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003723
Arthur Hungb3307ee2021-10-14 10:57:37 +00003724 std::string reason = std::string("reason=").append(options.reason);
3725 android_log_event_list(LOGTAG_INPUT_CANCEL)
3726 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3727
Svet Ganov5d3bc372020-01-26 23:11:07 -08003728 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003729 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003730 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3731 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003732 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003733 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003734 target.globalScaleFactor = windowInfo->globalScaleFactor;
3735 }
3736 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003737 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003738
hongzuo liu95785e22022-09-06 02:51:35 +00003739 const bool wasEmpty = connection->outboundQueue.empty();
3740
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003741 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003742 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003743 switch (cancelationEventEntry->type) {
3744 case EventEntry::Type::KEY: {
3745 logOutboundKeyDetails("cancel - ",
3746 static_cast<const KeyEntry&>(*cancelationEventEntry));
3747 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003748 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003749 case EventEntry::Type::MOTION: {
3750 logOutboundMotionDetails("cancel - ",
3751 static_cast<const MotionEntry&>(*cancelationEventEntry));
3752 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003754 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003755 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003756 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3757 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003758 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
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 }
3762 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003763 case EventEntry::Type::DEVICE_RESET:
3764 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003765 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003766 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003767 break;
3768 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769 }
3770
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003771 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003772 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003774
hongzuo liu95785e22022-09-06 02:51:35 +00003775 // If the outbound queue was previously empty, start the dispatch cycle going.
3776 if (wasEmpty && !connection->outboundQueue.empty()) {
3777 startDispatchCycleLocked(currentTime, connection);
3778 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779}
3780
Svet Ganov5d3bc372020-01-26 23:11:07 -08003781void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Arthur Hungc539dbb2022-12-08 07:45:36 +00003782 const nsecs_t downTime, const sp<Connection>& connection,
3783 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003784 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003785 return;
3786 }
3787
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003788 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003789 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003790
3791 if (downEvents.empty()) {
3792 return;
3793 }
3794
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003795 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003796 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3797 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003798 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003799
3800 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003801 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003802 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3803 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003804 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003805 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003806 target.globalScaleFactor = windowInfo->globalScaleFactor;
3807 }
3808 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00003809 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003810
hongzuo liu95785e22022-09-06 02:51:35 +00003811 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003812 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003813 switch (downEventEntry->type) {
3814 case EventEntry::Type::MOTION: {
3815 logOutboundMotionDetails("down - ",
3816 static_cast<const MotionEntry&>(*downEventEntry));
3817 break;
3818 }
3819
3820 case EventEntry::Type::KEY:
3821 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003822 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003823 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003824 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003825 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003826 case EventEntry::Type::SENSOR:
3827 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003828 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003829 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003830 break;
3831 }
3832 }
3833
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003834 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003835 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003836 }
3837
hongzuo liu95785e22022-09-06 02:51:35 +00003838 // If the outbound queue was previously empty, start the dispatch cycle going.
3839 if (wasEmpty && !connection->outboundQueue.empty()) {
3840 startDispatchCycleLocked(downTime, connection);
3841 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003842}
3843
Arthur Hungc539dbb2022-12-08 07:45:36 +00003844void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
3845 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
3846 if (windowHandle != nullptr) {
3847 sp<Connection> wallpaperConnection = getConnectionLocked(windowHandle->getToken());
3848 if (wallpaperConnection != nullptr) {
3849 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
3850 }
3851 }
3852}
3853
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003854std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003855 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003856 ALOG_ASSERT(pointerIds.value != 0);
3857
3858 uint32_t splitPointerIndexMap[MAX_POINTERS];
3859 PointerProperties splitPointerProperties[MAX_POINTERS];
3860 PointerCoords splitPointerCoords[MAX_POINTERS];
3861
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003862 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863 uint32_t splitPointerCount = 0;
3864
3865 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003866 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003868 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869 uint32_t pointerId = uint32_t(pointerProperties.id);
3870 if (pointerIds.hasBit(pointerId)) {
3871 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3872 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3873 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003874 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875 splitPointerCount += 1;
3876 }
3877 }
3878
3879 if (splitPointerCount != pointerIds.count()) {
3880 // This is bad. We are missing some of the pointers that we expected to deliver.
3881 // Most likely this indicates that we received an ACTION_MOVE events that has
3882 // different pointer ids than we expected based on the previous ACTION_DOWN
3883 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3884 // in this way.
3885 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003886 "we expected there to be %d pointers. This probably means we received "
3887 "a broken sequence of pointer ids from the input device.",
3888 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003889 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003890 }
3891
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003892 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003894 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3895 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3897 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003898 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899 uint32_t pointerId = uint32_t(pointerProperties.id);
3900 if (pointerIds.hasBit(pointerId)) {
3901 if (pointerIds.count() == 1) {
3902 // The first/last pointer went down/up.
3903 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003904 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003905 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3906 ? AMOTION_EVENT_ACTION_CANCEL
3907 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908 } else {
3909 // A secondary pointer went down/up.
3910 uint32_t splitPointerIndex = 0;
3911 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3912 splitPointerIndex += 1;
3913 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003914 action = maskedAction |
3915 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003916 }
3917 } else {
3918 // An unrelated pointer changed.
3919 action = AMOTION_EVENT_ACTION_MOVE;
3920 }
3921 }
3922
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003923 if (action == AMOTION_EVENT_ACTION_DOWN) {
3924 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3925 "Split motion event has mismatching downTime and eventTime for "
3926 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3927 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3928 }
3929
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003930 int32_t newId = mIdGenerator.nextId();
3931 if (ATRACE_ENABLED()) {
3932 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3933 ") to MotionEvent(id=0x%" PRIx32 ").",
3934 originalMotionEntry.id, newId);
3935 ATRACE_NAME(message.c_str());
3936 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003937 std::unique_ptr<MotionEntry> splitMotionEntry =
3938 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3939 originalMotionEntry.deviceId, originalMotionEntry.source,
3940 originalMotionEntry.displayId,
3941 originalMotionEntry.policyFlags, action,
3942 originalMotionEntry.actionButton,
3943 originalMotionEntry.flags, originalMotionEntry.metaState,
3944 originalMotionEntry.buttonState,
3945 originalMotionEntry.classification,
3946 originalMotionEntry.edgeFlags,
3947 originalMotionEntry.xPrecision,
3948 originalMotionEntry.yPrecision,
3949 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003950 originalMotionEntry.yCursorPosition, splitDownTime,
3951 splitPointerCount, splitPointerProperties,
3952 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003954 if (originalMotionEntry.injectionState) {
3955 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956 splitMotionEntry->injectionState->refCount += 1;
3957 }
3958
3959 return splitMotionEntry;
3960}
3961
3962void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003963 if (DEBUG_INBOUND_EVENT_DETAILS) {
3964 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3965 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966
Antonio Kantekf16f2832021-09-28 04:39:20 +00003967 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003969 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003971 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3972 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3973 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 } // release lock
3975
3976 if (needWake) {
3977 mLooper->wake();
3978 }
3979}
3980
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003981/**
3982 * If one of the meta shortcuts is detected, process them here:
3983 * Meta + Backspace -> generate BACK
3984 * Meta + Enter -> generate HOME
3985 * This will potentially overwrite keyCode and metaState.
3986 */
3987void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003988 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003989 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3990 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3991 if (keyCode == AKEYCODE_DEL) {
3992 newKeyCode = AKEYCODE_BACK;
3993 } else if (keyCode == AKEYCODE_ENTER) {
3994 newKeyCode = AKEYCODE_HOME;
3995 }
3996 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003997 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003998 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003999 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004000 keyCode = newKeyCode;
4001 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4002 }
4003 } else if (action == AKEY_EVENT_ACTION_UP) {
4004 // In order to maintain a consistent stream of up and down events, check to see if the key
4005 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4006 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004007 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004008 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004009 auto replacementIt = mReplacedKeys.find(replacement);
4010 if (replacementIt != mReplacedKeys.end()) {
4011 keyCode = replacementIt->second;
4012 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004013 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4014 }
4015 }
4016}
4017
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004019 if (DEBUG_INBOUND_EVENT_DETAILS) {
4020 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
4021 "policyFlags=0x%x, action=0x%x, "
4022 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
4023 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
4024 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
4025 args->downTime);
4026 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004027 if (!validateKeyEvent(args->action)) {
4028 return;
4029 }
4030
4031 uint32_t policyFlags = args->policyFlags;
4032 int32_t flags = args->flags;
4033 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004034 // InputDispatcher tracks and generates key repeats on behalf of
4035 // whatever notifies it, so repeatCount should always be set to 0
4036 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4038 policyFlags |= POLICY_FLAG_VIRTUAL;
4039 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4040 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004041 if (policyFlags & POLICY_FLAG_FUNCTION) {
4042 metaState |= AMETA_FUNCTION_ON;
4043 }
4044
4045 policyFlags |= POLICY_FLAG_TRUSTED;
4046
Michael Wright78f24442014-08-06 15:55:28 -07004047 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004048 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004049
Michael Wrightd02c5b62014-02-10 15:10:22 -08004050 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004051 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08004052 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
4053 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004054
Michael Wright2b3c3302018-03-02 17:19:13 +00004055 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004057 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4058 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004059 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004060 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004061
Antonio Kantekf16f2832021-09-28 04:39:20 +00004062 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063 { // acquire lock
4064 mLock.lock();
4065
4066 if (shouldSendKeyToInputFilterLocked(args)) {
4067 mLock.unlock();
4068
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004069 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4071 return; // event was consumed by the filter
4072 }
4073
4074 mLock.lock();
4075 }
4076
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004077 std::unique_ptr<KeyEntry> newEntry =
4078 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4079 args->displayId, policyFlags, args->action, flags,
4080 keyCode, args->scanCode, metaState, repeatCount,
4081 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004082
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004083 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004084 mLock.unlock();
4085 } // release lock
4086
4087 if (needWake) {
4088 mLooper->wake();
4089 }
4090}
4091
4092bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4093 return mInputFilterEnabled;
4094}
4095
4096void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004097 if (DEBUG_INBOUND_EVENT_DETAILS) {
4098 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4099 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004100 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004101 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4102 "yCursorPosition=%f, downTime=%" PRId64,
4103 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004104 args->policyFlags, MotionEvent::actionToString(args->action).c_str(),
4105 args->actionButton, args->flags, args->metaState, args->buttonState, args->edgeFlags,
4106 args->xPrecision, args->yPrecision, args->xCursorPosition, args->yCursorPosition,
4107 args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004108 for (uint32_t i = 0; i < args->pointerCount; i++) {
4109 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4110 "x=%f, y=%f, pressure=%f, size=%f, "
4111 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4112 "orientation=%f",
4113 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4114 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4115 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4116 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4117 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4118 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4119 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4120 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4121 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4122 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4123 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -08004125 LOG_ALWAYS_FATAL_IF(!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4126 args->pointerProperties),
4127 "Invalid event: %s", args->dump().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004128
4129 uint32_t policyFlags = args->policyFlags;
4130 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004131
4132 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004133 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004134 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4135 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004136 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004137 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138
Antonio Kantekf16f2832021-09-28 04:39:20 +00004139 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 { // acquire lock
4141 mLock.lock();
4142
4143 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004144 ui::Transform displayTransform;
4145 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4146 displayTransform = it->second.transform;
4147 }
4148
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149 mLock.unlock();
4150
4151 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004152 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4153 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004154 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004155 displayTransform, args->xPrecision, args->yPrecision,
4156 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004157 args->downTime, args->eventTime, args->pointerCount,
4158 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159
4160 policyFlags |= POLICY_FLAG_FILTERED;
4161 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4162 return; // event was consumed by the filter
4163 }
4164
4165 mLock.lock();
4166 }
4167
4168 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004169 std::unique_ptr<MotionEntry> newEntry =
4170 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4171 args->source, args->displayId, policyFlags,
4172 args->action, args->actionButton, args->flags,
4173 args->metaState, args->buttonState,
4174 args->classification, args->edgeFlags,
4175 args->xPrecision, args->yPrecision,
4176 args->xCursorPosition, args->yCursorPosition,
4177 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004178 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004180 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4181 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4182 !mInputFilterEnabled) {
4183 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4184 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4185 }
4186
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004187 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188 mLock.unlock();
4189 } // release lock
4190
4191 if (needWake) {
4192 mLooper->wake();
4193 }
4194}
4195
Chris Yef59a2f42020-10-16 12:55:26 -07004196void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004197 if (DEBUG_INBOUND_EVENT_DETAILS) {
4198 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4199 " sensorType=%s",
4200 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004201 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004202 }
Chris Yef59a2f42020-10-16 12:55:26 -07004203
Antonio Kantekf16f2832021-09-28 04:39:20 +00004204 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004205 { // acquire lock
4206 mLock.lock();
4207
4208 // Just enqueue a new sensor event.
4209 std::unique_ptr<SensorEntry> newEntry =
4210 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4211 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4212 args->sensorType, args->accuracy,
4213 args->accuracyChanged, args->values);
4214
4215 needWake = enqueueInboundEventLocked(std::move(newEntry));
4216 mLock.unlock();
4217 } // release lock
4218
4219 if (needWake) {
4220 mLooper->wake();
4221 }
4222}
4223
Chris Yefb552902021-02-03 17:18:37 -08004224void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004225 if (DEBUG_INBOUND_EVENT_DETAILS) {
4226 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4227 args->deviceId, args->isOn);
4228 }
Chris Yefb552902021-02-03 17:18:37 -08004229 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4230}
4231
Michael Wrightd02c5b62014-02-10 15:10:22 -08004232bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004233 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234}
4235
4236void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004237 if (DEBUG_INBOUND_EVENT_DETAILS) {
4238 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4239 "switchMask=0x%08x",
4240 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4241 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242
4243 uint32_t policyFlags = args->policyFlags;
4244 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004245 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004246}
4247
4248void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004249 if (DEBUG_INBOUND_EVENT_DETAILS) {
4250 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4251 args->deviceId);
4252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253
Antonio Kantekf16f2832021-09-28 04:39:20 +00004254 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004256 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004258 std::unique_ptr<DeviceResetEntry> newEntry =
4259 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4260 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 } // release lock
4262
4263 if (needWake) {
4264 mLooper->wake();
4265 }
4266}
4267
Prabir Pradhan7e186182020-11-10 13:56:45 -08004268void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004269 if (DEBUG_INBOUND_EVENT_DETAILS) {
4270 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004271 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004272 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004273
Antonio Kantekf16f2832021-09-28 04:39:20 +00004274 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004275 { // acquire lock
4276 std::scoped_lock _l(mLock);
4277 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004278 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004279 needWake = enqueueInboundEventLocked(std::move(entry));
4280 } // release lock
4281
4282 if (needWake) {
4283 mLooper->wake();
4284 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004285}
4286
Prabir Pradhan5735a322022-04-11 17:23:34 +00004287InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4288 std::optional<int32_t> targetUid,
4289 InputEventInjectionSync syncMode,
4290 std::chrono::milliseconds timeout,
4291 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004292 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004293 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4294 "policyFlags=0x%08x",
4295 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4296 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004297 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004298 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299
Prabir Pradhan5735a322022-04-11 17:23:34 +00004300 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004302 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004303 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4304 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4305 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4306 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4307 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004308 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004309 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004310 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004311 }
4312
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004313 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004315 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004316 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4317 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004318 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004319 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004322 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004323 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4324 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4325 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004326 int32_t keyCode = incomingKey.getKeyCode();
4327 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004328 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004329 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004330 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004331 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004332 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4333 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4334 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004336 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4337 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004338 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004339
4340 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4341 android::base::Timer t;
4342 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4343 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4344 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4345 std::to_string(t.duration().count()).c_str());
4346 }
4347 }
4348
4349 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004350 std::unique_ptr<KeyEntry> injectedEntry =
4351 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004352 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004353 incomingKey.getDisplayId(), policyFlags, action,
4354 flags, keyCode, incomingKey.getScanCode(), metaState,
4355 incomingKey.getRepeatCount(),
4356 incomingKey.getDownTime());
4357 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004358 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359 }
4360
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004361 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004362 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004363 const int32_t action = motionEvent.getAction();
4364 const bool isPointerEvent =
4365 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4366 // If a pointer event has no displayId specified, inject it to the default display.
4367 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4368 ? ADISPLAY_ID_DEFAULT
4369 : event->getDisplayId();
4370 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004371 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004372 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004373 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004374 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004375 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004376 }
4377
4378 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004379 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004380 android::base::Timer t;
4381 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4382 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4383 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4384 std::to_string(t.duration().count()).c_str());
4385 }
4386 }
4387
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004388 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4389 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4390 }
4391
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004392 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004393 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4394 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004395 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004396 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4397 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004398 displayId, policyFlags, action, actionButton,
4399 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004400 motionEvent.getButtonState(),
4401 motionEvent.getClassification(),
4402 motionEvent.getEdgeFlags(),
4403 motionEvent.getXPrecision(),
4404 motionEvent.getYPrecision(),
4405 motionEvent.getRawXCursorPosition(),
4406 motionEvent.getRawYCursorPosition(),
4407 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004408 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004409 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004410 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004411 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004412 sampleEventTimes += 1;
4413 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004414 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004415 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4416 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004417 displayId, policyFlags, action, actionButton,
4418 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004419 motionEvent.getButtonState(),
4420 motionEvent.getClassification(),
4421 motionEvent.getEdgeFlags(),
4422 motionEvent.getXPrecision(),
4423 motionEvent.getYPrecision(),
4424 motionEvent.getRawXCursorPosition(),
4425 motionEvent.getRawYCursorPosition(),
4426 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004427 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004428 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004429 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4430 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004431 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004432 }
4433 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004435
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004436 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004437 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004438 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439 }
4440
Prabir Pradhan5735a322022-04-11 17:23:34 +00004441 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004442 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004443 injectionState->injectionIsAsync = true;
4444 }
4445
4446 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004447 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004448
4449 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004450 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004451 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004452 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004453 }
4454
4455 mLock.unlock();
4456
4457 if (needWake) {
4458 mLooper->wake();
4459 }
4460
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004461 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004462 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004463 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004464
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004465 if (syncMode == InputEventInjectionSync::NONE) {
4466 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004467 } else {
4468 for (;;) {
4469 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004470 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471 break;
4472 }
4473
4474 nsecs_t remainingTimeout = endTime - now();
4475 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004476 if (DEBUG_INJECTION) {
4477 ALOGD("injectInputEvent - Timed out waiting for injection result "
4478 "to become available.");
4479 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004480 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004481 break;
4482 }
4483
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004484 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004485 }
4486
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004487 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4488 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004489 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004490 if (DEBUG_INJECTION) {
4491 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4492 injectionState->pendingForegroundDispatches);
4493 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004494 nsecs_t remainingTimeout = endTime - now();
4495 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004496 if (DEBUG_INJECTION) {
4497 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4498 "dispatches to finish.");
4499 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004500 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501 break;
4502 }
4503
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004504 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505 }
4506 }
4507 }
4508
4509 injectionState->release();
4510 } // release lock
4511
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004512 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004513 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004514 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004515
4516 return injectionResult;
4517}
4518
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004519std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004520 std::array<uint8_t, 32> calculatedHmac;
4521 std::unique_ptr<VerifiedInputEvent> result;
4522 switch (event.getType()) {
4523 case AINPUT_EVENT_TYPE_KEY: {
4524 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4525 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4526 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004527 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004528 break;
4529 }
4530 case AINPUT_EVENT_TYPE_MOTION: {
4531 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4532 VerifiedMotionEvent verifiedMotionEvent =
4533 verifiedMotionEventFromMotionEvent(motionEvent);
4534 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004535 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004536 break;
4537 }
4538 default: {
4539 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4540 return nullptr;
4541 }
4542 }
4543 if (calculatedHmac == INVALID_HMAC) {
4544 return nullptr;
4545 }
4546 if (calculatedHmac != event.getHmac()) {
4547 return nullptr;
4548 }
4549 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004550}
4551
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004552void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004553 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004554 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004555 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004556 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004557 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004558 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004559
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004560 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004561 // Log the outcome since the injector did not wait for the injection result.
4562 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004563 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004564 ALOGV("Asynchronous input event injection succeeded.");
4565 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004566 case InputEventInjectionResult::TARGET_MISMATCH:
4567 ALOGV("Asynchronous input event injection target mismatch.");
4568 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004569 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004570 ALOGW("Asynchronous input event injection failed.");
4571 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004572 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004573 ALOGW("Asynchronous input event injection timed out.");
4574 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004575 case InputEventInjectionResult::PENDING:
4576 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4577 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004578 }
4579 }
4580
4581 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004582 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004583 }
4584}
4585
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004586void InputDispatcher::transformMotionEntryForInjectionLocked(
4587 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004588 // Input injection works in the logical display coordinate space, but the input pipeline works
4589 // display space, so we need to transform the injected events accordingly.
4590 const auto it = mDisplayInfos.find(entry.displayId);
4591 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004592 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004593
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004594 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4595 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4596 const vec2 cursor =
4597 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4598 {entry.xCursorPosition, entry.yCursorPosition});
4599 entry.xCursorPosition = cursor.x;
4600 entry.yCursorPosition = cursor.y;
4601 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004602 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004603 entry.pointerCoords[i] =
4604 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4605 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004606 }
4607}
4608
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004609void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4610 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611 if (injectionState) {
4612 injectionState->pendingForegroundDispatches += 1;
4613 }
4614}
4615
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004616void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4617 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004618 if (injectionState) {
4619 injectionState->pendingForegroundDispatches -= 1;
4620
4621 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004622 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004623 }
4624 }
4625}
4626
chaviw98318de2021-05-19 16:45:23 -05004627const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004628 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004629 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004630 auto it = mWindowHandlesByDisplay.find(displayId);
4631 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004632}
4633
chaviw98318de2021-05-19 16:45:23 -05004634sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004635 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004636 if (windowHandleToken == nullptr) {
4637 return nullptr;
4638 }
4639
Arthur Hungb92218b2018-08-14 12:00:21 +08004640 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004641 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4642 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004643 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004644 return windowHandle;
4645 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004646 }
4647 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004648 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004649}
4650
chaviw98318de2021-05-19 16:45:23 -05004651sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4652 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004653 if (windowHandleToken == nullptr) {
4654 return nullptr;
4655 }
4656
chaviw98318de2021-05-19 16:45:23 -05004657 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004658 if (windowHandle->getToken() == windowHandleToken) {
4659 return windowHandle;
4660 }
4661 }
4662 return nullptr;
4663}
4664
chaviw98318de2021-05-19 16:45:23 -05004665sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4666 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004667 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004668 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4669 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004670 if (handle->getId() == windowHandle->getId() &&
4671 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004672 if (windowHandle->getInfo()->displayId != it.first) {
4673 ALOGE("Found window %s in display %" PRId32
4674 ", but it should belong to display %" PRId32,
4675 windowHandle->getName().c_str(), it.first,
4676 windowHandle->getInfo()->displayId);
4677 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004678 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004679 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004680 }
4681 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004682 return nullptr;
4683}
4684
chaviw98318de2021-05-19 16:45:23 -05004685sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004686 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4687 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004688}
4689
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004690bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4691 const MotionEntry& motionEntry) const {
4692 const WindowInfo& info = *window->getInfo();
4693
4694 // Skip spy window targets that are not valid for targeted injection.
4695 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004696 return false;
4697 }
4698
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004699 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4700 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4701 return false;
4702 }
4703
4704 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4705 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4706 window->getName().c_str());
4707 return false;
4708 }
4709
4710 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004711 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004712 ALOGW("Not sending touch to %s because there's no corresponding connection",
4713 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004714 return false;
4715 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004716
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004717 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004718 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004719 return false;
4720 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004721
4722 // Drop events that can't be trusted due to occlusion
4723 const auto [x, y] = resolveTouchedPosition(motionEntry);
4724 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4725 if (!isTouchTrustedLocked(occlusionInfo)) {
4726 if (DEBUG_TOUCH_OCCLUSION) {
4727 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4728 for (const auto& log : occlusionInfo.debugInfo) {
4729 ALOGD("%s", log.c_str());
4730 }
4731 }
4732 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4733 occlusionInfo.obscuringUid);
4734 return false;
4735 }
4736
4737 // Drop touch events if requested by input feature
4738 if (shouldDropInput(motionEntry, window)) {
4739 return false;
4740 }
4741
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004742 return true;
4743}
4744
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004745std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4746 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004747 auto connectionIt = mConnectionsByToken.find(token);
4748 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004749 return nullptr;
4750 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004751 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004752}
4753
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004754void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004755 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4756 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004757 // Remove all handles on a display if there are no windows left.
4758 mWindowHandlesByDisplay.erase(displayId);
4759 return;
4760 }
4761
4762 // Since we compare the pointer of input window handles across window updates, we need
4763 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004764 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4765 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4766 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004767 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004768 }
4769
chaviw98318de2021-05-19 16:45:23 -05004770 std::vector<sp<WindowInfoHandle>> newHandles;
4771 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004772 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004773 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004774 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004775 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004776 const bool canReceiveInput =
4777 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4778 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004779 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004780 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004781 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004782 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004783 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004784 }
4785
4786 if (info->displayId != displayId) {
4787 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4788 handle->getName().c_str(), displayId, info->displayId);
4789 continue;
4790 }
4791
Robert Carredd13602020-04-13 17:24:34 -07004792 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4793 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004794 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004795 oldHandle->updateFrom(handle);
4796 newHandles.push_back(oldHandle);
4797 } else {
4798 newHandles.push_back(handle);
4799 }
4800 }
4801
4802 // Insert or replace
4803 mWindowHandlesByDisplay[displayId] = newHandles;
4804}
4805
Arthur Hung72d8dc32020-03-28 00:48:39 +00004806void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004807 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004808 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004809 { // acquire lock
4810 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004811 for (const auto& [displayId, handles] : handlesPerDisplay) {
4812 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004813 }
4814 }
4815 // Wake up poll loop since it may need to make new input dispatching choices.
4816 mLooper->wake();
4817}
4818
Arthur Hungb92218b2018-08-14 12:00:21 +08004819/**
4820 * Called from InputManagerService, update window handle list by displayId that can receive input.
4821 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4822 * If set an empty list, remove all handles from the specific display.
4823 * For focused handle, check if need to change and send a cancel event to previous one.
4824 * For removed handle, check if need to send a cancel event if already in touch.
4825 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004826void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004827 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004828 if (DEBUG_FOCUS) {
4829 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004830 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004831 windowList += iwh->getName() + " ";
4832 }
4833 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4834 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004835
Prabir Pradhand65552b2021-10-07 11:23:50 -07004836 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004837 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004838 const WindowInfo& info = *window->getInfo();
4839
4840 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004841 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004842 if (noInputWindow && window->getToken() != nullptr) {
4843 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4844 window->getName().c_str());
4845 window->releaseChannel();
4846 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004847
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004848 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004849 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4850 !info.inputConfig.test(
4851 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004852 "%s has feature SPY, but is not a trusted overlay.",
4853 window->getName().c_str());
4854
Prabir Pradhand65552b2021-10-07 11:23:50 -07004855 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004856 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4857 !info.inputConfig.test(
4858 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004859 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4860 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004861 }
4862
Arthur Hung72d8dc32020-03-28 00:48:39 +00004863 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004864 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004866 // Save the old windows' orientation by ID before it gets updated.
4867 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004868 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004869 oldWindowOrientations.emplace(handle->getId(),
4870 handle->getInfo()->transform.getOrientation());
4871 }
4872
chaviw98318de2021-05-19 16:45:23 -05004873 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004874
chaviw98318de2021-05-19 16:45:23 -05004875 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004876
Vishnu Nairc519ff72021-01-21 08:23:08 -08004877 std::optional<FocusResolver::FocusChanges> changes =
4878 mFocusResolver.setInputWindows(displayId, windowHandles);
4879 if (changes) {
4880 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004883 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4884 mTouchStatesByDisplay.find(displayId);
4885 if (stateIt != mTouchStatesByDisplay.end()) {
4886 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004887 for (size_t i = 0; i < state.windows.size();) {
4888 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004889 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004890 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004891 ALOGD("Touched window was removed: %s in display %" PRId32,
4892 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004893 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004894 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004895 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4896 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004897 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00004898 "touched window was removed");
4899 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004900 // Since we are about to drop the touch, cancel the events for the wallpaper as
4901 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004902 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004903 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4904 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004905 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004906 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004907 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004909 state.windows.erase(state.windows.begin() + i);
4910 } else {
4911 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912 }
4913 }
arthurhungb89ccb02020-12-30 16:19:01 +08004914
arthurhung6d4bed92021-03-17 11:59:33 +08004915 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004916 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004917 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004918 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004919 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004920 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4921 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004922 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004923 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004924 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004925
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004926 // Determine if the orientation of any of the input windows have changed, and cancel all
4927 // pointer events if necessary.
4928 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4929 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4930 if (newWindowHandle != nullptr &&
4931 newWindowHandle->getInfo()->transform.getOrientation() !=
4932 oldWindowOrientations[oldWindowHandle->getId()]) {
4933 std::shared_ptr<InputChannel> inputChannel =
4934 getInputChannelLocked(newWindowHandle->getToken());
4935 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004936 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004937 "touched window's orientation changed");
4938 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004939 }
4940 }
4941 }
4942
Arthur Hung72d8dc32020-03-28 00:48:39 +00004943 // Release information for windows that are no longer present.
4944 // This ensures that unused input channels are released promptly.
4945 // Otherwise, they might stick around until the window handle is destroyed
4946 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004947 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004948 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004949 if (DEBUG_FOCUS) {
4950 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004951 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004952 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004953 }
chaviw291d88a2019-02-14 10:33:58 -08004954 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955}
4956
4957void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004958 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004959 if (DEBUG_FOCUS) {
4960 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4961 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4962 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004963 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004964 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004965 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004966 } // release lock
4967
4968 // Wake up poll loop since it may need to make new input dispatching choices.
4969 mLooper->wake();
4970}
4971
Vishnu Nair599f1412021-06-21 10:39:58 -07004972void InputDispatcher::setFocusedApplicationLocked(
4973 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4974 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4975 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4976
4977 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4978 return; // This application is already focused. No need to wake up or change anything.
4979 }
4980
4981 // Set the new application handle.
4982 if (inputApplicationHandle != nullptr) {
4983 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4984 } else {
4985 mFocusedApplicationHandlesByDisplay.erase(displayId);
4986 }
4987
4988 // No matter what the old focused application was, stop waiting on it because it is
4989 // no longer focused.
4990 resetNoFocusedWindowTimeoutLocked();
4991}
4992
Tiger Huang721e26f2018-07-24 22:26:19 +08004993/**
4994 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4995 * the display not specified.
4996 *
4997 * We track any unreleased events for each window. If a window loses the ability to receive the
4998 * released event, we will send a cancel event to it. So when the focused display is changed, we
4999 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5000 * display. The display-specified events won't be affected.
5001 */
5002void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005003 if (DEBUG_FOCUS) {
5004 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5005 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005006 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005007 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005008
5009 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005010 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005011 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005012 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005013 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005014 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005015 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005016 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005017 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005018 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005019 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005020 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5021 }
5022 }
5023 mFocusedDisplayId = displayId;
5024
Chris Ye3c2d6f52020-08-09 10:39:48 -07005025 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005026 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005027 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005028
Vishnu Nairad321cd2020-08-20 16:40:21 -07005029 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005030 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005031 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005032 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005033 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005034 }
5035 }
5036 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005037 } // release lock
5038
5039 // Wake up poll loop since it may need to make new input dispatching choices.
5040 mLooper->wake();
5041}
5042
Michael Wrightd02c5b62014-02-10 15:10:22 -08005043void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005044 if (DEBUG_FOCUS) {
5045 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5046 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005047
5048 bool changed;
5049 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005050 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005051
5052 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5053 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005054 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005055 }
5056
5057 if (mDispatchEnabled && !enabled) {
5058 resetAndDropEverythingLocked("dispatcher is being disabled");
5059 }
5060
5061 mDispatchEnabled = enabled;
5062 mDispatchFrozen = frozen;
5063 changed = true;
5064 } else {
5065 changed = false;
5066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005067 } // release lock
5068
5069 if (changed) {
5070 // Wake up poll loop since it may need to make new input dispatching choices.
5071 mLooper->wake();
5072 }
5073}
5074
5075void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005076 if (DEBUG_FOCUS) {
5077 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5078 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005079
5080 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005081 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005082
5083 if (mInputFilterEnabled == enabled) {
5084 return;
5085 }
5086
5087 mInputFilterEnabled = enabled;
5088 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5089 } // release lock
5090
5091 // Wake up poll loop since there might be work to do to drop everything.
5092 mLooper->wake();
5093}
5094
Antonio Kanteka042c022022-07-06 16:51:07 -07005095bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5096 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005097 bool needWake = false;
5098 {
5099 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005100 ALOGD_IF(DEBUG_TOUCH_MODE,
5101 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5102 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5103 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5104 mTouchModePerDisplay.count(displayId) == 0
5105 ? "not set"
5106 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5107
Antonio Kantek15beb512022-06-13 22:35:41 +00005108 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5109 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005110 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005111 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005112 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005113 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5114 !recentWindowsAreOwnedByLocked(pid, uid)) {
5115 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5116 "window nor none of the previously interacted window",
5117 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005118 return false;
5119 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005120 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005121 mTouchModePerDisplay[displayId] = inTouchMode;
5122 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5123 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005124 needWake = enqueueInboundEventLocked(std::move(entry));
5125 } // release lock
5126
5127 if (needWake) {
5128 mLooper->wake();
5129 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005130 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005131}
5132
Antonio Kantek48710e42022-03-24 14:19:30 -07005133bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5134 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5135 if (focusedToken == nullptr) {
5136 return false;
5137 }
5138 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5139 return isWindowOwnedBy(windowHandle, pid, uid);
5140}
5141
5142bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5143 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5144 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5145 const sp<WindowInfoHandle> windowHandle =
5146 getWindowHandleLocked(connectionToken);
5147 return isWindowOwnedBy(windowHandle, pid, uid);
5148 }) != mInteractionConnectionTokens.end();
5149}
5150
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005151void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5152 if (opacity < 0 || opacity > 1) {
5153 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5154 return;
5155 }
5156
5157 std::scoped_lock lock(mLock);
5158 mMaximumObscuringOpacityForTouch = opacity;
5159}
5160
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005161std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5162InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005163 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5164 for (TouchedWindow& w : state.windows) {
5165 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005166 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005167 }
5168 }
5169 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005170 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005171}
5172
arthurhungb89ccb02020-12-30 16:19:01 +08005173bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5174 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005175 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005176 if (DEBUG_FOCUS) {
5177 ALOGD("Trivial transfer to same window.");
5178 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005179 return true;
5180 }
5181
Michael Wrightd02c5b62014-02-10 15:10:22 -08005182 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005183 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005184
Arthur Hungabbb9d82021-09-01 14:52:30 +00005185 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005186 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005187 if (state == nullptr || touchedWindow == nullptr) {
5188 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005189 return false;
5190 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005191
Arthur Hungabbb9d82021-09-01 14:52:30 +00005192 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5193 if (toWindowHandle == nullptr) {
5194 ALOGW("Cannot transfer focus because to window not found.");
5195 return false;
5196 }
5197
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005198 if (DEBUG_FOCUS) {
5199 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005200 touchedWindow->windowHandle->getName().c_str(),
5201 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005202 }
5203
Arthur Hungabbb9d82021-09-01 14:52:30 +00005204 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005205 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005206 BitSet32 pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005207 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005208 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005209
Arthur Hungabbb9d82021-09-01 14:52:30 +00005210 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005211 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005212 ftl::Flags<InputTarget::Flags> newTargetFlags =
5213 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005214 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005215 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005216 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005217 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005218
Arthur Hungabbb9d82021-09-01 14:52:30 +00005219 // Store the dragging window.
5220 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005221 if (pointerIds.count() != 1) {
5222 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5223 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005224 return false;
5225 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005226 // Track the pointer id for drag window and generate the drag state.
5227 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005228 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005229 }
5230
Arthur Hungabbb9d82021-09-01 14:52:30 +00005231 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005232 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5233 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005234 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005235 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005236 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005237 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005238 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005239 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005240 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5241 newTargetFlags);
5242
5243 // Check if the wallpaper window should deliver the corresponding event.
5244 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5245 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005246 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005247 } // release lock
5248
5249 // Wake up poll loop since it may need to make new input dispatching choices.
5250 mLooper->wake();
5251 return true;
5252}
5253
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005254/**
5255 * Get the touched foreground window on the given display.
5256 * Return null if there are no windows touched on that display, or if more than one foreground
5257 * window is being touched.
5258 */
5259sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5260 auto stateIt = mTouchStatesByDisplay.find(displayId);
5261 if (stateIt == mTouchStatesByDisplay.end()) {
5262 ALOGI("No touch state on display %" PRId32, displayId);
5263 return nullptr;
5264 }
5265
5266 const TouchState& state = stateIt->second;
5267 sp<WindowInfoHandle> touchedForegroundWindow;
5268 // If multiple foreground windows are touched, return nullptr
5269 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005270 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005271 if (touchedForegroundWindow != nullptr) {
5272 ALOGI("Two or more foreground windows: %s and %s",
5273 touchedForegroundWindow->getName().c_str(),
5274 window.windowHandle->getName().c_str());
5275 return nullptr;
5276 }
5277 touchedForegroundWindow = window.windowHandle;
5278 }
5279 }
5280 return touchedForegroundWindow;
5281}
5282
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005283// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005284bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005285 sp<IBinder> fromToken;
5286 { // acquire lock
5287 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005288 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005289 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005290 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5291 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005292 return false;
5293 }
5294
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005295 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5296 if (from == nullptr) {
5297 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5298 return false;
5299 }
5300
5301 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005302 } // release lock
5303
5304 return transferTouchFocus(fromToken, destChannelToken);
5305}
5306
Michael Wrightd02c5b62014-02-10 15:10:22 -08005307void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005308 if (DEBUG_FOCUS) {
5309 ALOGD("Resetting and dropping all events (%s).", reason);
5310 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005311
Michael Wrightfb04fd52022-11-24 22:31:11 +00005312 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313 synthesizeCancelationEventsForAllConnectionsLocked(options);
5314
5315 resetKeyRepeatLocked();
5316 releasePendingEventLocked();
5317 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005318 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005319
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005320 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005321 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005322 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323}
5324
5325void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005326 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005327 dumpDispatchStateLocked(dump);
5328
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005329 std::istringstream stream(dump);
5330 std::string line;
5331
5332 while (std::getline(stream, line, '\n')) {
5333 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005334 }
5335}
5336
Prabir Pradhan99987712020-11-10 18:43:05 -08005337std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5338 std::string dump;
5339
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005340 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5341 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005342
5343 std::string windowName = "None";
5344 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005345 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005346 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5347 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5348 : "token has capture without window";
5349 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005350 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005351
5352 return dump;
5353}
5354
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005355void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005356 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5357 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5358 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005359 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005360
Tiger Huang721e26f2018-07-24 22:26:19 +08005361 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5362 dump += StringPrintf(INDENT "FocusedApplications:\n");
5363 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5364 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005365 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005366 const std::chrono::duration timeout =
5367 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005368 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005369 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005370 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005372 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005373 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005374 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005375
Vishnu Nairc519ff72021-01-21 08:23:08 -08005376 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005377 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005378
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005379 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005380 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005381 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005382 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5383 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005384 }
5385 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005386 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005387 }
5388
arthurhung6d4bed92021-03-17 11:59:33 +08005389 if (mDragState) {
5390 dump += StringPrintf(INDENT "DragState:\n");
5391 mDragState->dump(dump, INDENT2);
5392 }
5393
Arthur Hungb92218b2018-08-14 12:00:21 +08005394 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005395 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5396 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5397 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5398 const auto& displayInfo = it->second;
5399 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5400 displayInfo.logicalHeight);
5401 displayInfo.transform.dump(dump, "transform", INDENT4);
5402 } else {
5403 dump += INDENT2 "No DisplayInfo found!\n";
5404 }
5405
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005406 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005407 dump += INDENT2 "Windows:\n";
5408 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005409 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5410 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005411
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005412 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005413 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005414 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005415 "applicationInfo.name=%s, "
5416 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005417 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005418 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005419 windowInfo->displayId,
5420 windowInfo->inputConfig.string().c_str(),
5421 windowInfo->alpha, windowInfo->frameLeft,
5422 windowInfo->frameTop, windowInfo->frameRight,
5423 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005424 windowInfo->applicationInfo.name.c_str(),
5425 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005426 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005427 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005428 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005429 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005430 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005431 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005432 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005433 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005434 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005435 }
5436 } else {
5437 dump += INDENT2 "Windows: <none>\n";
5438 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005439 }
5440 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005441 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005442 }
5443
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005444 if (!mGlobalMonitorsByDisplay.empty()) {
5445 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5446 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005447 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005448 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005449 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005450 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005451 }
5452
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005453 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005454
5455 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005456 if (!mRecentQueue.empty()) {
5457 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005458 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005459 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005460 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005461 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005462 }
5463 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005464 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005465 }
5466
5467 // Dump event currently being dispatched.
5468 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005469 dump += INDENT "PendingEvent:\n";
5470 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005471 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005472 dump += StringPrintf(", age=%" PRId64 "ms\n",
5473 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005474 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005475 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005476 }
5477
5478 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005479 if (!mInboundQueue.empty()) {
5480 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005481 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005482 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005483 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005484 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485 }
5486 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005487 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488 }
5489
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005490 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005491 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005492 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005493 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005494 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005495 }
5496 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005497 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005498 }
5499
Prabir Pradhancef936d2021-07-21 16:17:52 +00005500 if (!mCommandQueue.empty()) {
5501 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5502 } else {
5503 dump += INDENT "CommandQueue: <empty>\n";
5504 }
5505
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005506 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005507 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005508 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005509 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005510 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005511 connection->inputChannel->getFd().get(),
5512 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005513 connection->getWindowName().c_str(),
5514 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005515 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005516
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005517 if (!connection->outboundQueue.empty()) {
5518 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5519 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005520 dump += dumpQueue(connection->outboundQueue, currentTime);
5521
Michael Wrightd02c5b62014-02-10 15:10:22 -08005522 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005523 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005524 }
5525
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005526 if (!connection->waitQueue.empty()) {
5527 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5528 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005529 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005530 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005531 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005532 }
5533 }
5534 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005535 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005536 }
5537
5538 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005539 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5540 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005541 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005542 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005543 }
5544
Antonio Kantek15beb512022-06-13 22:35:41 +00005545 if (!mTouchModePerDisplay.empty()) {
5546 dump += INDENT "TouchModePerDisplay:\n";
5547 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5548 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5549 std::to_string(touchMode).c_str());
5550 }
5551 } else {
5552 dump += INDENT "TouchModePerDisplay: <none>\n";
5553 }
5554
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005555 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005556 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5557 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5558 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005559 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005560 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005561}
5562
Michael Wright3dd60e22019-03-27 22:06:44 +00005563void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5564 const size_t numMonitors = monitors.size();
5565 for (size_t i = 0; i < numMonitors; i++) {
5566 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005567 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005568 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5569 dump += "\n";
5570 }
5571}
5572
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005573class LooperEventCallback : public LooperCallback {
5574public:
5575 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5576 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5577
5578private:
5579 std::function<int(int events)> mCallback;
5580};
5581
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005582Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005583 if (DEBUG_CHANNEL_CREATION) {
5584 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5585 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005586
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005587 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005588 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005589 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005590
5591 if (result) {
5592 return base::Error(result) << "Failed to open input channel pair with name " << name;
5593 }
5594
Michael Wrightd02c5b62014-02-10 15:10:22 -08005595 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005596 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005597 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005598 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005599 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005600 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005601
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005602 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5603 ALOGE("Created a new connection, but the token %p is already known", token.get());
5604 }
5605 mConnectionsByToken.emplace(token, connection);
5606
5607 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5608 this, std::placeholders::_1, token);
5609
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005610 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5611 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005612 } // release lock
5613
5614 // Wake the looper because some connections have changed.
5615 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005616 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005617}
5618
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005619Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005620 const std::string& name,
5621 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005622 std::shared_ptr<InputChannel> serverChannel;
5623 std::unique_ptr<InputChannel> clientChannel;
5624 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5625 if (result) {
5626 return base::Error(result) << "Failed to open input channel pair with name " << name;
5627 }
5628
Michael Wright3dd60e22019-03-27 22:06:44 +00005629 { // acquire lock
5630 std::scoped_lock _l(mLock);
5631
5632 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005633 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5634 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005635 }
5636
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005637 sp<Connection> connection =
5638 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005639 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005640 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005641
5642 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5643 ALOGE("Created a new connection, but the token %p is already known", token.get());
5644 }
5645 mConnectionsByToken.emplace(token, connection);
5646 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5647 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005648
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005649 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005650
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005651 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5652 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005653 }
Garfield Tan15601662020-09-22 15:32:38 -07005654
Michael Wright3dd60e22019-03-27 22:06:44 +00005655 // Wake the looper because some connections have changed.
5656 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005657 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005658}
5659
Garfield Tan15601662020-09-22 15:32:38 -07005660status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005661 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005662 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005663
Garfield Tan15601662020-09-22 15:32:38 -07005664 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005665 if (status) {
5666 return status;
5667 }
5668 } // release lock
5669
5670 // Wake the poll loop because removing the connection may have changed the current
5671 // synchronization state.
5672 mLooper->wake();
5673 return OK;
5674}
5675
Garfield Tan15601662020-09-22 15:32:38 -07005676status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5677 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005678 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005679 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005680 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005681 return BAD_VALUE;
5682 }
5683
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005684 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005685
Michael Wrightd02c5b62014-02-10 15:10:22 -08005686 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005687 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005688 }
5689
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005690 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005691
5692 nsecs_t currentTime = now();
5693 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5694
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005695 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005696 return OK;
5697}
5698
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005699void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005700 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5701 auto& [displayId, monitors] = *it;
5702 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5703 return monitor.inputChannel->getConnectionToken() == connectionToken;
5704 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005705
Michael Wright3dd60e22019-03-27 22:06:44 +00005706 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005707 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005708 } else {
5709 ++it;
5710 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005711 }
5712}
5713
Michael Wright3dd60e22019-03-27 22:06:44 +00005714status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005715 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005716 return pilferPointersLocked(token);
5717}
Michael Wright3dd60e22019-03-27 22:06:44 +00005718
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005719status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005720 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5721 if (!requestingChannel) {
5722 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5723 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005724 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005725
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005726 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07005727 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.isEmpty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005728 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5729 " Ignoring.");
5730 return BAD_VALUE;
5731 }
5732
5733 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005734 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005735 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005736 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005737 "input channel stole pointer stream");
5738 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005739 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005740 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005741 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005742 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005743 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005744 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005745 if (channel != nullptr && channel->getConnectionToken() != token) {
5746 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5747 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5748 canceledWindows += channel->getName();
5749 }
5750 }
5751 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5752 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5753 canceledWindows.c_str());
5754
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005755 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005756 // This only blocks relevant pointers to be sent to other windows
5757 window.isPilferingPointers = true;
5758
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005759 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005760 return OK;
5761}
5762
Prabir Pradhan99987712020-11-10 18:43:05 -08005763void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5764 { // acquire lock
5765 std::scoped_lock _l(mLock);
5766 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005767 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005768 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5769 windowHandle != nullptr ? windowHandle->getName().c_str()
5770 : "token without window");
5771 }
5772
Vishnu Nairc519ff72021-01-21 08:23:08 -08005773 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005774 if (focusedToken != windowToken) {
5775 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5776 enabled ? "enable" : "disable");
5777 return;
5778 }
5779
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005780 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005781 ALOGW("Ignoring request to %s Pointer Capture: "
5782 "window has %s requested pointer capture.",
5783 enabled ? "enable" : "disable", enabled ? "already" : "not");
5784 return;
5785 }
5786
Christine Franksb768bb42021-11-29 12:11:31 -08005787 if (enabled) {
5788 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5789 mIneligibleDisplaysForPointerCapture.end(),
5790 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5791 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5792 return;
5793 }
5794 }
5795
Prabir Pradhan99987712020-11-10 18:43:05 -08005796 setPointerCaptureLocked(enabled);
5797 } // release lock
5798
5799 // Wake the thread to process command entries.
5800 mLooper->wake();
5801}
5802
Christine Franksb768bb42021-11-29 12:11:31 -08005803void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5804 { // acquire lock
5805 std::scoped_lock _l(mLock);
5806 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5807 if (!isEligible) {
5808 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5809 }
5810 } // release lock
5811}
5812
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005813std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5814 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005815 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005816 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005817 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005818 }
5819 }
5820 }
5821 return std::nullopt;
5822}
5823
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005824sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005825 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005826 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005827 }
5828
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005829 for (const auto& [token, connection] : mConnectionsByToken) {
5830 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005831 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005832 }
5833 }
Robert Carr4e670e52018-08-15 13:26:12 -07005834
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005835 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005836}
5837
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005838std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5839 sp<Connection> connection = getConnectionLocked(connectionToken);
5840 if (connection == nullptr) {
5841 return "<nullptr>";
5842 }
5843 return connection->getInputChannelName();
5844}
5845
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005846void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005847 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005848 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005849}
5850
Prabir Pradhancef936d2021-07-21 16:17:52 +00005851void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5852 const sp<Connection>& connection, uint32_t seq,
5853 bool handled, nsecs_t consumeTime) {
5854 // Handle post-event policy actions.
5855 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5856 if (dispatchEntryIt == connection->waitQueue.end()) {
5857 return;
5858 }
5859 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5860 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5861 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5862 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5863 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5864 }
5865 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5866 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5867 connection->inputChannel->getConnectionToken(),
5868 dispatchEntry->deliveryTime, consumeTime, finishTime);
5869 }
5870
5871 bool restartEvent;
5872 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5873 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5874 restartEvent =
5875 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5876 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5877 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5878 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5879 handled);
5880 } else {
5881 restartEvent = false;
5882 }
5883
5884 // Dequeue the event and start the next cycle.
5885 // Because the lock might have been released, it is possible that the
5886 // contents of the wait queue to have been drained, so we need to double-check
5887 // a few things.
5888 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5889 if (dispatchEntryIt != connection->waitQueue.end()) {
5890 dispatchEntry = *dispatchEntryIt;
5891 connection->waitQueue.erase(dispatchEntryIt);
5892 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5893 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5894 if (!connection->responsive) {
5895 connection->responsive = isConnectionResponsive(*connection);
5896 if (connection->responsive) {
5897 // The connection was unresponsive, and now it's responsive.
5898 processConnectionResponsiveLocked(*connection);
5899 }
5900 }
5901 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005902 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005903 connection->outboundQueue.push_front(dispatchEntry);
5904 traceOutboundQueueLength(*connection);
5905 } else {
5906 releaseDispatchEntry(dispatchEntry);
5907 }
5908 }
5909
5910 // Start the next dispatch cycle for this connection.
5911 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005912}
5913
Prabir Pradhancef936d2021-07-21 16:17:52 +00005914void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5915 const sp<IBinder>& newToken) {
5916 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5917 scoped_unlock unlock(mLock);
5918 mPolicy->notifyFocusChanged(oldToken, newToken);
5919 };
5920 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005921}
5922
Prabir Pradhancef936d2021-07-21 16:17:52 +00005923void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5924 auto command = [this, token, x, y]() REQUIRES(mLock) {
5925 scoped_unlock unlock(mLock);
5926 mPolicy->notifyDropWindow(token, x, y);
5927 };
5928 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005929}
5930
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005931void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5932 if (connection == nullptr) {
5933 LOG_ALWAYS_FATAL("Caller must check for nullness");
5934 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005935 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5936 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005937 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005938 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005939 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005940 return;
5941 }
5942 /**
5943 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5944 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5945 * has changed. This could cause newer entries to time out before the already dispatched
5946 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5947 * processes the events linearly. So providing information about the oldest entry seems to be
5948 * most useful.
5949 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005950 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005951 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5952 std::string reason =
5953 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005954 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005955 ns2ms(currentWait),
5956 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005957 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005958 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005959
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005960 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5961
5962 // Stop waking up for events on this connection, it is already unresponsive
5963 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005964}
5965
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005966void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5967 std::string reason =
5968 StringPrintf("%s does not have a focused window", application->getName().c_str());
5969 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005970
Prabir Pradhancef936d2021-07-21 16:17:52 +00005971 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5972 scoped_unlock unlock(mLock);
5973 mPolicy->notifyNoFocusedWindowAnr(application);
5974 };
5975 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005976}
5977
chaviw98318de2021-05-19 16:45:23 -05005978void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005979 const std::string& reason) {
5980 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5981 updateLastAnrStateLocked(windowLabel, reason);
5982}
5983
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005984void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5985 const std::string& reason) {
5986 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005987 updateLastAnrStateLocked(windowLabel, reason);
5988}
5989
5990void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5991 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005992 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005993 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005994 struct tm tm;
5995 localtime_r(&t, &tm);
5996 char timestr[64];
5997 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005998 mLastAnrState.clear();
5999 mLastAnrState += INDENT "ANR:\n";
6000 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006001 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6002 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006003 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006004}
6005
Prabir Pradhancef936d2021-07-21 16:17:52 +00006006void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6007 KeyEntry& entry) {
6008 const KeyEvent event = createKeyEvent(entry);
6009 nsecs_t delay = 0;
6010 { // release lock
6011 scoped_unlock unlock(mLock);
6012 android::base::Timer t;
6013 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
6014 entry.policyFlags);
6015 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6016 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6017 std::to_string(t.duration().count()).c_str());
6018 }
6019 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006020
6021 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006022 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006023 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006024 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006025 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006026 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006027 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006029}
6030
Prabir Pradhancef936d2021-07-21 16:17:52 +00006031void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006032 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006033 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006034 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006035 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006036 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006037 };
6038 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006039}
6040
Prabir Pradhanedd96402022-02-15 01:46:16 -08006041void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6042 std::optional<int32_t> pid) {
6043 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006044 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006045 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006046 };
6047 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006048}
6049
6050/**
6051 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6052 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6053 * command entry to the command queue.
6054 */
6055void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6056 std::string reason) {
6057 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006058 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006059 if (connection.monitor) {
6060 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6061 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006062 pid = findMonitorPidByTokenLocked(connectionToken);
6063 } else {
6064 // The connection is a window
6065 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6066 reason.c_str());
6067 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6068 if (handle != nullptr) {
6069 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006070 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006071 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006072 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006073}
6074
6075/**
6076 * Tell the policy that a connection has become responsive so that it can stop ANR.
6077 */
6078void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6079 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006080 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006081 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006082 pid = findMonitorPidByTokenLocked(connectionToken);
6083 } else {
6084 // The connection is a window
6085 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6086 if (handle != nullptr) {
6087 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006088 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006089 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006090 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006091}
6092
Prabir Pradhancef936d2021-07-21 16:17:52 +00006093bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006094 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006095 KeyEntry& keyEntry, bool handled) {
6096 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006097 if (!handled) {
6098 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006099 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006100 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006101 return false;
6102 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006103
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006104 // Get the fallback key state.
6105 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006106 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006107 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006108 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006109 connection->inputState.removeFallbackKey(originalKeyCode);
6110 }
6111
6112 if (handled || !dispatchEntry->hasForegroundTarget()) {
6113 // If the application handles the original key for which we previously
6114 // generated a fallback or if the window is not a foreground window,
6115 // then cancel the associated fallback key, if any.
6116 if (fallbackKeyCode != -1) {
6117 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006118 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6119 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6120 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6121 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6122 keyEntry.policyFlags);
6123 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006124 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006125 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006126
6127 mLock.unlock();
6128
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006129 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006130 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006131
6132 mLock.lock();
6133
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006134 // Cancel the fallback key.
6135 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006136 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006137 "application handled the original non-fallback key "
6138 "or is no longer a foreground target, "
6139 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006140 options.keyCode = fallbackKeyCode;
6141 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006142 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006143 connection->inputState.removeFallbackKey(originalKeyCode);
6144 }
6145 } else {
6146 // If the application did not handle a non-fallback key, first check
6147 // that we are in a good state to perform unhandled key event processing
6148 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006149 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006150 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006151 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6152 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6153 "since this is not an initial down. "
6154 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6155 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6156 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006157 return false;
6158 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006159
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006160 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006161 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6162 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6163 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6164 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6165 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006166 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006167
6168 mLock.unlock();
6169
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006170 bool fallback =
6171 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006172 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006173
6174 mLock.lock();
6175
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006176 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006177 connection->inputState.removeFallbackKey(originalKeyCode);
6178 return false;
6179 }
6180
6181 // Latch the fallback keycode for this key on an initial down.
6182 // The fallback keycode cannot change at any other point in the lifecycle.
6183 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006184 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006185 fallbackKeyCode = event.getKeyCode();
6186 } else {
6187 fallbackKeyCode = AKEYCODE_UNKNOWN;
6188 }
6189 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6190 }
6191
6192 ALOG_ASSERT(fallbackKeyCode != -1);
6193
6194 // Cancel the fallback key if the policy decides not to send it anymore.
6195 // We will continue to dispatch the key to the policy but we will no
6196 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006197 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6198 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006199 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6200 if (fallback) {
6201 ALOGD("Unhandled key event: Policy requested to send key %d"
6202 "as a fallback for %d, but on the DOWN it had requested "
6203 "to send %d instead. Fallback canceled.",
6204 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6205 } else {
6206 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6207 "but on the DOWN it had requested to send %d. "
6208 "Fallback canceled.",
6209 originalKeyCode, fallbackKeyCode);
6210 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006211 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006212
Michael Wrightfb04fd52022-11-24 22:31:11 +00006213 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006214 "canceling fallback, policy no longer desires it");
6215 options.keyCode = fallbackKeyCode;
6216 synthesizeCancelationEventsForConnectionLocked(connection, options);
6217
6218 fallback = false;
6219 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006220 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006221 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006222 }
6223 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006224
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006225 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6226 {
6227 std::string msg;
6228 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6229 connection->inputState.getFallbackKeys();
6230 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6231 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6232 }
6233 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6234 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006235 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006236 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006237
6238 if (fallback) {
6239 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006240 keyEntry.eventTime = event.getEventTime();
6241 keyEntry.deviceId = event.getDeviceId();
6242 keyEntry.source = event.getSource();
6243 keyEntry.displayId = event.getDisplayId();
6244 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6245 keyEntry.keyCode = fallbackKeyCode;
6246 keyEntry.scanCode = event.getScanCode();
6247 keyEntry.metaState = event.getMetaState();
6248 keyEntry.repeatCount = event.getRepeatCount();
6249 keyEntry.downTime = event.getDownTime();
6250 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006251
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006252 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6253 ALOGD("Unhandled key event: Dispatching fallback key. "
6254 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6255 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6256 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006257 return true; // restart the event
6258 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006259 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6260 ALOGD("Unhandled key event: No fallback key.");
6261 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006262
6263 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006264 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006265 }
6266 }
6267 return false;
6268}
6269
Prabir Pradhancef936d2021-07-21 16:17:52 +00006270bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006271 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006272 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006273 return false;
6274}
6275
Michael Wrightd02c5b62014-02-10 15:10:22 -08006276void InputDispatcher::traceInboundQueueLengthLocked() {
6277 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006278 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006279 }
6280}
6281
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006282void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006283 if (ATRACE_ENABLED()) {
6284 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006285 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6286 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006287 }
6288}
6289
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006290void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006291 if (ATRACE_ENABLED()) {
6292 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006293 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6294 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006295 }
6296}
6297
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006298void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006299 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006300
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006301 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006302 dumpDispatchStateLocked(dump);
6303
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006304 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006305 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006306 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006307 }
6308}
6309
6310void InputDispatcher::monitor() {
6311 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006312 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006313 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006314 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006315}
6316
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006317/**
6318 * Wake up the dispatcher and wait until it processes all events and commands.
6319 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6320 * this method can be safely called from any thread, as long as you've ensured that
6321 * the work you are interested in completing has already been queued.
6322 */
6323bool InputDispatcher::waitForIdle() {
6324 /**
6325 * Timeout should represent the longest possible time that a device might spend processing
6326 * events and commands.
6327 */
6328 constexpr std::chrono::duration TIMEOUT = 100ms;
6329 std::unique_lock lock(mLock);
6330 mLooper->wake();
6331 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6332 return result == std::cv_status::no_timeout;
6333}
6334
Vishnu Naire798b472020-07-23 13:52:21 -07006335/**
6336 * Sets focus to the window identified by the token. This must be called
6337 * after updating any input window handles.
6338 *
6339 * Params:
6340 * request.token - input channel token used to identify the window that should gain focus.
6341 * request.focusedToken - the token that the caller expects currently to be focused. If the
6342 * specified token does not match the currently focused window, this request will be dropped.
6343 * If the specified focused token matches the currently focused window, the call will succeed.
6344 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6345 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6346 * when requesting the focus change. This determines which request gets
6347 * precedence if there is a focus change request from another source such as pointer down.
6348 */
Vishnu Nair958da932020-08-21 17:12:37 -07006349void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6350 { // acquire lock
6351 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006352 std::optional<FocusResolver::FocusChanges> changes =
6353 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6354 if (changes) {
6355 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006356 }
6357 } // release lock
6358 // Wake up poll loop since it may need to make new input dispatching choices.
6359 mLooper->wake();
6360}
6361
Vishnu Nairc519ff72021-01-21 08:23:08 -08006362void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6363 if (changes.oldFocus) {
6364 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006365 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006366 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006367 "focus left window");
6368 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006369 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006370 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006371 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006372 if (changes.newFocus) {
6373 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006374 }
6375
Prabir Pradhan99987712020-11-10 18:43:05 -08006376 // If a window has pointer capture, then it must have focus. We need to ensure that this
6377 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6378 // If the window loses focus before it loses pointer capture, then the window can be in a state
6379 // where it has pointer capture but not focus, violating the contract. Therefore we must
6380 // dispatch the pointer capture event before the focus event. Since focus events are added to
6381 // the front of the queue (above), we add the pointer capture event to the front of the queue
6382 // after the focus events are added. This ensures the pointer capture event ends up at the
6383 // front.
6384 disablePointerCaptureForcedLocked();
6385
Vishnu Nairc519ff72021-01-21 08:23:08 -08006386 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006387 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006388 }
6389}
Vishnu Nair958da932020-08-21 17:12:37 -07006390
Prabir Pradhan99987712020-11-10 18:43:05 -08006391void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006392 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006393 return;
6394 }
6395
6396 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6397
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006398 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006399 setPointerCaptureLocked(false);
6400 }
6401
6402 if (!mWindowTokenWithPointerCapture) {
6403 // No need to send capture changes because no window has capture.
6404 return;
6405 }
6406
6407 if (mPendingEvent != nullptr) {
6408 // Move the pending event to the front of the queue. This will give the chance
6409 // for the pending event to be dropped if it is a captured event.
6410 mInboundQueue.push_front(mPendingEvent);
6411 mPendingEvent = nullptr;
6412 }
6413
6414 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006415 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006416 mInboundQueue.push_front(std::move(entry));
6417}
6418
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006419void InputDispatcher::setPointerCaptureLocked(bool enable) {
6420 mCurrentPointerCaptureRequest.enable = enable;
6421 mCurrentPointerCaptureRequest.seq++;
6422 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006423 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006424 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006425 };
6426 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006427}
6428
Vishnu Nair599f1412021-06-21 10:39:58 -07006429void InputDispatcher::displayRemoved(int32_t displayId) {
6430 { // acquire lock
6431 std::scoped_lock _l(mLock);
6432 // Set an empty list to remove all handles from the specific display.
6433 setInputWindowsLocked(/* window handles */ {}, displayId);
6434 setFocusedApplicationLocked(displayId, nullptr);
6435 // Call focus resolver to clean up stale requests. This must be called after input windows
6436 // have been removed for the removed display.
6437 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006438 // Reset pointer capture eligibility, regardless of previous state.
6439 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006440 // Remove the associated touch mode state.
6441 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006442 } // release lock
6443
6444 // Wake up poll loop since it may need to make new input dispatching choices.
6445 mLooper->wake();
6446}
6447
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006448void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6449 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006450 // The listener sends the windows as a flattened array. Separate the windows by display for
6451 // more convenient parsing.
6452 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006453 for (const auto& info : windowInfos) {
6454 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006455 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006456 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006457
6458 { // acquire lock
6459 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006460
6461 // Ensure that we have an entry created for all existing displays so that if a displayId has
6462 // no windows, we can tell that the windows were removed from the display.
6463 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6464 handlesPerDisplay[displayId];
6465 }
6466
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006467 mDisplayInfos.clear();
6468 for (const auto& displayInfo : displayInfos) {
6469 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6470 }
6471
6472 for (const auto& [displayId, handles] : handlesPerDisplay) {
6473 setInputWindowsLocked(handles, displayId);
6474 }
6475 }
6476 // Wake up poll loop since it may need to make new input dispatching choices.
6477 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006478}
6479
Vishnu Nair062a8672021-09-03 16:07:44 -07006480bool InputDispatcher::shouldDropInput(
6481 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006482 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6483 (windowHandle->getInfo()->inputConfig.test(
6484 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006485 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006486 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6487 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006488 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006489 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006490 windowHandle->getInfo()->displayId);
6491 return true;
6492 }
6493 return false;
6494}
6495
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006496void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6497 const std::vector<gui::WindowInfo>& windowInfos,
6498 const std::vector<DisplayInfo>& displayInfos) {
6499 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6500}
6501
Arthur Hungdfd528e2021-12-08 13:23:04 +00006502void InputDispatcher::cancelCurrentTouch() {
6503 {
6504 std::scoped_lock _l(mLock);
6505 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006506 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006507 "cancel current touch");
6508 synthesizeCancelationEventsForAllConnectionsLocked(options);
6509
6510 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006511 }
6512 // Wake up poll loop since there might be work to do.
6513 mLooper->wake();
6514}
6515
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006516void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6517 std::scoped_lock _l(mLock);
6518 mMonitorDispatchingTimeout = timeout;
6519}
6520
Arthur Hungc539dbb2022-12-08 07:45:36 +00006521void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6522 const sp<WindowInfoHandle>& oldWindowHandle,
6523 const sp<WindowInfoHandle>& newWindowHandle,
6524 TouchState& state, const BitSet32& pointerIds) {
6525 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6526 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6527 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6528 newWindowHandle->getInfo()->inputConfig.test(
6529 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6530 const sp<WindowInfoHandle> oldWallpaper =
6531 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6532 const sp<WindowInfoHandle> newWallpaper =
6533 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6534 if (oldWallpaper == newWallpaper) {
6535 return;
6536 }
6537
6538 if (oldWallpaper != nullptr) {
6539 state.addOrUpdateWindow(oldWallpaper, InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6540 BitSet32(0));
6541 }
6542
6543 if (newWallpaper != nullptr) {
6544 state.addOrUpdateWindow(newWallpaper,
6545 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6546 InputTarget::Flags::WINDOW_IS_OBSCURED |
6547 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6548 pointerIds);
6549 }
6550}
6551
6552void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6553 ftl::Flags<InputTarget::Flags> newTargetFlags,
6554 const sp<WindowInfoHandle> fromWindowHandle,
6555 const sp<WindowInfoHandle> toWindowHandle,
6556 TouchState& state, const BitSet32& pointerIds) {
6557 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6558 fromWindowHandle->getInfo()->inputConfig.test(
6559 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6560 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6561 toWindowHandle->getInfo()->inputConfig.test(
6562 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6563
6564 const sp<WindowInfoHandle> oldWallpaper =
6565 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6566 const sp<WindowInfoHandle> newWallpaper =
6567 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6568 if (oldWallpaper == newWallpaper) {
6569 return;
6570 }
6571
6572 if (oldWallpaper != nullptr) {
6573 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6574 "transferring touch focus to another window");
6575 state.removeWindowByToken(oldWallpaper->getToken());
6576 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6577 }
6578
6579 if (newWallpaper != nullptr) {
6580 nsecs_t downTimeInTarget = now();
6581 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6582 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6583 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6584 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6585 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
6586 sp<Connection> wallpaperConnection = getConnectionLocked(newWallpaper->getToken());
6587 if (wallpaperConnection != nullptr) {
6588 sp<Connection> toConnection = getConnectionLocked(toWindowHandle->getToken());
6589 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6590 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6591 wallpaperFlags);
6592 }
6593 }
6594}
6595
6596sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6597 const sp<WindowInfoHandle>& windowHandle) const {
6598 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6599 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6600 bool foundWindow = false;
6601 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6602 if (!foundWindow && otherHandle != windowHandle) {
6603 continue;
6604 }
6605 if (windowHandle == otherHandle) {
6606 foundWindow = true;
6607 continue;
6608 }
6609
6610 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6611 return otherHandle;
6612 }
6613 }
6614 return nullptr;
6615}
6616
Garfield Tane84e6f92019-08-29 17:28:41 -07006617} // namespace android::inputdispatcher