blob: 906bb1b0d9bb3362346086a272c7ce238e3bbc7e [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
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000557} // namespace
558
Michael Wrightd02c5b62014-02-10 15:10:22 -0800559// --- InputDispatcher ---
560
Garfield Tan00f511d2019-06-12 16:55:40 -0700561InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800562 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
563
564InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
565 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700566 : mPolicy(policy),
567 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700568 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800569 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700570 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700571 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700572 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800573 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700574 mDispatchEnabled(false),
575 mDispatchFrozen(false),
576 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100577 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000578 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800579 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800580 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000581 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000582 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700583 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800584 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800585
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700586 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700587#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700588 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700589#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700590 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800591 policy->getDispatcherConfiguration(&mConfig);
592}
593
594InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000595 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596
Prabir Pradhancef936d2021-07-21 16:17:52 +0000597 resetKeyRepeatLocked();
598 releasePendingEventLocked();
599 drainInboundQueueLocked();
600 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800601
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000602 while (!mConnectionsByToken.empty()) {
603 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000604 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
605 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800606 }
607}
608
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700609status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700610 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700611 return ALREADY_EXISTS;
612 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700613 mThread = std::make_unique<InputThread>(
614 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
615 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700616}
617
618status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700619 if (mThread && mThread->isCallingThread()) {
620 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700621 return INVALID_OPERATION;
622 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700623 mThread.reset();
624 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700625}
626
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700628 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800630 std::scoped_lock _l(mLock);
631 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632
633 // Run a dispatch loop if there are no pending commands.
634 // The dispatch loop might enqueue commands to run afterwards.
635 if (!haveCommandsLocked()) {
636 dispatchOnceInnerLocked(&nextWakeupTime);
637 }
638
639 // Run all pending commands if there are any.
640 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000641 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700642 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800643 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800644
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700645 // If we are still waiting for ack on some events,
646 // we might have to wake up earlier to check if an app is anr'ing.
647 const nsecs_t nextAnrCheck = processAnrsLocked();
648 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
649
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800650 // We are about to enter an infinitely long sleep, because we have no commands or
651 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700652 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800653 mDispatcherEnteredIdle.notify_all();
654 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800655 } // release lock
656
657 // Wait for callback or timeout or wake. (make sure we round up, not down)
658 nsecs_t currentTime = now();
659 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
660 mLooper->pollOnce(timeoutMillis);
661}
662
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700663/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500664 * Raise ANR if there is no focused window.
665 * Before the ANR is raised, do a final state check:
666 * 1. The currently focused application must be the same one we are waiting for.
667 * 2. Ensure we still don't have a focused window.
668 */
669void InputDispatcher::processNoFocusedWindowAnrLocked() {
670 // Check if the application that we are waiting for is still focused.
671 std::shared_ptr<InputApplicationHandle> focusedApplication =
672 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
673 if (focusedApplication == nullptr ||
674 focusedApplication->getApplicationToken() !=
675 mAwaitedFocusedApplication->getApplicationToken()) {
676 // Unexpected because we should have reset the ANR timer when focused application changed
677 ALOGE("Waited for a focused window, but focused application has already changed to %s",
678 focusedApplication->getName().c_str());
679 return; // The focused application has changed.
680 }
681
chaviw98318de2021-05-19 16:45:23 -0500682 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500683 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
684 if (focusedWindowHandle != nullptr) {
685 return; // We now have a focused window. No need for ANR.
686 }
687 onAnrLocked(mAwaitedFocusedApplication);
688}
689
690/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700691 * Check if any of the connections' wait queues have events that are too old.
692 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
693 * Return the time at which we should wake up next.
694 */
695nsecs_t InputDispatcher::processAnrsLocked() {
696 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700697 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700698 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
699 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
700 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500701 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700702 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500703 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700704 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700705 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500706 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700707 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
708 }
709 }
710
711 // Check if any connection ANRs are due
712 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
713 if (currentTime < nextAnrCheck) { // most likely scenario
714 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
715 }
716
717 // If we reached here, we have an unresponsive connection.
718 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
719 if (connection == nullptr) {
720 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
721 return nextAnrCheck;
722 }
723 connection->responsive = false;
724 // Stop waking up for this unresponsive connection
725 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000726 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700727 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700728}
729
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800730std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
731 const sp<Connection>& connection) {
732 if (connection->monitor) {
733 return mMonitorDispatchingTimeout;
734 }
735 const sp<WindowInfoHandle> window =
736 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700737 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500738 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700739 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500740 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700741}
742
Michael Wrightd02c5b62014-02-10 15:10:22 -0800743void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
744 nsecs_t currentTime = now();
745
Jeff Browndc5992e2014-04-11 01:27:26 -0700746 // Reset the key repeat timer whenever normal dispatch is suspended while the
747 // device is in a non-interactive state. This is to ensure that we abort a key
748 // repeat if the device is just coming out of sleep.
749 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800750 resetKeyRepeatLocked();
751 }
752
753 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
754 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100755 if (DEBUG_FOCUS) {
756 ALOGD("Dispatch frozen. Waiting some more.");
757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800758 return;
759 }
760
761 // Optimize latency of app switches.
762 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
763 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
764 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
765 if (mAppSwitchDueTime < *nextWakeupTime) {
766 *nextWakeupTime = mAppSwitchDueTime;
767 }
768
769 // Ready to start a new event.
770 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700771 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700772 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773 if (isAppSwitchDue) {
774 // The inbound queue is empty so the app switch key we were waiting
775 // for will never arrive. Stop waiting for it.
776 resetPendingAppSwitchLocked(false);
777 isAppSwitchDue = false;
778 }
779
780 // Synthesize a key repeat if appropriate.
781 if (mKeyRepeatState.lastKeyEntry) {
782 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
783 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
784 } else {
785 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
786 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
787 }
788 }
789 }
790
791 // Nothing to do if there is no pending event.
792 if (!mPendingEvent) {
793 return;
794 }
795 } else {
796 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700797 mPendingEvent = mInboundQueue.front();
798 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 traceInboundQueueLengthLocked();
800 }
801
802 // Poke user activity for this event.
803 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700804 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 }
807
808 // Now we have an event to dispatch.
809 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700810 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800811 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700812 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700814 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800815 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700816 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800817 }
818
819 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700820 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821 }
822
823 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700824 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700825 const ConfigurationChangedEntry& typedEntry =
826 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700827 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700828 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700829 break;
830 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800831
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700832 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700833 const DeviceResetEntry& typedEntry =
834 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700835 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700836 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700837 break;
838 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100840 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700841 std::shared_ptr<FocusEntry> typedEntry =
842 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100843 dispatchFocusLocked(currentTime, typedEntry);
844 done = true;
845 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
846 break;
847 }
848
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700849 case EventEntry::Type::TOUCH_MODE_CHANGED: {
850 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
851 dispatchTouchModeChangeLocked(currentTime, typedEntry);
852 done = true;
853 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
854 break;
855 }
856
Prabir Pradhan99987712020-11-10 18:43:05 -0800857 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
858 const auto typedEntry =
859 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
860 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
861 done = true;
862 break;
863 }
864
arthurhungb89ccb02020-12-30 16:19:01 +0800865 case EventEntry::Type::DRAG: {
866 std::shared_ptr<DragEntry> typedEntry =
867 std::static_pointer_cast<DragEntry>(mPendingEvent);
868 dispatchDragLocked(currentTime, typedEntry);
869 done = true;
870 break;
871 }
872
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700873 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700874 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700875 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700876 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700877 resetPendingAppSwitchLocked(true);
878 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700879 } else if (dropReason == DropReason::NOT_DROPPED) {
880 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700881 }
882 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700883 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700884 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700885 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700886 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
887 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700888 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700889 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700890 break;
891 }
892
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700893 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700894 std::shared_ptr<MotionEntry> motionEntry =
895 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700896 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
897 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700899 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700900 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700901 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700902 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
903 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700904 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700905 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700906 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907 }
Chris Yef59a2f42020-10-16 12:55:26 -0700908
909 case EventEntry::Type::SENSOR: {
910 std::shared_ptr<SensorEntry> sensorEntry =
911 std::static_pointer_cast<SensorEntry>(mPendingEvent);
912 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
913 dropReason = DropReason::APP_SWITCH;
914 }
915 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
916 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
917 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
918 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
919 dropReason = DropReason::STALE;
920 }
921 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
922 done = true;
923 break;
924 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925 }
926
927 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700928 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700929 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930 }
Michael Wright3a981722015-06-10 15:26:13 +0100931 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932
933 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -0700934 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800935 }
936}
937
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800938bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
939 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
940}
941
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700942/**
943 * Return true if the events preceding this incoming motion event should be dropped
944 * Return false otherwise (the default behaviour)
945 */
946bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700947 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700948 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700949
950 // Optimize case where the current application is unresponsive and the user
951 // decides to touch a window in a different application.
952 // If the application takes too long to catch up then we drop all events preceding
953 // the touch into the other window.
954 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -0700955 const int32_t displayId = motionEntry.displayId;
956 const auto [x, y] = resolveTouchedPosition(motionEntry);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700957 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -0700958
chaviw98318de2021-05-19 16:45:23 -0500959 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700960 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700961 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700962 touchedWindowHandle->getApplicationToken() !=
963 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700964 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700965 ALOGI("Pruning input queue because user touched a different application while waiting "
966 "for %s",
967 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700968 return true;
969 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700970
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800971 // Alternatively, maybe there's a spy window that could handle this event.
972 const std::vector<sp<WindowInfoHandle>> touchedSpies =
973 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
974 for (const auto& windowHandle : touchedSpies) {
975 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000976 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800977 // This spy window could take more input. Drop all events preceding this
978 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700979 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800980 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700981 mAwaitedFocusedApplication->getName().c_str());
982 return true;
983 }
984 }
985 }
986
987 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
988 // yet been processed by some connections, the dispatcher will wait for these motion
989 // events to be processed before dispatching the key event. This is because these motion events
990 // may cause a new window to be launched, which the user might expect to receive focus.
991 // To prevent waiting forever for such events, just send the key to the currently focused window
992 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
993 ALOGD("Received a new pointer down event, stop waiting for events to process and "
994 "just send the pending key event to the focused window.");
995 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700996 }
997 return false;
998}
999
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001000bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001001 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001002 mInboundQueue.push_back(std::move(newEntry));
1003 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004 traceInboundQueueLengthLocked();
1005
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001006 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001007 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001008 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1009 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001010 // Optimize app switch latency.
1011 // If the application takes too long to catch up then we drop all events preceding
1012 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001013 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001014 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001015 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001016 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001017 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001018 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001019 if (DEBUG_APP_SWITCH) {
1020 ALOGD("App switch is pending!");
1021 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001022 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001023 mAppSwitchSawKeyDown = false;
1024 needWake = true;
1025 }
1026 }
1027 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001028
1029 // If a new up event comes in, and the pending event with same key code has been asked
1030 // to try again later because of the policy. We have to reset the intercept key wake up
1031 // time for it may have been handled in the policy and could be dropped.
1032 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1033 mPendingEvent->type == EventEntry::Type::KEY) {
1034 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1035 if (pendingKey.keyCode == keyEntry.keyCode &&
1036 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001037 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1038 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001039 pendingKey.interceptKeyWakeupTime = 0;
1040 needWake = true;
1041 }
1042 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001043 break;
1044 }
1045
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001046 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001047 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1048 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001049 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1050 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001051 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001052 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001053 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001055 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001056 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1057 break;
1058 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001059 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001060 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001061 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001062 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001063 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1064 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001065 // nothing to do
1066 break;
1067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068 }
1069
1070 return needWake;
1071}
1072
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001073void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001074 // Do not store sensor event in recent queue to avoid flooding the queue.
1075 if (entry->type != EventEntry::Type::SENSOR) {
1076 mRecentQueue.push_back(entry);
1077 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001078 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001079 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 }
1081}
1082
chaviw98318de2021-05-19 16:45:23 -05001083sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1084 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001085 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001086 bool addOutsideTargets,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07001087 bool ignoreDragWindow) const {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001088 if (addOutsideTargets && touchState == nullptr) {
1089 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001090 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001092 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001093 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001094 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001095 continue;
1096 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001098 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001099 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001100 return windowHandle;
1101 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001102
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001103 if (addOutsideTargets &&
1104 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001105 touchState->addOrUpdateWindow(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001106 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107 }
1108 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001109 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001110}
1111
Prabir Pradhand65552b2021-10-07 11:23:50 -07001112std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1113 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001114 // Traverse windows from front to back and gather the touched spy windows.
1115 std::vector<sp<WindowInfoHandle>> spyWindows;
1116 const auto& windowHandles = getWindowHandlesLocked(displayId);
1117 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1118 const WindowInfo& info = *windowHandle->getInfo();
1119
Prabir Pradhand65552b2021-10-07 11:23:50 -07001120 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001121 continue;
1122 }
1123 if (!info.isSpy()) {
1124 // The first touched non-spy window was found, so return the spy windows touched so far.
1125 return spyWindows;
1126 }
1127 spyWindows.push_back(windowHandle);
1128 }
1129 return spyWindows;
1130}
1131
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001132void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133 const char* reason;
1134 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001135 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001136 if (DEBUG_INBOUND_EVENT_DETAILS) {
1137 ALOGD("Dropped event because policy consumed it.");
1138 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001139 reason = "inbound event was dropped because the policy consumed it";
1140 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001141 case DropReason::DISABLED:
1142 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001143 ALOGI("Dropped event because input dispatch is disabled.");
1144 }
1145 reason = "inbound event was dropped because input dispatch is disabled";
1146 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001147 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001148 ALOGI("Dropped event because of pending overdue app switch.");
1149 reason = "inbound event was dropped because of pending overdue app switch";
1150 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001151 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001152 ALOGI("Dropped event because the current application is not responding and the user "
1153 "has started interacting with a different application.");
1154 reason = "inbound event was dropped because the current application is not responding "
1155 "and the user has started interacting with a different application";
1156 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001157 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001158 ALOGI("Dropped event because it is stale.");
1159 reason = "inbound event was dropped because it is stale";
1160 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001161 case DropReason::NO_POINTER_CAPTURE:
1162 ALOGI("Dropped event because there is no window with Pointer Capture.");
1163 reason = "inbound event was dropped because there is no window with Pointer Capture";
1164 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001165 case DropReason::NOT_DROPPED: {
1166 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001167 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001168 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169 }
1170
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001171 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001172 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001173 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001175 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001177 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001178 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1179 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001180 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001181 synthesizeCancelationEventsForAllConnectionsLocked(options);
1182 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001183 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1184 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001185 synthesizeCancelationEventsForAllConnectionsLocked(options);
1186 }
1187 break;
1188 }
Chris Yef59a2f42020-10-16 12:55:26 -07001189 case EventEntry::Type::SENSOR: {
1190 break;
1191 }
arthurhungb89ccb02020-12-30 16:19:01 +08001192 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1193 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001194 break;
1195 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001196 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001197 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001198 case EventEntry::Type::CONFIGURATION_CHANGED:
1199 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001200 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001201 break;
1202 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203 }
1204}
1205
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001206static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001207 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1208 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001209}
1210
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001211bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1212 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1213 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1214 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215}
1216
1217bool InputDispatcher::isAppSwitchPendingLocked() {
Colin Cross5b799302022-10-18 21:52:41 -07001218 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219}
1220
1221void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001222 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001224 if (DEBUG_APP_SWITCH) {
1225 if (handled) {
1226 ALOGD("App switch has arrived.");
1227 } else {
1228 ALOGD("App switch was abandoned.");
1229 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001231}
1232
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001234 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235}
1236
Prabir Pradhancef936d2021-07-21 16:17:52 +00001237bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001238 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239 return false;
1240 }
1241
1242 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001243 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001244 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001245 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1246 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001247 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 return true;
1249}
1250
Prabir Pradhancef936d2021-07-21 16:17:52 +00001251void InputDispatcher::postCommandLocked(Command&& command) {
1252 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253}
1254
1255void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001256 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001257 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001258 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259 releaseInboundEventLocked(entry);
1260 }
1261 traceInboundQueueLengthLocked();
1262}
1263
1264void InputDispatcher::releasePendingEventLocked() {
1265 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001267 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268 }
1269}
1270
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001271void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001273 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001274 if (DEBUG_DISPATCH_CYCLE) {
1275 ALOGD("Injected inbound event was dropped.");
1276 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001277 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 }
1279 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001280 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001281 }
1282 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283}
1284
1285void InputDispatcher::resetKeyRepeatLocked() {
1286 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001287 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288 }
1289}
1290
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001291std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1292 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293
Michael Wright2e732952014-09-24 13:26:59 -07001294 uint32_t policyFlags = entry->policyFlags &
1295 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001297 std::shared_ptr<KeyEntry> newEntry =
1298 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1299 entry->source, entry->displayId, policyFlags, entry->action,
1300 entry->flags, entry->keyCode, entry->scanCode,
1301 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001303 newEntry->syntheticRepeat = true;
1304 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001305 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001306 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307}
1308
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001309bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001310 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001311 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1312 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1313 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001314
1315 // Reset key repeating in case a keyboard device was added or removed or something.
1316 resetKeyRepeatLocked();
1317
1318 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001319 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1320 scoped_unlock unlock(mLock);
1321 mPolicy->notifyConfigurationChanged(eventTime);
1322 };
1323 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 return true;
1325}
1326
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001327bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1328 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001329 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1330 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1331 entry.deviceId);
1332 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001333
liushenxiang42232912021-05-21 20:24:09 +08001334 // Reset key repeating in case a keyboard device was disabled or enabled.
1335 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1336 resetKeyRepeatLocked();
1337 }
1338
Michael Wrightfb04fd52022-11-24 22:31:11 +00001339 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001340 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341 synthesizeCancelationEventsForAllConnectionsLocked(options);
1342 return true;
1343}
1344
Vishnu Nairad321cd2020-08-20 16:40:21 -07001345void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001346 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001347 if (mPendingEvent != nullptr) {
1348 // Move the pending event to the front of the queue. This will give the chance
1349 // for the pending event to get dispatched to the newly focused window
1350 mInboundQueue.push_front(mPendingEvent);
1351 mPendingEvent = nullptr;
1352 }
1353
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001354 std::unique_ptr<FocusEntry> focusEntry =
1355 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1356 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001357
1358 // This event should go to the front of the queue, but behind all other focus events
1359 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001360 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001361 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001362 [](const std::shared_ptr<EventEntry>& event) {
1363 return event->type == EventEntry::Type::FOCUS;
1364 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001365
1366 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001367 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001368}
1369
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001370void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001371 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001372 if (channel == nullptr) {
1373 return; // Window has gone away
1374 }
1375 InputTarget target;
1376 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001377 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001378 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001379 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1380 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001381 std::string reason = std::string("reason=").append(entry->reason);
1382 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001383 dispatchEventLocked(currentTime, entry, {target});
1384}
1385
Prabir Pradhan99987712020-11-10 18:43:05 -08001386void InputDispatcher::dispatchPointerCaptureChangedLocked(
1387 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1388 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001389 dropReason = DropReason::NOT_DROPPED;
1390
Prabir Pradhan99987712020-11-10 18:43:05 -08001391 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001392 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001393
1394 if (entry->pointerCaptureRequest.enable) {
1395 // Enable Pointer Capture.
1396 if (haveWindowWithPointerCapture &&
1397 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001398 // This can happen if pointer capture is disabled and re-enabled before we notify the
1399 // app of the state change, so there is no need to notify the app.
1400 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1401 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001402 }
1403 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001404 // This can happen if a window requests capture and immediately releases capture.
1405 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001406 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001407 return;
1408 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001409 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1410 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1411 return;
1412 }
1413
Vishnu Nairc519ff72021-01-21 08:23:08 -08001414 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001415 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1416 mWindowTokenWithPointerCapture = token;
1417 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001418 // Disable Pointer Capture.
1419 // We do not check if the sequence number matches for requests to disable Pointer Capture
1420 // for two reasons:
1421 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1422 // to disable capture with the same sequence number: one generated by
1423 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1424 // Capture being disabled in InputReader.
1425 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1426 // actual Pointer Capture state that affects events being generated by input devices is
1427 // in InputReader.
1428 if (!haveWindowWithPointerCapture) {
1429 // Pointer capture was already forcefully disabled because of focus change.
1430 dropReason = DropReason::NOT_DROPPED;
1431 return;
1432 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001433 token = mWindowTokenWithPointerCapture;
1434 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001435 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001436 setPointerCaptureLocked(false);
1437 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001438 }
1439
1440 auto channel = getInputChannelLocked(token);
1441 if (channel == nullptr) {
1442 // Window has gone away, clean up Pointer Capture state.
1443 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001444 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001445 setPointerCaptureLocked(false);
1446 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001447 return;
1448 }
1449 InputTarget target;
1450 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001451 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001452 entry->dispatchInProgress = true;
1453 dispatchEventLocked(currentTime, entry, {target});
1454
1455 dropReason = DropReason::NOT_DROPPED;
1456}
1457
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001458void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1459 const std::shared_ptr<TouchModeEntry>& entry) {
1460 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001461 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001462 if (windowHandles.empty()) {
1463 return;
1464 }
1465 const std::vector<InputTarget> inputTargets =
1466 getInputTargetsFromWindowHandlesLocked(windowHandles);
1467 if (inputTargets.empty()) {
1468 return;
1469 }
1470 entry->dispatchInProgress = true;
1471 dispatchEventLocked(currentTime, entry, inputTargets);
1472}
1473
1474std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1475 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1476 std::vector<InputTarget> inputTargets;
1477 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001478 const sp<IBinder>& token = handle->getToken();
1479 if (token == nullptr) {
1480 continue;
1481 }
1482 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1483 if (channel == nullptr) {
1484 continue; // Window has gone away
1485 }
1486 InputTarget target;
1487 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001488 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001489 inputTargets.push_back(target);
1490 }
1491 return inputTargets;
1492}
1493
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001494bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001495 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001497 if (!entry->dispatchInProgress) {
1498 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1499 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1500 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1501 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001502 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503 // We have seen two identical key downs in a row which indicates that the device
1504 // driver is automatically generating key repeats itself. We take note of the
1505 // repeat here, but we disable our own next key repeat timer since it is clear that
1506 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001507 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1508 // Make sure we don't get key down from a different device. If a different
1509 // device Id has same key pressed down, the new device Id will replace the
1510 // current one to hold the key repeat with repeat count reset.
1511 // In the future when got a KEY_UP on the device id, drop it and do not
1512 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1514 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001515 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516 } else {
1517 // Not a repeat. Save key down state in case we do see a repeat later.
1518 resetKeyRepeatLocked();
1519 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1520 }
1521 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001522 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1523 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001524 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001525 if (DEBUG_INBOUND_EVENT_DETAILS) {
1526 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1527 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001528 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529 resetKeyRepeatLocked();
1530 }
1531
1532 if (entry->repeatCount == 1) {
1533 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1534 } else {
1535 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1536 }
1537
1538 entry->dispatchInProgress = true;
1539
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001540 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001541 }
1542
1543 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001544 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 if (currentTime < entry->interceptKeyWakeupTime) {
1546 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1547 *nextWakeupTime = entry->interceptKeyWakeupTime;
1548 }
1549 return false; // wait until next wakeup
1550 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001551 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552 entry->interceptKeyWakeupTime = 0;
1553 }
1554
1555 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001556 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001558 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001559 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001560
1561 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1562 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1563 };
1564 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 return false; // wait for the command to run
1566 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001567 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001569 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001570 if (*dropReason == DropReason::NOT_DROPPED) {
1571 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 }
1573 }
1574
1575 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001576 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001577 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001578 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1579 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001580 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581 return true;
1582 }
1583
1584 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001585 InputEventInjectionResult injectionResult;
1586 sp<WindowInfoHandle> focusedWindow =
1587 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1588 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001589 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590 return false;
1591 }
1592
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001593 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001594 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001595 return true;
1596 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001597 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1598
1599 std::vector<InputTarget> inputTargets;
1600 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001601 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001602 BitSet32(0), getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001604 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001605 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001606
1607 // Dispatch the key.
1608 dispatchEventLocked(currentTime, entry, inputTargets);
1609 return true;
1610}
1611
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001612void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001613 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1614 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1615 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1616 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1617 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1618 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1619 entry.metaState, entry.repeatCount, entry.downTime);
1620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621}
1622
Prabir Pradhancef936d2021-07-21 16:17:52 +00001623void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1624 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001625 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001626 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1627 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1628 "source=0x%x, sensorType=%s",
1629 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001630 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001631 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001632 auto command = [this, entry]() REQUIRES(mLock) {
1633 scoped_unlock unlock(mLock);
1634
1635 if (entry->accuracyChanged) {
1636 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1637 }
1638 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1639 entry->hwTimestamp, entry->values);
1640 };
1641 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001642}
1643
1644bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001645 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1646 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001647 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001648 }
Chris Yef59a2f42020-10-16 12:55:26 -07001649 { // acquire lock
1650 std::scoped_lock _l(mLock);
1651
1652 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1653 std::shared_ptr<EventEntry> entry = *it;
1654 if (entry->type == EventEntry::Type::SENSOR) {
1655 it = mInboundQueue.erase(it);
1656 releaseInboundEventLocked(entry);
1657 }
1658 }
1659 }
1660 return true;
1661}
1662
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001663bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001664 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001665 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001667 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668 entry->dispatchInProgress = true;
1669
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001670 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001671 }
1672
1673 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001674 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001675 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001676 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1677 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 return true;
1679 }
1680
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001681 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682
1683 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001684 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685
1686 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001687 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688 if (isPointerEvent) {
1689 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001690
1691 if (mDragState &&
1692 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1693 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1694 pilferPointersLocked(mDragState->dragWindow->getToken());
1695 }
1696
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001697 std::vector<TouchedWindow> touchedWindows =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001698 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001699 /*byref*/ injectionResult);
1700 for (const TouchedWindow& touchedWindow : touchedWindows) {
1701 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED,
1702 "Shouldn't be adding window if the injection didn't succeed.");
1703 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1704 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
1705 inputTargets);
1706 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 } else {
1708 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001709 sp<WindowInfoHandle> focusedWindow =
1710 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1711 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1712 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1713 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001714 InputTarget::Flags::FOREGROUND |
1715 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001716 BitSet32(0), getDownTime(*entry), inputTargets);
1717 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001719 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720 return false;
1721 }
1722
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001723 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001724 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001725 return true;
1726 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001727 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001728 CancelationOptions::Mode mode(
1729 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1730 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001731 CancelationOptions options(mode, "input event injection failed");
1732 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733 return true;
1734 }
1735
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001736 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001737 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738
1739 // Dispatch the motion.
1740 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001741 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001742 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743 synthesizeCancelationEventsForAllConnectionsLocked(options);
1744 }
1745 dispatchEventLocked(currentTime, entry, inputTargets);
1746 return true;
1747}
1748
chaviw98318de2021-05-19 16:45:23 -05001749void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001750 bool isExiting, const int32_t rawX,
1751 const int32_t rawY) {
1752 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001753 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001754 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1755 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001756
1757 enqueueInboundEventLocked(std::move(dragEntry));
1758}
1759
1760void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1761 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1762 if (channel == nullptr) {
1763 return; // Window has gone away
1764 }
1765 InputTarget target;
1766 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001767 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001768 entry->dispatchInProgress = true;
1769 dispatchEventLocked(currentTime, entry, {target});
1770}
1771
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001772void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001773 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001774 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001775 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001776 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001777 "metaState=0x%x, buttonState=0x%x,"
1778 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001779 prefix, entry.eventTime, entry.deviceId,
1780 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1781 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1782 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1783 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001785 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1786 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1787 "x=%f, y=%f, pressure=%f, size=%f, "
1788 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1789 "orientation=%f",
1790 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1791 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1792 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1793 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1794 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1795 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1796 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1797 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1798 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1799 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1800 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001801 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802}
1803
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001804void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1805 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001806 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001807 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001808 if (DEBUG_DISPATCH_CYCLE) {
1809 ALOGD("dispatchEventToCurrentInputTargets");
1810 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001812 updateInteractionTokensLocked(*eventEntry, inputTargets);
1813
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1815
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001816 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001817
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001818 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001819 sp<Connection> connection =
1820 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001821 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001822 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001824 if (DEBUG_FOCUS) {
1825 ALOGD("Dropping event delivery to target with channel '%s' because it "
1826 "is no longer registered with the input dispatcher.",
1827 inputTarget.inputChannel->getName().c_str());
1828 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001829 }
1830 }
1831}
1832
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001833void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1834 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1835 // If the policy decides to close the app, we will get a channel removal event via
1836 // unregisterInputChannel, and will clean up the connection that way. We are already not
1837 // sending new pointers to the connection when it blocked, but focused events will continue to
1838 // pile up.
1839 ALOGW("Canceling events for %s because it is unresponsive",
1840 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001841 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001842 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001843 "application not responding");
1844 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845 }
1846}
1847
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001848void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001849 if (DEBUG_FOCUS) {
1850 ALOGD("Resetting ANR timeouts.");
1851 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852
1853 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001854 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001855 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856}
1857
Tiger Huang721e26f2018-07-24 22:26:19 +08001858/**
1859 * Get the display id that the given event should go to. If this event specifies a valid display id,
1860 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1861 * Focused display is the display that the user most recently interacted with.
1862 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001863int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001864 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001865 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001866 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001867 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1868 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001869 break;
1870 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001871 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001872 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1873 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001874 break;
1875 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001876 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001877 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001878 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001879 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001880 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001881 case EventEntry::Type::SENSOR:
1882 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001883 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001884 return ADISPLAY_ID_NONE;
1885 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001886 }
1887 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1888}
1889
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001890bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1891 const char* focusedWindowName) {
1892 if (mAnrTracker.empty()) {
1893 // already processed all events that we waited for
1894 mKeyIsWaitingForEventsTimeout = std::nullopt;
1895 return false;
1896 }
1897
1898 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1899 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001900 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001901 mKeyIsWaitingForEventsTimeout = currentTime +
1902 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1903 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001904 return true;
1905 }
1906
1907 // We still have pending events, and already started the timer
1908 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1909 return true; // Still waiting
1910 }
1911
1912 // Waited too long, and some connection still hasn't processed all motions
1913 // Just send the key to the focused window
1914 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1915 focusedWindowName);
1916 mKeyIsWaitingForEventsTimeout = std::nullopt;
1917 return false;
1918}
1919
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001920sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
1921 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
1922 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001923 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001924 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925
Tiger Huang721e26f2018-07-24 22:26:19 +08001926 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001927 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001928 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001929 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1930
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931 // If there is no currently focused window and no focused application
1932 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001933 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1934 ALOGI("Dropping %s event because there is no focused window or focused application in "
1935 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001936 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001937 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001938 }
1939
Vishnu Nair062a8672021-09-03 16:07:44 -07001940 // Drop key events if requested by input feature
1941 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001942 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07001943 }
1944
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001945 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1946 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1947 // start interacting with another application via touch (app switch). This code can be removed
1948 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1949 // an app is expected to have a focused window.
1950 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1951 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1952 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001953 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1954 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1955 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001956 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001957 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001958 ALOGW("Waiting because no window has focus but %s may eventually add a "
1959 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001960 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001961 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001962 outInjectionResult = InputEventInjectionResult::PENDING;
1963 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001964 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1965 // Already raised ANR. Drop the event
1966 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001967 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001968 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001969 } else {
1970 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001971 outInjectionResult = InputEventInjectionResult::PENDING;
1972 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001973 }
1974 }
1975
1976 // we have a valid, non-null focused window
1977 resetNoFocusedWindowTimeoutLocked();
1978
Prabir Pradhan5735a322022-04-11 17:23:34 +00001979 // Verify targeted injection.
1980 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
1981 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001982 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
1983 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984 }
1985
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001986 if (focusedWindowHandle->getInfo()->inputConfig.test(
1987 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001988 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001989 outInjectionResult = InputEventInjectionResult::PENDING;
1990 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001991 }
1992
1993 // If the event is a key event, then we must wait for all previous events to
1994 // complete before delivering it because previous events may have the
1995 // side-effect of transferring focus to a different window and we want to
1996 // ensure that the following keys are sent to the new window.
1997 //
1998 // Suppose the user touches a button in a window then immediately presses "A".
1999 // If the button causes a pop-up window to appear then we want to ensure that
2000 // the "A" key is delivered to the new pop-up window. This is because users
2001 // often anticipate pending UI changes when typing on a keyboard.
2002 // To obtain this behavior, we must serialize key events with respect to all
2003 // prior input events.
2004 if (entry.type == EventEntry::Type::KEY) {
2005 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2006 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002007 outInjectionResult = InputEventInjectionResult::PENDING;
2008 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002009 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010 }
2011
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002012 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2013 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014}
2015
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002016/**
2017 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2018 * that are currently unresponsive.
2019 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002020std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2021 const std::vector<Monitor>& monitors) const {
2022 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002023 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002024 [this](const Monitor& monitor) REQUIRES(mLock) {
2025 sp<Connection> connection =
2026 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002027 if (connection == nullptr) {
2028 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002029 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002030 return false;
2031 }
2032 if (!connection->responsive) {
2033 ALOGW("Unresponsive monitor %s will not get the new gesture",
2034 connection->inputChannel->getName().c_str());
2035 return false;
2036 }
2037 return true;
2038 });
2039 return responsiveMonitors;
2040}
2041
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002042/**
2043 * In general, touch should be always split between windows. Some exceptions:
2044 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2045 * from the same device, *and* the window that's receiving the current pointer does not support
2046 * split touch.
2047 * 2. Don't split mouse events
2048 */
2049bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2050 const MotionEntry& entry) const {
2051 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2052 // We should never split mouse events
2053 return false;
2054 }
2055 for (const TouchedWindow& touchedWindow : touchState.windows) {
2056 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2057 // Spy windows should not affect whether or not touch is split.
2058 continue;
2059 }
2060 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2061 continue;
2062 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002063 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2064 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2065 // Wallpaper window should not affect whether or not touch is split
2066 continue;
2067 }
2068
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002069 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2070 // being sent there. For now, use deviceId from touch state.
2071 if (entry.deviceId == touchState.deviceId && !touchedWindow.pointerIds.isEmpty()) {
2072 return false;
2073 }
2074 }
2075 return true;
2076}
2077
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002078std::vector<TouchedWindow> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002079 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2080 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002081 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002082
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002083 std::vector<TouchedWindow> touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002084 // For security reasons, we defer updating the touch state until we are sure that
2085 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002086 const int32_t displayId = entry.displayId;
2087 const int32_t action = entry.action;
2088 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089
2090 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002091 outInjectionResult = InputEventInjectionResult::PENDING;
Sam Dubey39d37cf2022-12-07 18:05:35 +00002092 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2093 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002095 // Copy current touch state into tempTouchState.
2096 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2097 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002098 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002099 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002100 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2101 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002102 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002103 }
2104
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002105 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002106 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002107 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002108
2109 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2110 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2111 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2112 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2113 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002114 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002115
Michael Wrightd02c5b62014-02-10 15:10:22 -08002116 if (newGesture) {
2117 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002118 if (switchedDevice && tempTouchState.isDown() && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002119 ALOGI("Dropping event because a pointer for a different device is already down "
2120 "in display %" PRId32,
2121 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002122 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002123 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakouf0ab2c82022-10-25 18:15:28 -07002124 return touchedWindows; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002126 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002127 tempTouchState.deviceId = entry.deviceId;
2128 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002130 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002131 ALOGI("Dropping move event because a pointer for a different device is already active "
2132 "in display %" PRId32,
2133 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002134 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002135 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakouf0ab2c82022-10-25 18:15:28 -07002136 return touchedWindows; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137 }
2138
2139 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2140 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002141 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002142 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002143 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002144 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Sam Dubey39d37cf2022-12-07 18:05:35 +00002145 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
2146 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002147
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002149 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002150 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2151 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002153 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002154 }
2155
Prabir Pradhan5735a322022-04-11 17:23:34 +00002156 // Verify targeted injection.
2157 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2158 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002159 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002160 newTouchedWindowHandle = nullptr;
2161 goto Failed;
2162 }
2163
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002164 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002165 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002166 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2167 // New window supports splitting, but we should never split mouse events.
2168 isSplit = !isFromMouse;
2169 } else if (isSplit) {
2170 // New window does not support splitting but we have already split events.
2171 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002172 newTouchedWindowHandle = nullptr;
2173 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002174 } else {
2175 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002176 // be delivered to a new window which supports split touch. Pointers from a mouse device
2177 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002178 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002179 }
2180
Sam Dubey39d37cf2022-12-07 18:05:35 +00002181 // Update hover state.
2182 if (newTouchedWindowHandle != nullptr) {
2183 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2184 newHoverWindowHandle = nullptr;
2185 } else if (isHoverAction) {
2186 newHoverWindowHandle = newTouchedWindowHandle;
2187 }
2188 }
2189
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002190 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002191 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002192 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002193 // Process the foreground window first so that it is the first to receive the event.
2194 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002195 }
2196
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002197 if (newTouchedWindows.empty()) {
2198 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2199 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002200 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002201 goto Failed;
2202 }
2203
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002204 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002205 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002206 continue;
2207 }
2208
2209 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002210 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002211
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002212 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2213 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002214 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002215 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002216
2217 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002218 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002219 }
2220 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002221 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002222 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002223 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002224 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002225
2226 // Update the temporary touch state.
2227 BitSet32 pointerIds;
Sam Dubey39d37cf2022-12-07 18:05:35 +00002228 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002229
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002230 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
2231 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002232
2233 // If this is the pointer going down and the touched window has a wallpaper
2234 // then also add the touched wallpaper windows so they are locked in for the duration
2235 // of the touch gesture.
2236 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2237 // engine only supports touch events. We would need to add a mechanism similar
2238 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2239 if (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2240 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2241 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2242 windowHandle->getInfo()->inputConfig.test(
2243 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2244 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2245 if (wallpaper != nullptr) {
2246 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2247 InputTarget::Flags::WINDOW_IS_OBSCURED |
2248 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2249 InputTarget::Flags::DISPATCH_AS_IS;
2250 if (isSplit) {
2251 wallpaperFlags |= InputTarget::Flags::SPLIT;
2252 }
2253 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2254 entry.eventTime);
2255 }
2256 }
2257 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002258 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002259
2260 // If any existing window is pilfering pointers from newly added window, remove it
2261 BitSet32 canceledPointers = BitSet32(0);
2262 for (const TouchedWindow& window : tempTouchState.windows) {
2263 if (window.isPilferingPointers) {
2264 canceledPointers |= window.pointerIds;
2265 }
2266 }
2267 tempTouchState.cancelPointersForNonPilferingWindows(canceledPointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268 } else {
2269 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2270
2271 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002272 if (!tempTouchState.isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002273 ALOGD_IF(DEBUG_FOCUS,
2274 "Dropping event because the pointer is not down or we previously "
2275 "dropped the pointer down event in display %" PRId32 ": %s",
2276 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002277 outInjectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278 goto Failed;
2279 }
2280
arthurhung6d4bed92021-03-17 11:59:33 +08002281 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002282
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002284 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002285 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002286 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07002287 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002288 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002289 tempTouchState.getFirstForegroundWindowHandle();
Sam Dubey39d37cf2022-12-07 18:05:35 +00002290 newTouchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002291 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002292
Prabir Pradhan5735a322022-04-11 17:23:34 +00002293 // Verify targeted injection.
2294 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2295 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002296 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002297 newTouchedWindowHandle = nullptr;
2298 goto Failed;
2299 }
2300
Vishnu Nair062a8672021-09-03 16:07:44 -07002301 // Drop touch events if requested by input feature
2302 if (newTouchedWindowHandle != nullptr &&
2303 shouldDropInput(entry, newTouchedWindowHandle)) {
2304 newTouchedWindowHandle = nullptr;
2305 }
2306
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002307 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2308 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002309 if (DEBUG_FOCUS) {
2310 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2311 oldTouchedWindowHandle->getName().c_str(),
2312 newTouchedWindowHandle->getName().c_str(), displayId);
2313 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002315 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002316 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002317 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318
2319 // Make a slippery entrance into the new window.
2320 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002321 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322 }
2323
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002324 ftl::Flags<InputTarget::Flags> targetFlags =
2325 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002326 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002327 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002328 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002330 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331 }
2332 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002333 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002334 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002335 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336 }
2337
2338 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002339 pointerIds.markBit(entry.pointerProperties[0].id);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002340 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2341 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002342
2343 // Check if the wallpaper window should deliver the corresponding event.
2344 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
2345 tempTouchState, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346 }
2347 }
Arthur Hung96483742022-11-15 03:30:48 +00002348
2349 // Update the pointerIds for non-splittable when it received pointer down.
2350 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2351 // If no split, we suppose all touched windows should receive pointer down.
2352 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2353 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2354 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2355 // Ignore drag window for it should just track one pointer.
2356 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2357 continue;
2358 }
2359 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2360 }
2361 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362 }
2363
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002364 // Update dispatching for hover enter and exit.
Sam Dubey39d37cf2022-12-07 18:05:35 +00002365 if (newHoverWindowHandle != mLastHoverWindowHandle) {
2366 // Let the previous window know that the hover sequence is over, unless we already did
2367 // it when dispatching it as is to newTouchedWindowHandle.
2368 if (mLastHoverWindowHandle != nullptr &&
2369 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2370 mLastHoverWindowHandle != newTouchedWindowHandle)) {
2371 if (DEBUG_HOVER) {
2372 ALOGD("Sending hover exit event to window %s.",
2373 mLastHoverWindowHandle->getName().c_str());
2374 }
2375 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2376 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT,
2377 BitSet32(0));
2378 }
2379
2380 // Let the new window know that the hover sequence is starting, unless we already did it
2381 // when dispatching it as is to newTouchedWindowHandle.
2382 if (newHoverWindowHandle != nullptr &&
2383 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2384 newHoverWindowHandle != newTouchedWindowHandle)) {
2385 if (DEBUG_HOVER) {
2386 ALOGD("Sending hover enter event to window %s.",
2387 newHoverWindowHandle->getName().c_str());
2388 }
2389 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2390 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER,
2391 BitSet32(0));
2392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002394
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002395 // Ensure that we have at least one foreground window or at least one window that cannot be a
2396 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2397 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2398 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002399 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2400 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002401 return !canReceiveForegroundTouches(
2402 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002403 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002404 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002405 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2406 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002407 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002408 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002409 }
2410
Prabir Pradhan5735a322022-04-11 17:23:34 +00002411 // Ensure that all touched windows are valid for injection.
2412 if (entry.injectionState != nullptr) {
2413 std::string errs;
2414 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002415 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002416 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2417 // dispatched to any uid, since the coords will be zeroed out later.
2418 continue;
2419 }
2420 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2421 if (err) errs += "\n - " + *err;
2422 }
2423 if (!errs.empty()) {
2424 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2425 "%d:%s",
2426 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002427 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002428 goto Failed;
2429 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002430 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002431
Michael Wrightd02c5b62014-02-10 15:10:22 -08002432 // Check whether windows listening for outside touches are owned by the same UID. If it is
2433 // set the policy flag that we will not reveal coordinate information to this window.
2434 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002435 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002436 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002437 if (foregroundWindowHandle) {
2438 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002439 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002440 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
chaviw98318de2021-05-19 16:45:23 -05002441 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2442 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2443 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002444 InputTarget::Flags::ZERO_COORDS,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002445 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002447 }
2448 }
2449 }
2450 }
2451
Sam Dubey39d37cf2022-12-07 18:05:35 +00002452 // Success! Output targets.
2453 touchedWindows = tempTouchState.windows;
Siarhei Vishniakoud57302f2022-11-08 11:12:29 -08002454 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubey39d37cf2022-12-07 18:05:35 +00002455
Michael Wrightd02c5b62014-02-10 15:10:22 -08002456 // Drop the outside or hover touch windows since we will not care about them
2457 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002458 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002459
2460Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002461 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002462 if (switchedDevice) {
2463 if (DEBUG_FOCUS) {
2464 ALOGD("Conflicting pointer actions: Switched to a different device.");
2465 }
2466 *outConflictingPointerActions = true;
2467 }
2468
2469 if (isHoverAction) {
2470 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002471 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002472 ALOGD_IF(DEBUG_FOCUS,
2473 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002474 *outConflictingPointerActions = true;
2475 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002476 tempTouchState.reset();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002477 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2478 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2479 tempTouchState.deviceId = entry.deviceId;
2480 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002481 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002482 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2483 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002484 // All pointers up or canceled.
2485 tempTouchState.reset();
2486 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2487 // First pointer went down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002488 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002489 ALOGD("Conflicting pointer actions: Down received while already down.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002490 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002491 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002492 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2493 // One pointer went up.
2494 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2495 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002496
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002497 for (size_t i = 0; i < tempTouchState.windows.size();) {
2498 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2499 touchedWindow.pointerIds.clearBit(pointerId);
2500 if (touchedWindow.pointerIds.isEmpty()) {
2501 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2502 continue;
2503 }
2504 i += 1;
2505 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002506 }
2507
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002508 // Save changes unless the action was scroll in which case the temporary touch
2509 // state was only valid for this one action.
2510 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002511 if (displayId >= 0) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002512 mTouchStatesByDisplay[displayId] = tempTouchState;
2513 } else {
2514 mTouchStatesByDisplay.erase(displayId);
2515 }
2516 }
2517
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002518 if (tempTouchState.windows.empty()) {
2519 mTouchStatesByDisplay.erase(displayId);
2520 }
2521
Sam Dubey39d37cf2022-12-07 18:05:35 +00002522 // Update hover state.
2523 mLastHoverWindowHandle = newHoverWindowHandle;
2524
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002525 return touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002526}
2527
arthurhung6d4bed92021-03-17 11:59:33 +08002528void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002529 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2530 // have an explicit reason to support it.
2531 constexpr bool isStylus = false;
2532
chaviw98318de2021-05-19 16:45:23 -05002533 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002534 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002535 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002536 if (dropWindow) {
2537 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002538 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002539 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002540 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002541 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002542 }
2543 mDragState.reset();
2544}
2545
2546void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002547 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002548 return;
2549 }
2550
arthurhung6d4bed92021-03-17 11:59:33 +08002551 if (!mDragState->isStartDrag) {
2552 mDragState->isStartDrag = true;
2553 mDragState->isStylusButtonDownAtStart =
2554 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2555 }
2556
Arthur Hung54745652022-04-20 07:17:41 +00002557 // Find the pointer index by id.
2558 int32_t pointerIndex = 0;
2559 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2560 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2561 if (pointerProperties.id == mDragState->pointerId) {
2562 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002563 }
Arthur Hung54745652022-04-20 07:17:41 +00002564 }
arthurhung6d4bed92021-03-17 11:59:33 +08002565
Arthur Hung54745652022-04-20 07:17:41 +00002566 if (uint32_t(pointerIndex) == entry.pointerCount) {
2567 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002568 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002569 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002570 return;
2571 }
2572
2573 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2574 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2575 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2576
2577 switch (maskedAction) {
2578 case AMOTION_EVENT_ACTION_MOVE: {
2579 // Handle the special case : stylus button no longer pressed.
2580 bool isStylusButtonDown =
2581 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2582 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2583 finishDragAndDrop(entry.displayId, x, y);
2584 return;
2585 }
2586
2587 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2588 // until we have an explicit reason to support it.
2589 constexpr bool isStylus = false;
2590
2591 const sp<WindowInfoHandle> hoverWindowHandle =
2592 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2593 isStylus, false /*addOutsideTargets*/,
2594 true /*ignoreDragWindow*/);
2595 // enqueue drag exit if needed.
2596 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2597 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2598 if (mDragState->dragHoverWindowHandle != nullptr) {
2599 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2600 y);
2601 }
2602 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2603 }
2604 // enqueue drag location if needed.
2605 if (hoverWindowHandle != nullptr) {
2606 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2607 }
2608 break;
2609 }
2610
2611 case AMOTION_EVENT_ACTION_POINTER_UP:
2612 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2613 break;
2614 }
2615 // The drag pointer is up.
2616 [[fallthrough]];
2617 case AMOTION_EVENT_ACTION_UP:
2618 finishDragAndDrop(entry.displayId, x, y);
2619 break;
2620 case AMOTION_EVENT_ACTION_CANCEL: {
2621 ALOGD("Receiving cancel when drag and drop.");
2622 sendDropWindowCommandLocked(nullptr, 0, 0);
2623 mDragState.reset();
2624 break;
2625 }
arthurhungb89ccb02020-12-30 16:19:01 +08002626 }
2627}
2628
chaviw98318de2021-05-19 16:45:23 -05002629void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002630 ftl::Flags<InputTarget::Flags> targetFlags,
2631 BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002632 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002633 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002634 std::vector<InputTarget>::iterator it =
2635 std::find_if(inputTargets.begin(), inputTargets.end(),
2636 [&windowHandle](const InputTarget& inputTarget) {
2637 return inputTarget.inputChannel->getConnectionToken() ==
2638 windowHandle->getToken();
2639 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002640
chaviw98318de2021-05-19 16:45:23 -05002641 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002642
2643 if (it == inputTargets.end()) {
2644 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002645 std::shared_ptr<InputChannel> inputChannel =
2646 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002647 if (inputChannel == nullptr) {
2648 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2649 return;
2650 }
2651 inputTarget.inputChannel = inputChannel;
2652 inputTarget.flags = targetFlags;
2653 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002654 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002655 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2656 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002657 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002658 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002659 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002660 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002661 inputTargets.push_back(inputTarget);
2662 it = inputTargets.end() - 1;
2663 }
2664
2665 ALOG_ASSERT(it->flags == targetFlags);
2666 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2667
chaviw1ff3d1e2020-07-01 15:53:47 -07002668 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669}
2670
Michael Wright3dd60e22019-03-27 22:06:44 +00002671void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002672 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002673 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2674 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002675
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002676 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2677 InputTarget target;
2678 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002679 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002680 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2681 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002682 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2683 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002684 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002685 target.setDefaultPointerTransform(target.displayTransform);
2686 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687 }
2688}
2689
Robert Carrc9bf1d32020-04-13 17:21:08 -07002690/**
2691 * Indicate whether one window handle should be considered as obscuring
2692 * another window handle. We only check a few preconditions. Actually
2693 * checking the bounds is left to the caller.
2694 */
chaviw98318de2021-05-19 16:45:23 -05002695static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2696 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002697 // Compare by token so cloned layers aren't counted
2698 if (haveSameToken(windowHandle, otherHandle)) {
2699 return false;
2700 }
2701 auto info = windowHandle->getInfo();
2702 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002703 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002704 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002705 } else if (otherInfo->alpha == 0 &&
2706 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002707 // Those act as if they were invisible, so we don't need to flag them.
2708 // We do want to potentially flag touchable windows even if they have 0
2709 // opacity, since they can consume touches and alter the effects of the
2710 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002711 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002712 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2713 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002714 } else if (info->ownerUid == otherInfo->ownerUid) {
2715 // If ownerUid is the same we don't generate occlusion events as there
2716 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002717 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002718 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002719 return false;
2720 } else if (otherInfo->displayId != info->displayId) {
2721 return false;
2722 }
2723 return true;
2724}
2725
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002726/**
2727 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2728 * untrusted, one should check:
2729 *
2730 * 1. If result.hasBlockingOcclusion is true.
2731 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2732 * BLOCK_UNTRUSTED.
2733 *
2734 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2735 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2736 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2737 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2738 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2739 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2740 *
2741 * If neither of those is true, then it means the touch can be allowed.
2742 */
2743InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002744 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2745 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002746 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002747 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002748 TouchOcclusionInfo info;
2749 info.hasBlockingOcclusion = false;
2750 info.obscuringOpacity = 0;
2751 info.obscuringUid = -1;
2752 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002753 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002754 if (windowHandle == otherHandle) {
2755 break; // All future windows are below us. Exit early.
2756 }
chaviw98318de2021-05-19 16:45:23 -05002757 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002758 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2759 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002760 if (DEBUG_TOUCH_OCCLUSION) {
2761 info.debugInfo.push_back(
2762 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2763 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002764 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2765 // we perform the checks below to see if the touch can be propagated or not based on the
2766 // window's touch occlusion mode
2767 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2768 info.hasBlockingOcclusion = true;
2769 info.obscuringUid = otherInfo->ownerUid;
2770 info.obscuringPackage = otherInfo->packageName;
2771 break;
2772 }
2773 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2774 uint32_t uid = otherInfo->ownerUid;
2775 float opacity =
2776 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2777 // Given windows A and B:
2778 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2779 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2780 opacityByUid[uid] = opacity;
2781 if (opacity > info.obscuringOpacity) {
2782 info.obscuringOpacity = opacity;
2783 info.obscuringUid = uid;
2784 info.obscuringPackage = otherInfo->packageName;
2785 }
2786 }
2787 }
2788 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002789 if (DEBUG_TOUCH_OCCLUSION) {
2790 info.debugInfo.push_back(
2791 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2792 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002793 return info;
2794}
2795
chaviw98318de2021-05-19 16:45:23 -05002796std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002797 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002798 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2799 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2800 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2801 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002802 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2803 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2804 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2805 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2806 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002807 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002808 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002809}
2810
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002811bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2812 if (occlusionInfo.hasBlockingOcclusion) {
2813 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2814 occlusionInfo.obscuringUid);
2815 return false;
2816 }
2817 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2818 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2819 "%.2f, maximum allowed = %.2f)",
2820 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2821 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2822 return false;
2823 }
2824 return true;
2825}
2826
chaviw98318de2021-05-19 16:45:23 -05002827bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002828 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002829 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002830 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2831 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002832 if (windowHandle == otherHandle) {
2833 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002834 }
chaviw98318de2021-05-19 16:45:23 -05002835 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002836 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002837 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838 return true;
2839 }
2840 }
2841 return false;
2842}
2843
chaviw98318de2021-05-19 16:45:23 -05002844bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002845 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002846 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2847 const WindowInfo* windowInfo = windowHandle->getInfo();
2848 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002849 if (windowHandle == otherHandle) {
2850 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002851 }
chaviw98318de2021-05-19 16:45:23 -05002852 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002853 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002854 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002855 return true;
2856 }
2857 }
2858 return false;
2859}
2860
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002861std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002862 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002863 if (applicationHandle != nullptr) {
2864 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002865 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866 } else {
2867 return applicationHandle->getName();
2868 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002869 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002870 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002871 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002872 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873 }
2874}
2875
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002876void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002877 if (!isUserActivityEvent(eventEntry)) {
2878 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002879 return;
2880 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002881 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002882 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002883 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002884 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002885 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002886 if (DEBUG_DISPATCH_CYCLE) {
2887 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2888 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889 return;
2890 }
2891 }
2892
2893 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002894 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002895 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002896 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2897 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002898 return;
2899 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002900
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002901 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002902 eventType = USER_ACTIVITY_EVENT_TOUCH;
2903 }
2904 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002905 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002906 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002907 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2908 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002909 return;
2910 }
2911 eventType = USER_ACTIVITY_EVENT_BUTTON;
2912 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002913 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002914 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002915 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002916 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002917 break;
2918 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919 }
2920
Prabir Pradhancef936d2021-07-21 16:17:52 +00002921 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2922 REQUIRES(mLock) {
2923 scoped_unlock unlock(mLock);
2924 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2925 };
2926 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927}
2928
2929void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002930 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002931 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002932 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002933 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002934 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002935 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002936 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002937 ATRACE_NAME(message.c_str());
2938 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002939 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002940 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002941 "globalScaleFactor=%f, pointerIds=0x%x %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002942 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002943 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2944 inputTarget.getPointerInfoString().c_str());
2945 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002946
2947 // Skip this event if the connection status is not normal.
2948 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002949 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002950 if (DEBUG_DISPATCH_CYCLE) {
2951 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002952 connection->getInputChannelName().c_str(),
2953 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002954 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002955 return;
2956 }
2957
2958 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002959 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002960 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002961 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002962 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002963
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002964 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002965 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002966 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
2967 "Splitting motion events requires a down time to be set for the "
2968 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002969 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002970 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
2971 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972 if (!splitMotionEntry) {
2973 return; // split event was dropped
2974 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002975 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2976 std::string reason = std::string("reason=pointer cancel on split window");
2977 android_log_event_list(LOGTAG_INPUT_CANCEL)
2978 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2979 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002980 if (DEBUG_FOCUS) {
2981 ALOGD("channel '%s' ~ Split motion event.",
2982 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002983 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002984 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002985 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2986 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002987 return;
2988 }
2989 }
2990
2991 // Not splitting. Enqueue dispatch entries for the event as is.
2992 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2993}
2994
2995void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002996 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002997 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002998 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002999 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003000 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003001 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003002 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003003 ATRACE_NAME(message.c_str());
3004 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003005 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3006 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003007
hongzuo liu95785e22022-09-06 02:51:35 +00003008 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003009
3010 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003011 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003012 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003013 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003014 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003015 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003016 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003017 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003018 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003019 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003020 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003021 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003022 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003023
3024 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003025 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003026 startDispatchCycleLocked(currentTime, connection);
3027 }
3028}
3029
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003030void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003031 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003032 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003033 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003034 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003035 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3036 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003037 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003038 ATRACE_NAME(message.c_str());
3039 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003040 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3041 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042 return;
3043 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003044
3045 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3046 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047
3048 // This is a new event.
3049 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003050 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003051 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003053 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3054 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003055 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003057 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003058 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003059 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003060 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003061 dispatchEntry->resolvedAction = keyEntry.action;
3062 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003063
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003064 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3065 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003066 if (DEBUG_DISPATCH_CYCLE) {
3067 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3068 "event",
3069 connection->getInputChannelName().c_str());
3070 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003071 return; // skip the inconsistent event
3072 }
3073 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003074 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003075
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003076 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003077 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003078 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3079 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3080 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3081 static_cast<int32_t>(IdGenerator::Source::OTHER);
3082 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003083 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003084 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003085 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003086 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003087 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003088 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003089 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003090 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003091 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003092 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3093 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003094 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003095 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003096 }
3097 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003098 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3099 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003100 if (DEBUG_DISPATCH_CYCLE) {
3101 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3102 "enter event",
3103 connection->getInputChannelName().c_str());
3104 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003105 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3106 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003107 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3108 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003109
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003110 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003111 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003112 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3113 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003114 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003115 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3116 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003118 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3119 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003120 if (DEBUG_DISPATCH_CYCLE) {
3121 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3122 "event",
3123 connection->getInputChannelName().c_str());
3124 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003125 return; // skip the inconsistent event
3126 }
3127
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003128 dispatchEntry->resolvedEventId =
3129 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3130 ? mIdGenerator.nextId()
3131 : motionEntry.id;
3132 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3133 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3134 ") to MotionEvent(id=0x%" PRIx32 ").",
3135 motionEntry.id, dispatchEntry->resolvedEventId);
3136 ATRACE_NAME(message.c_str());
3137 }
3138
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003139 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3140 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3141 // Skip reporting pointer down outside focus to the policy.
3142 break;
3143 }
3144
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003145 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003146 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003147
3148 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003149 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003150 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003151 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003152 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3153 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003154 break;
3155 }
Chris Yef59a2f42020-10-16 12:55:26 -07003156 case EventEntry::Type::SENSOR: {
3157 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3158 break;
3159 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003160 case EventEntry::Type::CONFIGURATION_CHANGED:
3161 case EventEntry::Type::DEVICE_RESET: {
3162 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003163 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003164 break;
3165 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166 }
3167
3168 // Remember that we are waiting for this dispatch to complete.
3169 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003170 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171 }
3172
3173 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003174 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003175 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003176}
3177
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003178/**
3179 * This function is purely for debugging. It helps us understand where the user interaction
3180 * was taking place. For example, if user is touching launcher, we will see a log that user
3181 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3182 * We will see both launcher and wallpaper in that list.
3183 * Once the interaction with a particular set of connections starts, no new logs will be printed
3184 * until the set of interacted connections changes.
3185 *
3186 * The following items are skipped, to reduce the logspam:
3187 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3188 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3189 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3190 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3191 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003192 */
3193void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3194 const std::vector<InputTarget>& targets) {
3195 // Skip ACTION_UP events, and all events other than keys and motions
3196 if (entry.type == EventEntry::Type::KEY) {
3197 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3198 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3199 return;
3200 }
3201 } else if (entry.type == EventEntry::Type::MOTION) {
3202 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3203 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3204 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3205 return;
3206 }
3207 } else {
3208 return; // Not a key or a motion
3209 }
3210
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003211 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003212 std::vector<sp<Connection>> newConnections;
3213 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003214 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003215 continue; // Skip windows that receive ACTION_OUTSIDE
3216 }
3217
3218 sp<IBinder> token = target.inputChannel->getConnectionToken();
3219 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003220 if (connection == nullptr) {
3221 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003222 }
3223 newConnectionTokens.insert(std::move(token));
3224 newConnections.emplace_back(connection);
3225 }
3226 if (newConnectionTokens == mInteractionConnectionTokens) {
3227 return; // no change
3228 }
3229 mInteractionConnectionTokens = newConnectionTokens;
3230
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003231 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003232 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003233 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003234 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003235 std::string message = "Interaction with: " + targetList;
3236 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003237 message += "<none>";
3238 }
3239 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3240}
3241
chaviwfd6d3512019-03-25 13:23:49 -07003242void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003243 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003244 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003245 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3246 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003247 return;
3248 }
3249
Vishnu Nairc519ff72021-01-21 08:23:08 -08003250 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003251 if (focusedToken == token) {
3252 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003253 return;
3254 }
3255
Prabir Pradhancef936d2021-07-21 16:17:52 +00003256 auto command = [this, token]() REQUIRES(mLock) {
3257 scoped_unlock unlock(mLock);
3258 mPolicy->onPointerDownOutsideFocus(token);
3259 };
3260 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261}
3262
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003263status_t InputDispatcher::publishMotionEvent(Connection& connection,
3264 DispatchEntry& dispatchEntry) const {
3265 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3266 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3267
3268 PointerCoords scaledCoords[MAX_POINTERS];
3269 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3270
3271 // Set the X and Y offset and X and Y scale depending on the input source.
3272 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003273 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003274 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3275 if (globalScaleFactor != 1.0f) {
3276 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3277 scaledCoords[i] = motionEntry.pointerCoords[i];
3278 // Don't apply window scale here since we don't want scale to affect raw
3279 // coordinates. The scale will be sent back to the client and applied
3280 // later when requesting relative coordinates.
3281 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3282 1 /* windowYScale */);
3283 }
3284 usingCoords = scaledCoords;
3285 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003286 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003287 // We don't want the dispatch target to know the coordinates
3288 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3289 scaledCoords[i].clear();
3290 }
3291 usingCoords = scaledCoords;
3292 }
3293
3294 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3295
3296 // Publish the motion event.
3297 return connection.inputPublisher
3298 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3299 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3300 std::move(hmac), dispatchEntry.resolvedAction,
3301 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3302 motionEntry.edgeFlags, motionEntry.metaState,
3303 motionEntry.buttonState, motionEntry.classification,
3304 dispatchEntry.transform, motionEntry.xPrecision,
3305 motionEntry.yPrecision, motionEntry.xCursorPosition,
3306 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3307 motionEntry.downTime, motionEntry.eventTime,
3308 motionEntry.pointerCount, motionEntry.pointerProperties,
3309 usingCoords);
3310}
3311
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003313 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003314 if (ATRACE_ENABLED()) {
3315 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003316 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003317 ATRACE_NAME(message.c_str());
3318 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003319 if (DEBUG_DISPATCH_CYCLE) {
3320 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3321 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003322
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003323 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003324 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003326 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003327 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328
3329 // Publish the event.
3330 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003331 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3332 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003333 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003334 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3335 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003336
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003337 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003338 status = connection->inputPublisher
3339 .publishKeyEvent(dispatchEntry->seq,
3340 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3341 keyEntry.source, keyEntry.displayId,
3342 std::move(hmac), dispatchEntry->resolvedAction,
3343 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3344 keyEntry.scanCode, keyEntry.metaState,
3345 keyEntry.repeatCount, keyEntry.downTime,
3346 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003347 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348 }
3349
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003350 case EventEntry::Type::MOTION: {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003351 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003352 break;
3353 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003354
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003355 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003356 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003357 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003358 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003359 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003360 break;
3361 }
3362
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003363 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3364 const TouchModeEntry& touchModeEntry =
3365 static_cast<const TouchModeEntry&>(eventEntry);
3366 status = connection->inputPublisher
3367 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3368 touchModeEntry.inTouchMode);
3369
3370 break;
3371 }
3372
Prabir Pradhan99987712020-11-10 18:43:05 -08003373 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3374 const auto& captureEntry =
3375 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3376 status = connection->inputPublisher
3377 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003378 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003379 break;
3380 }
3381
arthurhungb89ccb02020-12-30 16:19:01 +08003382 case EventEntry::Type::DRAG: {
3383 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3384 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3385 dragEntry.id, dragEntry.x,
3386 dragEntry.y,
3387 dragEntry.isExiting);
3388 break;
3389 }
3390
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003391 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003392 case EventEntry::Type::DEVICE_RESET:
3393 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003394 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003395 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003396 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003397 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003398 }
3399
3400 // Check the result.
3401 if (status) {
3402 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003403 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003405 "This is unexpected because the wait queue is empty, so the pipe "
3406 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003407 "event to it, status=%s(%d)",
3408 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3409 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3411 } else {
3412 // Pipe is full and we are waiting for the app to finish process some events
3413 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003414 if (DEBUG_DISPATCH_CYCLE) {
3415 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3416 "waiting for the application to catch up",
3417 connection->getInputChannelName().c_str());
3418 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419 }
3420 } else {
3421 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003422 "status=%s(%d)",
3423 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3424 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3426 }
3427 return;
3428 }
3429
3430 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003431 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3432 connection->outboundQueue.end(),
3433 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003434 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003435 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003436 if (connection->responsive) {
3437 mAnrTracker.insert(dispatchEntry->timeoutTime,
3438 connection->inputChannel->getConnectionToken());
3439 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003440 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003441 }
3442}
3443
chaviw09c8d2d2020-08-24 15:48:26 -07003444std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3445 size_t size;
3446 switch (event.type) {
3447 case VerifiedInputEvent::Type::KEY: {
3448 size = sizeof(VerifiedKeyEvent);
3449 break;
3450 }
3451 case VerifiedInputEvent::Type::MOTION: {
3452 size = sizeof(VerifiedMotionEvent);
3453 break;
3454 }
3455 }
3456 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3457 return mHmacKeyManager.sign(start, size);
3458}
3459
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003460const std::array<uint8_t, 32> InputDispatcher::getSignature(
3461 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003462 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3463 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003464 // Only sign events up and down events as the purely move events
3465 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003466 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003467 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003468
3469 VerifiedMotionEvent verifiedEvent =
3470 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3471 verifiedEvent.actionMasked = actionMasked;
3472 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3473 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003474}
3475
3476const std::array<uint8_t, 32> InputDispatcher::getSignature(
3477 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3478 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3479 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3480 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003481 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003482}
3483
Michael Wrightd02c5b62014-02-10 15:10:22 -08003484void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003485 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003486 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003487 if (DEBUG_DISPATCH_CYCLE) {
3488 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3489 connection->getInputChannelName().c_str(), seq, toString(handled));
3490 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003491
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003492 if (connection->status == Connection::Status::BROKEN ||
3493 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494 return;
3495 }
3496
3497 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003498 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3499 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3500 };
3501 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502}
3503
3504void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003505 const sp<Connection>& connection,
3506 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003507 if (DEBUG_DISPATCH_CYCLE) {
3508 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3509 connection->getInputChannelName().c_str(), toString(notify));
3510 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511
3512 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003513 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003514 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003515 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003516 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517
3518 // The connection appears to be unrecoverably broken.
3519 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003520 if (connection->status == Connection::Status::NORMAL) {
3521 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522
3523 if (notify) {
3524 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003525 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3526 connection->getInputChannelName().c_str());
3527
3528 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003529 scoped_unlock unlock(mLock);
3530 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3531 };
3532 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533 }
3534 }
3535}
3536
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003537void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3538 while (!queue.empty()) {
3539 DispatchEntry* dispatchEntry = queue.front();
3540 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003541 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542 }
3543}
3544
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003545void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003546 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003547 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548 }
3549 delete dispatchEntry;
3550}
3551
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003552int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3553 std::scoped_lock _l(mLock);
3554 sp<Connection> connection = getConnectionLocked(connectionToken);
3555 if (connection == nullptr) {
3556 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3557 connectionToken.get(), events);
3558 return 0; // remove the callback
3559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003561 bool notify;
3562 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3563 if (!(events & ALOOPER_EVENT_INPUT)) {
3564 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3565 "events=0x%x",
3566 connection->getInputChannelName().c_str(), events);
3567 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003568 }
3569
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003570 nsecs_t currentTime = now();
3571 bool gotOne = false;
3572 status_t status = OK;
3573 for (;;) {
3574 Result<InputPublisher::ConsumerResponse> result =
3575 connection->inputPublisher.receiveConsumerResponse();
3576 if (!result.ok()) {
3577 status = result.error().code();
3578 break;
3579 }
3580
3581 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3582 const InputPublisher::Finished& finish =
3583 std::get<InputPublisher::Finished>(*result);
3584 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3585 finish.consumeTime);
3586 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003587 if (shouldReportMetricsForConnection(*connection)) {
3588 const InputPublisher::Timeline& timeline =
3589 std::get<InputPublisher::Timeline>(*result);
3590 mLatencyTracker
3591 .trackGraphicsLatency(timeline.inputEventId,
3592 connection->inputChannel->getConnectionToken(),
3593 std::move(timeline.graphicsTimeline));
3594 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003595 }
3596 gotOne = true;
3597 }
3598 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003599 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003600 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003601 return 1;
3602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603 }
3604
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003605 notify = status != DEAD_OBJECT || !connection->monitor;
3606 if (notify) {
3607 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3608 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3609 status);
3610 }
3611 } else {
3612 // Monitor channels are never explicitly unregistered.
3613 // We do it automatically when the remote endpoint is closed so don't warn about them.
3614 const bool stillHaveWindowHandle =
3615 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3616 notify = !connection->monitor && stillHaveWindowHandle;
3617 if (notify) {
3618 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3619 connection->getInputChannelName().c_str(), events);
3620 }
3621 }
3622
3623 // Remove the channel.
3624 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3625 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626}
3627
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003628void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003630 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003631 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632 }
3633}
3634
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003635void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003636 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003637 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003638 for (const Monitor& monitor : monitors) {
3639 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003640 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003641 }
3642}
3643
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003645 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003646 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003647 if (connection == nullptr) {
3648 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003650
3651 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003652}
3653
3654void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3655 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003656 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003657 return;
3658 }
3659
3660 nsecs_t currentTime = now();
3661
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003662 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003663 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003665 if (cancelationEvents.empty()) {
3666 return;
3667 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003668 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3669 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3670 "with reality: %s, mode=%d.",
3671 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3672 options.mode);
3673 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003674
Arthur Hungb3307ee2021-10-14 10:57:37 +00003675 std::string reason = std::string("reason=").append(options.reason);
3676 android_log_event_list(LOGTAG_INPUT_CANCEL)
3677 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3678
Svet Ganov5d3bc372020-01-26 23:11:07 -08003679 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003680 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003681 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3682 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003683 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003684 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003685 target.globalScaleFactor = windowInfo->globalScaleFactor;
3686 }
3687 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003688 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003689
hongzuo liu95785e22022-09-06 02:51:35 +00003690 const bool wasEmpty = connection->outboundQueue.empty();
3691
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003692 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003693 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003694 switch (cancelationEventEntry->type) {
3695 case EventEntry::Type::KEY: {
3696 logOutboundKeyDetails("cancel - ",
3697 static_cast<const KeyEntry&>(*cancelationEventEntry));
3698 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003699 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003700 case EventEntry::Type::MOTION: {
3701 logOutboundMotionDetails("cancel - ",
3702 static_cast<const MotionEntry&>(*cancelationEventEntry));
3703 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003705 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003706 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003707 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3708 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003709 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003710 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003711 break;
3712 }
3713 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003714 case EventEntry::Type::DEVICE_RESET:
3715 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003716 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003717 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003718 break;
3719 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003720 }
3721
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003722 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003723 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003725
hongzuo liu95785e22022-09-06 02:51:35 +00003726 // If the outbound queue was previously empty, start the dispatch cycle going.
3727 if (wasEmpty && !connection->outboundQueue.empty()) {
3728 startDispatchCycleLocked(currentTime, connection);
3729 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730}
3731
Svet Ganov5d3bc372020-01-26 23:11:07 -08003732void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Arthur Hungc539dbb2022-12-08 07:45:36 +00003733 const nsecs_t downTime, const sp<Connection>& connection,
3734 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003735 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003736 return;
3737 }
3738
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003739 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003740 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003741
3742 if (downEvents.empty()) {
3743 return;
3744 }
3745
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003746 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003747 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3748 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003749 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003750
3751 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003752 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003753 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3754 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003755 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003756 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003757 target.globalScaleFactor = windowInfo->globalScaleFactor;
3758 }
3759 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00003760 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003761
hongzuo liu95785e22022-09-06 02:51:35 +00003762 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003763 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003764 switch (downEventEntry->type) {
3765 case EventEntry::Type::MOTION: {
3766 logOutboundMotionDetails("down - ",
3767 static_cast<const MotionEntry&>(*downEventEntry));
3768 break;
3769 }
3770
3771 case EventEntry::Type::KEY:
3772 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003773 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003774 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003775 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003776 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003777 case EventEntry::Type::SENSOR:
3778 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003779 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003780 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003781 break;
3782 }
3783 }
3784
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003785 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003786 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003787 }
3788
hongzuo liu95785e22022-09-06 02:51:35 +00003789 // If the outbound queue was previously empty, start the dispatch cycle going.
3790 if (wasEmpty && !connection->outboundQueue.empty()) {
3791 startDispatchCycleLocked(downTime, connection);
3792 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003793}
3794
Arthur Hungc539dbb2022-12-08 07:45:36 +00003795void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
3796 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
3797 if (windowHandle != nullptr) {
3798 sp<Connection> wallpaperConnection = getConnectionLocked(windowHandle->getToken());
3799 if (wallpaperConnection != nullptr) {
3800 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
3801 }
3802 }
3803}
3804
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003805std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003806 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003807 ALOG_ASSERT(pointerIds.value != 0);
3808
3809 uint32_t splitPointerIndexMap[MAX_POINTERS];
3810 PointerProperties splitPointerProperties[MAX_POINTERS];
3811 PointerCoords splitPointerCoords[MAX_POINTERS];
3812
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003813 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814 uint32_t splitPointerCount = 0;
3815
3816 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003817 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003819 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820 uint32_t pointerId = uint32_t(pointerProperties.id);
3821 if (pointerIds.hasBit(pointerId)) {
3822 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3823 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3824 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003825 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003826 splitPointerCount += 1;
3827 }
3828 }
3829
3830 if (splitPointerCount != pointerIds.count()) {
3831 // This is bad. We are missing some of the pointers that we expected to deliver.
3832 // Most likely this indicates that we received an ACTION_MOVE events that has
3833 // different pointer ids than we expected based on the previous ACTION_DOWN
3834 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3835 // in this way.
3836 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003837 "we expected there to be %d pointers. This probably means we received "
3838 "a broken sequence of pointer ids from the input device.",
3839 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003840 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003841 }
3842
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003843 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003844 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003845 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3846 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003847 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3848 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003849 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003850 uint32_t pointerId = uint32_t(pointerProperties.id);
3851 if (pointerIds.hasBit(pointerId)) {
3852 if (pointerIds.count() == 1) {
3853 // The first/last pointer went down/up.
3854 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003855 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003856 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3857 ? AMOTION_EVENT_ACTION_CANCEL
3858 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003859 } else {
3860 // A secondary pointer went down/up.
3861 uint32_t splitPointerIndex = 0;
3862 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3863 splitPointerIndex += 1;
3864 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003865 action = maskedAction |
3866 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867 }
3868 } else {
3869 // An unrelated pointer changed.
3870 action = AMOTION_EVENT_ACTION_MOVE;
3871 }
3872 }
3873
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003874 if (action == AMOTION_EVENT_ACTION_DOWN) {
3875 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3876 "Split motion event has mismatching downTime and eventTime for "
3877 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3878 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3879 }
3880
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003881 int32_t newId = mIdGenerator.nextId();
3882 if (ATRACE_ENABLED()) {
3883 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3884 ") to MotionEvent(id=0x%" PRIx32 ").",
3885 originalMotionEntry.id, newId);
3886 ATRACE_NAME(message.c_str());
3887 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003888 std::unique_ptr<MotionEntry> splitMotionEntry =
3889 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3890 originalMotionEntry.deviceId, originalMotionEntry.source,
3891 originalMotionEntry.displayId,
3892 originalMotionEntry.policyFlags, action,
3893 originalMotionEntry.actionButton,
3894 originalMotionEntry.flags, originalMotionEntry.metaState,
3895 originalMotionEntry.buttonState,
3896 originalMotionEntry.classification,
3897 originalMotionEntry.edgeFlags,
3898 originalMotionEntry.xPrecision,
3899 originalMotionEntry.yPrecision,
3900 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003901 originalMotionEntry.yCursorPosition, splitDownTime,
3902 splitPointerCount, splitPointerProperties,
3903 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003905 if (originalMotionEntry.injectionState) {
3906 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003907 splitMotionEntry->injectionState->refCount += 1;
3908 }
3909
3910 return splitMotionEntry;
3911}
3912
3913void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003914 if (DEBUG_INBOUND_EVENT_DETAILS) {
3915 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3916 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917
Antonio Kantekf16f2832021-09-28 04:39:20 +00003918 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003920 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003922 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3923 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3924 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925 } // release lock
3926
3927 if (needWake) {
3928 mLooper->wake();
3929 }
3930}
3931
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003932/**
3933 * If one of the meta shortcuts is detected, process them here:
3934 * Meta + Backspace -> generate BACK
3935 * Meta + Enter -> generate HOME
3936 * This will potentially overwrite keyCode and metaState.
3937 */
3938void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003939 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003940 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3941 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3942 if (keyCode == AKEYCODE_DEL) {
3943 newKeyCode = AKEYCODE_BACK;
3944 } else if (keyCode == AKEYCODE_ENTER) {
3945 newKeyCode = AKEYCODE_HOME;
3946 }
3947 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003948 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003949 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003950 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003951 keyCode = newKeyCode;
3952 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3953 }
3954 } else if (action == AKEY_EVENT_ACTION_UP) {
3955 // In order to maintain a consistent stream of up and down events, check to see if the key
3956 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3957 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003958 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003959 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003960 auto replacementIt = mReplacedKeys.find(replacement);
3961 if (replacementIt != mReplacedKeys.end()) {
3962 keyCode = replacementIt->second;
3963 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003964 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3965 }
3966 }
3967}
3968
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003970 if (DEBUG_INBOUND_EVENT_DETAILS) {
3971 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3972 "policyFlags=0x%x, action=0x%x, "
3973 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3974 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3975 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3976 args->downTime);
3977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978 if (!validateKeyEvent(args->action)) {
3979 return;
3980 }
3981
3982 uint32_t policyFlags = args->policyFlags;
3983 int32_t flags = args->flags;
3984 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003985 // InputDispatcher tracks and generates key repeats on behalf of
3986 // whatever notifies it, so repeatCount should always be set to 0
3987 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3989 policyFlags |= POLICY_FLAG_VIRTUAL;
3990 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3991 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992 if (policyFlags & POLICY_FLAG_FUNCTION) {
3993 metaState |= AMETA_FUNCTION_ON;
3994 }
3995
3996 policyFlags |= POLICY_FLAG_TRUSTED;
3997
Michael Wright78f24442014-08-06 15:55:28 -07003998 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003999 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004000
Michael Wrightd02c5b62014-02-10 15:10:22 -08004001 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004002 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08004003 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
4004 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005
Michael Wright2b3c3302018-03-02 17:19:13 +00004006 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004007 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004008 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4009 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004010 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012
Antonio Kantekf16f2832021-09-28 04:39:20 +00004013 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014 { // acquire lock
4015 mLock.lock();
4016
4017 if (shouldSendKeyToInputFilterLocked(args)) {
4018 mLock.unlock();
4019
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004020 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4022 return; // event was consumed by the filter
4023 }
4024
4025 mLock.lock();
4026 }
4027
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004028 std::unique_ptr<KeyEntry> newEntry =
4029 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4030 args->displayId, policyFlags, args->action, flags,
4031 keyCode, args->scanCode, metaState, repeatCount,
4032 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004034 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004035 mLock.unlock();
4036 } // release lock
4037
4038 if (needWake) {
4039 mLooper->wake();
4040 }
4041}
4042
4043bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4044 return mInputFilterEnabled;
4045}
4046
4047void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004048 if (DEBUG_INBOUND_EVENT_DETAILS) {
4049 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4050 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004051 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004052 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4053 "yCursorPosition=%f, downTime=%" PRId64,
4054 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004055 args->policyFlags, MotionEvent::actionToString(args->action).c_str(),
4056 args->actionButton, args->flags, args->metaState, args->buttonState, args->edgeFlags,
4057 args->xPrecision, args->yPrecision, args->xCursorPosition, args->yCursorPosition,
4058 args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004059 for (uint32_t i = 0; i < args->pointerCount; i++) {
4060 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4061 "x=%f, y=%f, pressure=%f, size=%f, "
4062 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4063 "orientation=%f",
4064 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4065 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4066 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4067 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4068 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4069 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4070 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4071 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4072 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4073 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4074 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -08004076 LOG_ALWAYS_FATAL_IF(!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4077 args->pointerProperties),
4078 "Invalid event: %s", args->dump().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079
4080 uint32_t policyFlags = args->policyFlags;
4081 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004082
4083 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004084 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004085 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4086 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004087 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004088 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089
Antonio Kantekf16f2832021-09-28 04:39:20 +00004090 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091 { // acquire lock
4092 mLock.lock();
4093
4094 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004095 ui::Transform displayTransform;
4096 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4097 displayTransform = it->second.transform;
4098 }
4099
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100 mLock.unlock();
4101
4102 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004103 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4104 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004105 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004106 displayTransform, args->xPrecision, args->yPrecision,
4107 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004108 args->downTime, args->eventTime, args->pointerCount,
4109 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110
4111 policyFlags |= POLICY_FLAG_FILTERED;
4112 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4113 return; // event was consumed by the filter
4114 }
4115
4116 mLock.lock();
4117 }
4118
4119 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004120 std::unique_ptr<MotionEntry> newEntry =
4121 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4122 args->source, args->displayId, policyFlags,
4123 args->action, args->actionButton, args->flags,
4124 args->metaState, args->buttonState,
4125 args->classification, args->edgeFlags,
4126 args->xPrecision, args->yPrecision,
4127 args->xCursorPosition, args->yCursorPosition,
4128 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004129 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004131 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4132 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4133 !mInputFilterEnabled) {
4134 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4135 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4136 }
4137
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004138 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139 mLock.unlock();
4140 } // release lock
4141
4142 if (needWake) {
4143 mLooper->wake();
4144 }
4145}
4146
Chris Yef59a2f42020-10-16 12:55:26 -07004147void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004148 if (DEBUG_INBOUND_EVENT_DETAILS) {
4149 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4150 " sensorType=%s",
4151 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004152 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004153 }
Chris Yef59a2f42020-10-16 12:55:26 -07004154
Antonio Kantekf16f2832021-09-28 04:39:20 +00004155 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004156 { // acquire lock
4157 mLock.lock();
4158
4159 // Just enqueue a new sensor event.
4160 std::unique_ptr<SensorEntry> newEntry =
4161 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4162 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4163 args->sensorType, args->accuracy,
4164 args->accuracyChanged, args->values);
4165
4166 needWake = enqueueInboundEventLocked(std::move(newEntry));
4167 mLock.unlock();
4168 } // release lock
4169
4170 if (needWake) {
4171 mLooper->wake();
4172 }
4173}
4174
Chris Yefb552902021-02-03 17:18:37 -08004175void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004176 if (DEBUG_INBOUND_EVENT_DETAILS) {
4177 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4178 args->deviceId, args->isOn);
4179 }
Chris Yefb552902021-02-03 17:18:37 -08004180 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4181}
4182
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004184 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185}
4186
4187void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004188 if (DEBUG_INBOUND_EVENT_DETAILS) {
4189 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4190 "switchMask=0x%08x",
4191 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4192 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193
4194 uint32_t policyFlags = args->policyFlags;
4195 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004196 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197}
4198
4199void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004200 if (DEBUG_INBOUND_EVENT_DETAILS) {
4201 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4202 args->deviceId);
4203 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204
Antonio Kantekf16f2832021-09-28 04:39:20 +00004205 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004207 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004209 std::unique_ptr<DeviceResetEntry> newEntry =
4210 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4211 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212 } // release lock
4213
4214 if (needWake) {
4215 mLooper->wake();
4216 }
4217}
4218
Prabir Pradhan7e186182020-11-10 13:56:45 -08004219void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004220 if (DEBUG_INBOUND_EVENT_DETAILS) {
4221 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004222 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004223 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004224
Antonio Kantekf16f2832021-09-28 04:39:20 +00004225 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004226 { // acquire lock
4227 std::scoped_lock _l(mLock);
4228 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004229 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004230 needWake = enqueueInboundEventLocked(std::move(entry));
4231 } // release lock
4232
4233 if (needWake) {
4234 mLooper->wake();
4235 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004236}
4237
Prabir Pradhan5735a322022-04-11 17:23:34 +00004238InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4239 std::optional<int32_t> targetUid,
4240 InputEventInjectionSync syncMode,
4241 std::chrono::milliseconds timeout,
4242 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004243 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004244 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4245 "policyFlags=0x%08x",
4246 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4247 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004248 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004249 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250
Prabir Pradhan5735a322022-04-11 17:23:34 +00004251 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004253 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004254 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4255 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4256 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4257 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4258 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004259 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004260 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004261 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004262 }
4263
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004264 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004266 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004267 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4268 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004269 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004270 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004271 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004273 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004274 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4275 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4276 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004277 int32_t keyCode = incomingKey.getKeyCode();
4278 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004279 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004280 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004281 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004282 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004283 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4284 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4285 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004287 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4288 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004289 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004290
4291 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4292 android::base::Timer t;
4293 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4294 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4295 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4296 std::to_string(t.duration().count()).c_str());
4297 }
4298 }
4299
4300 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004301 std::unique_ptr<KeyEntry> injectedEntry =
4302 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004303 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004304 incomingKey.getDisplayId(), policyFlags, action,
4305 flags, keyCode, incomingKey.getScanCode(), metaState,
4306 incomingKey.getRepeatCount(),
4307 incomingKey.getDownTime());
4308 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004309 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 }
4311
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004312 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004313 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004314 const int32_t action = motionEvent.getAction();
4315 const bool isPointerEvent =
4316 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4317 // If a pointer event has no displayId specified, inject it to the default display.
4318 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4319 ? ADISPLAY_ID_DEFAULT
4320 : event->getDisplayId();
4321 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004322 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004323 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004324 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004325 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004326 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004327 }
4328
4329 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004330 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004331 android::base::Timer t;
4332 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4333 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4334 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4335 std::to_string(t.duration().count()).c_str());
4336 }
4337 }
4338
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004339 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4340 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4341 }
4342
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004343 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004344 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4345 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004346 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004347 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4348 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004349 displayId, policyFlags, action, actionButton,
4350 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004351 motionEvent.getButtonState(),
4352 motionEvent.getClassification(),
4353 motionEvent.getEdgeFlags(),
4354 motionEvent.getXPrecision(),
4355 motionEvent.getYPrecision(),
4356 motionEvent.getRawXCursorPosition(),
4357 motionEvent.getRawYCursorPosition(),
4358 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004359 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004360 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004361 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004362 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004363 sampleEventTimes += 1;
4364 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004365 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004366 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4367 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004368 displayId, policyFlags, action, actionButton,
4369 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004370 motionEvent.getButtonState(),
4371 motionEvent.getClassification(),
4372 motionEvent.getEdgeFlags(),
4373 motionEvent.getXPrecision(),
4374 motionEvent.getYPrecision(),
4375 motionEvent.getRawXCursorPosition(),
4376 motionEvent.getRawYCursorPosition(),
4377 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004378 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004379 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004380 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4381 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004382 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004383 }
4384 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004387 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004388 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004389 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004390 }
4391
Prabir Pradhan5735a322022-04-11 17:23:34 +00004392 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004393 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004394 injectionState->injectionIsAsync = true;
4395 }
4396
4397 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004398 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399
4400 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004401 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004402 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004403 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404 }
4405
4406 mLock.unlock();
4407
4408 if (needWake) {
4409 mLooper->wake();
4410 }
4411
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004412 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004413 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004414 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004415
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004416 if (syncMode == InputEventInjectionSync::NONE) {
4417 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004418 } else {
4419 for (;;) {
4420 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004421 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004422 break;
4423 }
4424
4425 nsecs_t remainingTimeout = endTime - now();
4426 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004427 if (DEBUG_INJECTION) {
4428 ALOGD("injectInputEvent - Timed out waiting for injection result "
4429 "to become available.");
4430 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004431 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004432 break;
4433 }
4434
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004435 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004436 }
4437
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004438 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4439 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004440 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004441 if (DEBUG_INJECTION) {
4442 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4443 injectionState->pendingForegroundDispatches);
4444 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004445 nsecs_t remainingTimeout = endTime - now();
4446 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004447 if (DEBUG_INJECTION) {
4448 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4449 "dispatches to finish.");
4450 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004451 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004452 break;
4453 }
4454
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004455 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004456 }
4457 }
4458 }
4459
4460 injectionState->release();
4461 } // release lock
4462
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004463 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004464 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004465 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466
4467 return injectionResult;
4468}
4469
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004470std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004471 std::array<uint8_t, 32> calculatedHmac;
4472 std::unique_ptr<VerifiedInputEvent> result;
4473 switch (event.getType()) {
4474 case AINPUT_EVENT_TYPE_KEY: {
4475 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4476 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4477 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004478 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004479 break;
4480 }
4481 case AINPUT_EVENT_TYPE_MOTION: {
4482 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4483 VerifiedMotionEvent verifiedMotionEvent =
4484 verifiedMotionEventFromMotionEvent(motionEvent);
4485 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004486 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004487 break;
4488 }
4489 default: {
4490 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4491 return nullptr;
4492 }
4493 }
4494 if (calculatedHmac == INVALID_HMAC) {
4495 return nullptr;
4496 }
4497 if (calculatedHmac != event.getHmac()) {
4498 return nullptr;
4499 }
4500 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004501}
4502
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004503void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004504 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004505 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004506 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004507 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004508 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004511 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512 // Log the outcome since the injector did not wait for the injection result.
4513 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004514 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004515 ALOGV("Asynchronous input event injection succeeded.");
4516 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004517 case InputEventInjectionResult::TARGET_MISMATCH:
4518 ALOGV("Asynchronous input event injection target mismatch.");
4519 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004520 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004521 ALOGW("Asynchronous input event injection failed.");
4522 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004523 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004524 ALOGW("Asynchronous input event injection timed out.");
4525 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004526 case InputEventInjectionResult::PENDING:
4527 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4528 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004529 }
4530 }
4531
4532 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004533 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534 }
4535}
4536
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004537void InputDispatcher::transformMotionEntryForInjectionLocked(
4538 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004539 // Input injection works in the logical display coordinate space, but the input pipeline works
4540 // display space, so we need to transform the injected events accordingly.
4541 const auto it = mDisplayInfos.find(entry.displayId);
4542 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004543 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004544
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004545 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4546 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4547 const vec2 cursor =
4548 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4549 {entry.xCursorPosition, entry.yCursorPosition});
4550 entry.xCursorPosition = cursor.x;
4551 entry.yCursorPosition = cursor.y;
4552 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004553 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004554 entry.pointerCoords[i] =
4555 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4556 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004557 }
4558}
4559
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004560void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4561 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004562 if (injectionState) {
4563 injectionState->pendingForegroundDispatches += 1;
4564 }
4565}
4566
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004567void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4568 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004569 if (injectionState) {
4570 injectionState->pendingForegroundDispatches -= 1;
4571
4572 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004573 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004574 }
4575 }
4576}
4577
chaviw98318de2021-05-19 16:45:23 -05004578const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004579 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004580 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004581 auto it = mWindowHandlesByDisplay.find(displayId);
4582 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004583}
4584
chaviw98318de2021-05-19 16:45:23 -05004585sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004586 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004587 if (windowHandleToken == nullptr) {
4588 return nullptr;
4589 }
4590
Arthur Hungb92218b2018-08-14 12:00:21 +08004591 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004592 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4593 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004594 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004595 return windowHandle;
4596 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004597 }
4598 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004599 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004600}
4601
chaviw98318de2021-05-19 16:45:23 -05004602sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4603 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004604 if (windowHandleToken == nullptr) {
4605 return nullptr;
4606 }
4607
chaviw98318de2021-05-19 16:45:23 -05004608 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004609 if (windowHandle->getToken() == windowHandleToken) {
4610 return windowHandle;
4611 }
4612 }
4613 return nullptr;
4614}
4615
chaviw98318de2021-05-19 16:45:23 -05004616sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4617 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004618 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004619 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4620 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004621 if (handle->getId() == windowHandle->getId() &&
4622 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004623 if (windowHandle->getInfo()->displayId != it.first) {
4624 ALOGE("Found window %s in display %" PRId32
4625 ", but it should belong to display %" PRId32,
4626 windowHandle->getName().c_str(), it.first,
4627 windowHandle->getInfo()->displayId);
4628 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004629 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004630 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004631 }
4632 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004633 return nullptr;
4634}
4635
chaviw98318de2021-05-19 16:45:23 -05004636sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004637 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4638 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639}
4640
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004641bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4642 const MotionEntry& motionEntry) const {
4643 const WindowInfo& info = *window->getInfo();
4644
4645 // Skip spy window targets that are not valid for targeted injection.
4646 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004647 return false;
4648 }
4649
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004650 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4651 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4652 return false;
4653 }
4654
4655 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4656 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4657 window->getName().c_str());
4658 return false;
4659 }
4660
4661 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004662 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004663 ALOGW("Not sending touch to %s because there's no corresponding connection",
4664 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004665 return false;
4666 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004667
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004668 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004669 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004670 return false;
4671 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004672
4673 // Drop events that can't be trusted due to occlusion
4674 const auto [x, y] = resolveTouchedPosition(motionEntry);
4675 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4676 if (!isTouchTrustedLocked(occlusionInfo)) {
4677 if (DEBUG_TOUCH_OCCLUSION) {
4678 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4679 for (const auto& log : occlusionInfo.debugInfo) {
4680 ALOGD("%s", log.c_str());
4681 }
4682 }
4683 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4684 occlusionInfo.obscuringUid);
4685 return false;
4686 }
4687
4688 // Drop touch events if requested by input feature
4689 if (shouldDropInput(motionEntry, window)) {
4690 return false;
4691 }
4692
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004693 return true;
4694}
4695
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004696std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4697 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004698 auto connectionIt = mConnectionsByToken.find(token);
4699 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004700 return nullptr;
4701 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004702 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004703}
4704
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004705void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004706 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4707 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004708 // Remove all handles on a display if there are no windows left.
4709 mWindowHandlesByDisplay.erase(displayId);
4710 return;
4711 }
4712
4713 // Since we compare the pointer of input window handles across window updates, we need
4714 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004715 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4716 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4717 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004718 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004719 }
4720
chaviw98318de2021-05-19 16:45:23 -05004721 std::vector<sp<WindowInfoHandle>> newHandles;
4722 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004723 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004724 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004725 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004726 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004727 const bool canReceiveInput =
4728 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4729 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004730 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004731 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004732 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004733 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004734 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004735 }
4736
4737 if (info->displayId != displayId) {
4738 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4739 handle->getName().c_str(), displayId, info->displayId);
4740 continue;
4741 }
4742
Robert Carredd13602020-04-13 17:24:34 -07004743 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4744 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004745 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004746 oldHandle->updateFrom(handle);
4747 newHandles.push_back(oldHandle);
4748 } else {
4749 newHandles.push_back(handle);
4750 }
4751 }
4752
4753 // Insert or replace
4754 mWindowHandlesByDisplay[displayId] = newHandles;
4755}
4756
Arthur Hung72d8dc32020-03-28 00:48:39 +00004757void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004758 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004759 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004760 { // acquire lock
4761 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004762 for (const auto& [displayId, handles] : handlesPerDisplay) {
4763 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004764 }
4765 }
4766 // Wake up poll loop since it may need to make new input dispatching choices.
4767 mLooper->wake();
4768}
4769
Arthur Hungb92218b2018-08-14 12:00:21 +08004770/**
4771 * Called from InputManagerService, update window handle list by displayId that can receive input.
4772 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4773 * If set an empty list, remove all handles from the specific display.
4774 * For focused handle, check if need to change and send a cancel event to previous one.
4775 * For removed handle, check if need to send a cancel event if already in touch.
4776 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004777void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004778 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004779 if (DEBUG_FOCUS) {
4780 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004781 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004782 windowList += iwh->getName() + " ";
4783 }
4784 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4785 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004786
Prabir Pradhand65552b2021-10-07 11:23:50 -07004787 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004788 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004789 const WindowInfo& info = *window->getInfo();
4790
4791 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004792 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004793 if (noInputWindow && window->getToken() != nullptr) {
4794 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4795 window->getName().c_str());
4796 window->releaseChannel();
4797 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004798
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004799 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004800 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4801 !info.inputConfig.test(
4802 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004803 "%s has feature SPY, but is not a trusted overlay.",
4804 window->getName().c_str());
4805
Prabir Pradhand65552b2021-10-07 11:23:50 -07004806 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004807 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4808 !info.inputConfig.test(
4809 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004810 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4811 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004812 }
4813
Arthur Hung72d8dc32020-03-28 00:48:39 +00004814 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004815 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004816
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004817 // Save the old windows' orientation by ID before it gets updated.
4818 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004819 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004820 oldWindowOrientations.emplace(handle->getId(),
4821 handle->getInfo()->transform.getOrientation());
4822 }
4823
chaviw98318de2021-05-19 16:45:23 -05004824 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004825
chaviw98318de2021-05-19 16:45:23 -05004826 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Sam Dubey39d37cf2022-12-07 18:05:35 +00004827 if (mLastHoverWindowHandle) {
4828 const WindowInfo* lastHoverWindowInfo = mLastHoverWindowHandle->getInfo();
4829 if (lastHoverWindowInfo->displayId == displayId &&
4830 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4831 windowHandles.end()) {
4832 mLastHoverWindowHandle = nullptr;
4833 }
4834 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004835
Vishnu Nairc519ff72021-01-21 08:23:08 -08004836 std::optional<FocusResolver::FocusChanges> changes =
4837 mFocusResolver.setInputWindows(displayId, windowHandles);
4838 if (changes) {
4839 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004840 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004841
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004842 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4843 mTouchStatesByDisplay.find(displayId);
4844 if (stateIt != mTouchStatesByDisplay.end()) {
4845 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004846 for (size_t i = 0; i < state.windows.size();) {
4847 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004848 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004849 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004850 ALOGD("Touched window was removed: %s in display %" PRId32,
4851 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004852 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004853 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004854 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4855 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004856 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00004857 "touched window was removed");
4858 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004859 // Since we are about to drop the touch, cancel the events for the wallpaper as
4860 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004861 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004862 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4863 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004864 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004865 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004866 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004868 state.windows.erase(state.windows.begin() + i);
4869 } else {
4870 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871 }
4872 }
arthurhungb89ccb02020-12-30 16:19:01 +08004873
arthurhung6d4bed92021-03-17 11:59:33 +08004874 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004875 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004876 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004877 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004878 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004879 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4880 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004881 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004882 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004883 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004884
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004885 // Determine if the orientation of any of the input windows have changed, and cancel all
4886 // pointer events if necessary.
4887 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4888 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4889 if (newWindowHandle != nullptr &&
4890 newWindowHandle->getInfo()->transform.getOrientation() !=
4891 oldWindowOrientations[oldWindowHandle->getId()]) {
4892 std::shared_ptr<InputChannel> inputChannel =
4893 getInputChannelLocked(newWindowHandle->getToken());
4894 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004895 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004896 "touched window's orientation changed");
4897 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004898 }
4899 }
4900 }
4901
Arthur Hung72d8dc32020-03-28 00:48:39 +00004902 // Release information for windows that are no longer present.
4903 // This ensures that unused input channels are released promptly.
4904 // Otherwise, they might stick around until the window handle is destroyed
4905 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004906 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004907 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004908 if (DEBUG_FOCUS) {
4909 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004910 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004911 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004912 }
chaviw291d88a2019-02-14 10:33:58 -08004913 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004914}
4915
4916void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004917 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004918 if (DEBUG_FOCUS) {
4919 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4920 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4921 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004922 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004923 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004924 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004925 } // release lock
4926
4927 // Wake up poll loop since it may need to make new input dispatching choices.
4928 mLooper->wake();
4929}
4930
Vishnu Nair599f1412021-06-21 10:39:58 -07004931void InputDispatcher::setFocusedApplicationLocked(
4932 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4933 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4934 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4935
4936 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4937 return; // This application is already focused. No need to wake up or change anything.
4938 }
4939
4940 // Set the new application handle.
4941 if (inputApplicationHandle != nullptr) {
4942 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4943 } else {
4944 mFocusedApplicationHandlesByDisplay.erase(displayId);
4945 }
4946
4947 // No matter what the old focused application was, stop waiting on it because it is
4948 // no longer focused.
4949 resetNoFocusedWindowTimeoutLocked();
4950}
4951
Tiger Huang721e26f2018-07-24 22:26:19 +08004952/**
4953 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4954 * the display not specified.
4955 *
4956 * We track any unreleased events for each window. If a window loses the ability to receive the
4957 * released event, we will send a cancel event to it. So when the focused display is changed, we
4958 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4959 * display. The display-specified events won't be affected.
4960 */
4961void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004962 if (DEBUG_FOCUS) {
4963 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4964 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004965 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004966 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004967
4968 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004969 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004970 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004971 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004972 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004973 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004974 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004975 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00004976 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004977 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004978 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004979 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4980 }
4981 }
4982 mFocusedDisplayId = displayId;
4983
Chris Ye3c2d6f52020-08-09 10:39:48 -07004984 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004985 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004986 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004987
Vishnu Nairad321cd2020-08-20 16:40:21 -07004988 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004989 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004990 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004991 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004992 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004993 }
4994 }
4995 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004996 } // release lock
4997
4998 // Wake up poll loop since it may need to make new input dispatching choices.
4999 mLooper->wake();
5000}
5001
Michael Wrightd02c5b62014-02-10 15:10:22 -08005002void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005003 if (DEBUG_FOCUS) {
5004 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5005 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005006
5007 bool changed;
5008 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005009 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005010
5011 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5012 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005013 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005014 }
5015
5016 if (mDispatchEnabled && !enabled) {
5017 resetAndDropEverythingLocked("dispatcher is being disabled");
5018 }
5019
5020 mDispatchEnabled = enabled;
5021 mDispatchFrozen = frozen;
5022 changed = true;
5023 } else {
5024 changed = false;
5025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005026 } // release lock
5027
5028 if (changed) {
5029 // Wake up poll loop since it may need to make new input dispatching choices.
5030 mLooper->wake();
5031 }
5032}
5033
5034void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005035 if (DEBUG_FOCUS) {
5036 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5037 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005038
5039 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005040 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005041
5042 if (mInputFilterEnabled == enabled) {
5043 return;
5044 }
5045
5046 mInputFilterEnabled = enabled;
5047 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5048 } // release lock
5049
5050 // Wake up poll loop since there might be work to do to drop everything.
5051 mLooper->wake();
5052}
5053
Antonio Kanteka042c022022-07-06 16:51:07 -07005054bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5055 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005056 bool needWake = false;
5057 {
5058 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005059 ALOGD_IF(DEBUG_TOUCH_MODE,
5060 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5061 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5062 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5063 mTouchModePerDisplay.count(displayId) == 0
5064 ? "not set"
5065 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5066
Antonio Kantek15beb512022-06-13 22:35:41 +00005067 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5068 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005069 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005070 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005071 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005072 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5073 !recentWindowsAreOwnedByLocked(pid, uid)) {
5074 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5075 "window nor none of the previously interacted window",
5076 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005077 return false;
5078 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005079 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005080 mTouchModePerDisplay[displayId] = inTouchMode;
5081 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5082 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005083 needWake = enqueueInboundEventLocked(std::move(entry));
5084 } // release lock
5085
5086 if (needWake) {
5087 mLooper->wake();
5088 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005089 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005090}
5091
Antonio Kantek48710e42022-03-24 14:19:30 -07005092bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5093 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5094 if (focusedToken == nullptr) {
5095 return false;
5096 }
5097 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5098 return isWindowOwnedBy(windowHandle, pid, uid);
5099}
5100
5101bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5102 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5103 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5104 const sp<WindowInfoHandle> windowHandle =
5105 getWindowHandleLocked(connectionToken);
5106 return isWindowOwnedBy(windowHandle, pid, uid);
5107 }) != mInteractionConnectionTokens.end();
5108}
5109
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005110void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5111 if (opacity < 0 || opacity > 1) {
5112 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5113 return;
5114 }
5115
5116 std::scoped_lock lock(mLock);
5117 mMaximumObscuringOpacityForTouch = opacity;
5118}
5119
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005120std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5121InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005122 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5123 for (TouchedWindow& w : state.windows) {
5124 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005125 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005126 }
5127 }
5128 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005129 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005130}
5131
arthurhungb89ccb02020-12-30 16:19:01 +08005132bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5133 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005134 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005135 if (DEBUG_FOCUS) {
5136 ALOGD("Trivial transfer to same window.");
5137 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005138 return true;
5139 }
5140
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005142 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005143
Arthur Hungabbb9d82021-09-01 14:52:30 +00005144 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005145 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005146 if (state == nullptr || touchedWindow == nullptr) {
5147 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005148 return false;
5149 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005150
Arthur Hungabbb9d82021-09-01 14:52:30 +00005151 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5152 if (toWindowHandle == nullptr) {
5153 ALOGW("Cannot transfer focus because to window not found.");
5154 return false;
5155 }
5156
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005157 if (DEBUG_FOCUS) {
5158 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005159 touchedWindow->windowHandle->getName().c_str(),
5160 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005161 }
5162
Arthur Hungabbb9d82021-09-01 14:52:30 +00005163 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005164 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005165 BitSet32 pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005166 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005167 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005168
Arthur Hungabbb9d82021-09-01 14:52:30 +00005169 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005170 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005171 ftl::Flags<InputTarget::Flags> newTargetFlags =
5172 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005173 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005174 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005175 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005176 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005177
Arthur Hungabbb9d82021-09-01 14:52:30 +00005178 // Store the dragging window.
5179 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005180 if (pointerIds.count() != 1) {
5181 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5182 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005183 return false;
5184 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005185 // Track the pointer id for drag window and generate the drag state.
5186 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005187 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005188 }
5189
Arthur Hungabbb9d82021-09-01 14:52:30 +00005190 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005191 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5192 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005193 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005194 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005195 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005196 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005197 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005198 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005199 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5200 newTargetFlags);
5201
5202 // Check if the wallpaper window should deliver the corresponding event.
5203 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5204 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005205 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005206 } // release lock
5207
5208 // Wake up poll loop since it may need to make new input dispatching choices.
5209 mLooper->wake();
5210 return true;
5211}
5212
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005213/**
5214 * Get the touched foreground window on the given display.
5215 * Return null if there are no windows touched on that display, or if more than one foreground
5216 * window is being touched.
5217 */
5218sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5219 auto stateIt = mTouchStatesByDisplay.find(displayId);
5220 if (stateIt == mTouchStatesByDisplay.end()) {
5221 ALOGI("No touch state on display %" PRId32, displayId);
5222 return nullptr;
5223 }
5224
5225 const TouchState& state = stateIt->second;
5226 sp<WindowInfoHandle> touchedForegroundWindow;
5227 // If multiple foreground windows are touched, return nullptr
5228 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005229 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005230 if (touchedForegroundWindow != nullptr) {
5231 ALOGI("Two or more foreground windows: %s and %s",
5232 touchedForegroundWindow->getName().c_str(),
5233 window.windowHandle->getName().c_str());
5234 return nullptr;
5235 }
5236 touchedForegroundWindow = window.windowHandle;
5237 }
5238 }
5239 return touchedForegroundWindow;
5240}
5241
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005242// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005243bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005244 sp<IBinder> fromToken;
5245 { // acquire lock
5246 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005247 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005248 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005249 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5250 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005251 return false;
5252 }
5253
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005254 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5255 if (from == nullptr) {
5256 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5257 return false;
5258 }
5259
5260 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005261 } // release lock
5262
5263 return transferTouchFocus(fromToken, destChannelToken);
5264}
5265
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005267 if (DEBUG_FOCUS) {
5268 ALOGD("Resetting and dropping all events (%s).", reason);
5269 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005270
Michael Wrightfb04fd52022-11-24 22:31:11 +00005271 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272 synthesizeCancelationEventsForAllConnectionsLocked(options);
5273
5274 resetKeyRepeatLocked();
5275 releasePendingEventLocked();
5276 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005277 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005278
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005279 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005280 mTouchStatesByDisplay.clear();
Sam Dubey39d37cf2022-12-07 18:05:35 +00005281 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005282 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005283}
5284
5285void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005286 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005287 dumpDispatchStateLocked(dump);
5288
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005289 std::istringstream stream(dump);
5290 std::string line;
5291
5292 while (std::getline(stream, line, '\n')) {
5293 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005294 }
5295}
5296
Prabir Pradhan99987712020-11-10 18:43:05 -08005297std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5298 std::string dump;
5299
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005300 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5301 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005302
5303 std::string windowName = "None";
5304 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005305 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005306 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5307 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5308 : "token has capture without window";
5309 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005310 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005311
5312 return dump;
5313}
5314
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005315void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005316 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5317 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5318 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005319 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005320
Tiger Huang721e26f2018-07-24 22:26:19 +08005321 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5322 dump += StringPrintf(INDENT "FocusedApplications:\n");
5323 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5324 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005325 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005326 const std::chrono::duration timeout =
5327 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005328 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005329 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005330 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005331 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005332 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005333 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005334 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005335
Vishnu Nairc519ff72021-01-21 08:23:08 -08005336 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005337 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005338
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005339 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005340 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005341 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005342 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5343 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005344 }
5345 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005346 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005347 }
5348
arthurhung6d4bed92021-03-17 11:59:33 +08005349 if (mDragState) {
5350 dump += StringPrintf(INDENT "DragState:\n");
5351 mDragState->dump(dump, INDENT2);
5352 }
5353
Arthur Hungb92218b2018-08-14 12:00:21 +08005354 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005355 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5356 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5357 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5358 const auto& displayInfo = it->second;
5359 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5360 displayInfo.logicalHeight);
5361 displayInfo.transform.dump(dump, "transform", INDENT4);
5362 } else {
5363 dump += INDENT2 "No DisplayInfo found!\n";
5364 }
5365
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005366 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005367 dump += INDENT2 "Windows:\n";
5368 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005369 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5370 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005371
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005372 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005373 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005374 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005375 "applicationInfo.name=%s, "
5376 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005377 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005378 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005379 windowInfo->displayId,
5380 windowInfo->inputConfig.string().c_str(),
5381 windowInfo->alpha, windowInfo->frameLeft,
5382 windowInfo->frameTop, windowInfo->frameRight,
5383 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005384 windowInfo->applicationInfo.name.c_str(),
5385 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005386 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005387 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005388 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005389 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005390 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005391 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005392 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005393 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005394 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005395 }
5396 } else {
5397 dump += INDENT2 "Windows: <none>\n";
5398 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005399 }
5400 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005401 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005402 }
5403
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005404 if (!mGlobalMonitorsByDisplay.empty()) {
5405 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5406 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005407 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005408 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005409 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005410 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005411 }
5412
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005413 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005414
5415 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005416 if (!mRecentQueue.empty()) {
5417 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005418 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005419 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005420 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005421 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005422 }
5423 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005424 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005425 }
5426
5427 // Dump event currently being dispatched.
5428 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005429 dump += INDENT "PendingEvent:\n";
5430 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005431 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005432 dump += StringPrintf(", age=%" PRId64 "ms\n",
5433 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005434 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005435 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005436 }
5437
5438 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005439 if (!mInboundQueue.empty()) {
5440 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005441 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005442 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005443 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005444 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005445 }
5446 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005447 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005448 }
5449
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005450 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005451 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005452 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005453 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005454 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005455 }
5456 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005457 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005458 }
5459
Prabir Pradhancef936d2021-07-21 16:17:52 +00005460 if (!mCommandQueue.empty()) {
5461 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5462 } else {
5463 dump += INDENT "CommandQueue: <empty>\n";
5464 }
5465
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005466 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005467 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005468 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005469 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005470 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005471 connection->inputChannel->getFd().get(),
5472 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005473 connection->getWindowName().c_str(),
5474 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005475 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005476
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005477 if (!connection->outboundQueue.empty()) {
5478 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5479 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005480 dump += dumpQueue(connection->outboundQueue, currentTime);
5481
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005483 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005484 }
5485
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005486 if (!connection->waitQueue.empty()) {
5487 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5488 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005489 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005491 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005492 }
5493 }
5494 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005495 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005496 }
5497
5498 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005499 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5500 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005501 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005502 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005503 }
5504
Antonio Kantek15beb512022-06-13 22:35:41 +00005505 if (!mTouchModePerDisplay.empty()) {
5506 dump += INDENT "TouchModePerDisplay:\n";
5507 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5508 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5509 std::to_string(touchMode).c_str());
5510 }
5511 } else {
5512 dump += INDENT "TouchModePerDisplay: <none>\n";
5513 }
5514
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005515 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005516 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5517 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5518 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005519 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005520 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005521}
5522
Michael Wright3dd60e22019-03-27 22:06:44 +00005523void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5524 const size_t numMonitors = monitors.size();
5525 for (size_t i = 0; i < numMonitors; i++) {
5526 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005527 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005528 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5529 dump += "\n";
5530 }
5531}
5532
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005533class LooperEventCallback : public LooperCallback {
5534public:
5535 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5536 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5537
5538private:
5539 std::function<int(int events)> mCallback;
5540};
5541
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005542Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005543 if (DEBUG_CHANNEL_CREATION) {
5544 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5545 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005546
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005547 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005548 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005549 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005550
5551 if (result) {
5552 return base::Error(result) << "Failed to open input channel pair with name " << name;
5553 }
5554
Michael Wrightd02c5b62014-02-10 15:10:22 -08005555 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005556 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005557 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005558 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005559 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005560 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005561
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005562 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5563 ALOGE("Created a new connection, but the token %p is already known", token.get());
5564 }
5565 mConnectionsByToken.emplace(token, connection);
5566
5567 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5568 this, std::placeholders::_1, token);
5569
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005570 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5571 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005572 } // release lock
5573
5574 // Wake the looper because some connections have changed.
5575 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005576 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005577}
5578
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005579Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005580 const std::string& name,
5581 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005582 std::shared_ptr<InputChannel> serverChannel;
5583 std::unique_ptr<InputChannel> clientChannel;
5584 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5585 if (result) {
5586 return base::Error(result) << "Failed to open input channel pair with name " << name;
5587 }
5588
Michael Wright3dd60e22019-03-27 22:06:44 +00005589 { // acquire lock
5590 std::scoped_lock _l(mLock);
5591
5592 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005593 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5594 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005595 }
5596
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005597 sp<Connection> connection =
5598 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005599 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005600 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005601
5602 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 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5607 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005608
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005609 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005610
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005611 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5612 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005613 }
Garfield Tan15601662020-09-22 15:32:38 -07005614
Michael Wright3dd60e22019-03-27 22:06:44 +00005615 // Wake the looper because some connections have changed.
5616 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005617 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005618}
5619
Garfield Tan15601662020-09-22 15:32:38 -07005620status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005621 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005622 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005623
Garfield Tan15601662020-09-22 15:32:38 -07005624 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005625 if (status) {
5626 return status;
5627 }
5628 } // release lock
5629
5630 // Wake the poll loop because removing the connection may have changed the current
5631 // synchronization state.
5632 mLooper->wake();
5633 return OK;
5634}
5635
Garfield Tan15601662020-09-22 15:32:38 -07005636status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5637 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005638 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005639 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005640 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005641 return BAD_VALUE;
5642 }
5643
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005644 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005645
Michael Wrightd02c5b62014-02-10 15:10:22 -08005646 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005647 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005648 }
5649
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005650 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005651
5652 nsecs_t currentTime = now();
5653 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5654
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005655 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005656 return OK;
5657}
5658
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005659void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005660 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5661 auto& [displayId, monitors] = *it;
5662 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5663 return monitor.inputChannel->getConnectionToken() == connectionToken;
5664 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005665
Michael Wright3dd60e22019-03-27 22:06:44 +00005666 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005667 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005668 } else {
5669 ++it;
5670 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005671 }
5672}
5673
Michael Wright3dd60e22019-03-27 22:06:44 +00005674status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005675 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005676 return pilferPointersLocked(token);
5677}
Michael Wright3dd60e22019-03-27 22:06:44 +00005678
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005679status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005680 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5681 if (!requestingChannel) {
5682 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5683 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005684 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005685
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005686 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07005687 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.isEmpty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005688 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5689 " Ignoring.");
5690 return BAD_VALUE;
5691 }
5692
5693 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005694 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005695 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005696 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005697 "input channel stole pointer stream");
5698 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005699 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005700 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005701 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005702 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005703 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005704 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005705 if (channel != nullptr && channel->getConnectionToken() != token) {
5706 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5707 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5708 canceledWindows += channel->getName();
5709 }
5710 }
5711 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5712 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5713 canceledWindows.c_str());
5714
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005715 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005716 // This only blocks relevant pointers to be sent to other windows
5717 window.isPilferingPointers = true;
5718
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005719 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005720 return OK;
5721}
5722
Prabir Pradhan99987712020-11-10 18:43:05 -08005723void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5724 { // acquire lock
5725 std::scoped_lock _l(mLock);
5726 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005727 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005728 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5729 windowHandle != nullptr ? windowHandle->getName().c_str()
5730 : "token without window");
5731 }
5732
Vishnu Nairc519ff72021-01-21 08:23:08 -08005733 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005734 if (focusedToken != windowToken) {
5735 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5736 enabled ? "enable" : "disable");
5737 return;
5738 }
5739
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005740 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005741 ALOGW("Ignoring request to %s Pointer Capture: "
5742 "window has %s requested pointer capture.",
5743 enabled ? "enable" : "disable", enabled ? "already" : "not");
5744 return;
5745 }
5746
Christine Franksb768bb42021-11-29 12:11:31 -08005747 if (enabled) {
5748 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5749 mIneligibleDisplaysForPointerCapture.end(),
5750 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5751 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5752 return;
5753 }
5754 }
5755
Prabir Pradhan99987712020-11-10 18:43:05 -08005756 setPointerCaptureLocked(enabled);
5757 } // release lock
5758
5759 // Wake the thread to process command entries.
5760 mLooper->wake();
5761}
5762
Christine Franksb768bb42021-11-29 12:11:31 -08005763void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5764 { // acquire lock
5765 std::scoped_lock _l(mLock);
5766 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5767 if (!isEligible) {
5768 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5769 }
5770 } // release lock
5771}
5772
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005773std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5774 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005775 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005776 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005777 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005778 }
5779 }
5780 }
5781 return std::nullopt;
5782}
5783
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005784sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005785 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005786 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005787 }
5788
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005789 for (const auto& [token, connection] : mConnectionsByToken) {
5790 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005791 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005792 }
5793 }
Robert Carr4e670e52018-08-15 13:26:12 -07005794
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005795 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005796}
5797
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005798std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5799 sp<Connection> connection = getConnectionLocked(connectionToken);
5800 if (connection == nullptr) {
5801 return "<nullptr>";
5802 }
5803 return connection->getInputChannelName();
5804}
5805
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005806void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005807 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005808 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005809}
5810
Prabir Pradhancef936d2021-07-21 16:17:52 +00005811void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5812 const sp<Connection>& connection, uint32_t seq,
5813 bool handled, nsecs_t consumeTime) {
5814 // Handle post-event policy actions.
5815 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5816 if (dispatchEntryIt == connection->waitQueue.end()) {
5817 return;
5818 }
5819 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5820 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5821 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5822 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5823 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5824 }
5825 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5826 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5827 connection->inputChannel->getConnectionToken(),
5828 dispatchEntry->deliveryTime, consumeTime, finishTime);
5829 }
5830
5831 bool restartEvent;
5832 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5833 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5834 restartEvent =
5835 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5836 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5837 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5838 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5839 handled);
5840 } else {
5841 restartEvent = false;
5842 }
5843
5844 // Dequeue the event and start the next cycle.
5845 // Because the lock might have been released, it is possible that the
5846 // contents of the wait queue to have been drained, so we need to double-check
5847 // a few things.
5848 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5849 if (dispatchEntryIt != connection->waitQueue.end()) {
5850 dispatchEntry = *dispatchEntryIt;
5851 connection->waitQueue.erase(dispatchEntryIt);
5852 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5853 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5854 if (!connection->responsive) {
5855 connection->responsive = isConnectionResponsive(*connection);
5856 if (connection->responsive) {
5857 // The connection was unresponsive, and now it's responsive.
5858 processConnectionResponsiveLocked(*connection);
5859 }
5860 }
5861 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005862 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005863 connection->outboundQueue.push_front(dispatchEntry);
5864 traceOutboundQueueLength(*connection);
5865 } else {
5866 releaseDispatchEntry(dispatchEntry);
5867 }
5868 }
5869
5870 // Start the next dispatch cycle for this connection.
5871 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005872}
5873
Prabir Pradhancef936d2021-07-21 16:17:52 +00005874void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5875 const sp<IBinder>& newToken) {
5876 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5877 scoped_unlock unlock(mLock);
5878 mPolicy->notifyFocusChanged(oldToken, newToken);
5879 };
5880 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005881}
5882
Prabir Pradhancef936d2021-07-21 16:17:52 +00005883void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5884 auto command = [this, token, x, y]() REQUIRES(mLock) {
5885 scoped_unlock unlock(mLock);
5886 mPolicy->notifyDropWindow(token, x, y);
5887 };
5888 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005889}
5890
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005891void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5892 if (connection == nullptr) {
5893 LOG_ALWAYS_FATAL("Caller must check for nullness");
5894 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005895 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5896 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005897 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005898 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005899 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005900 return;
5901 }
5902 /**
5903 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5904 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5905 * has changed. This could cause newer entries to time out before the already dispatched
5906 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5907 * processes the events linearly. So providing information about the oldest entry seems to be
5908 * most useful.
5909 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005910 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005911 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5912 std::string reason =
5913 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005914 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005915 ns2ms(currentWait),
5916 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005917 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005918 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005919
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005920 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5921
5922 // Stop waking up for events on this connection, it is already unresponsive
5923 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005924}
5925
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005926void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5927 std::string reason =
5928 StringPrintf("%s does not have a focused window", application->getName().c_str());
5929 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005930
Prabir Pradhancef936d2021-07-21 16:17:52 +00005931 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5932 scoped_unlock unlock(mLock);
5933 mPolicy->notifyNoFocusedWindowAnr(application);
5934 };
5935 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005936}
5937
chaviw98318de2021-05-19 16:45:23 -05005938void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005939 const std::string& reason) {
5940 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5941 updateLastAnrStateLocked(windowLabel, reason);
5942}
5943
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005944void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5945 const std::string& reason) {
5946 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005947 updateLastAnrStateLocked(windowLabel, reason);
5948}
5949
5950void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5951 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005952 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005953 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005954 struct tm tm;
5955 localtime_r(&t, &tm);
5956 char timestr[64];
5957 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005958 mLastAnrState.clear();
5959 mLastAnrState += INDENT "ANR:\n";
5960 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005961 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5962 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005963 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005964}
5965
Prabir Pradhancef936d2021-07-21 16:17:52 +00005966void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5967 KeyEntry& entry) {
5968 const KeyEvent event = createKeyEvent(entry);
5969 nsecs_t delay = 0;
5970 { // release lock
5971 scoped_unlock unlock(mLock);
5972 android::base::Timer t;
5973 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5974 entry.policyFlags);
5975 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5976 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5977 std::to_string(t.duration().count()).c_str());
5978 }
5979 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005980
5981 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00005982 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005983 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00005984 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005985 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00005986 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005987 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005989}
5990
Prabir Pradhancef936d2021-07-21 16:17:52 +00005991void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005992 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005993 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005994 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005995 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005996 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005997 };
5998 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005999}
6000
Prabir Pradhanedd96402022-02-15 01:46:16 -08006001void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6002 std::optional<int32_t> pid) {
6003 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006004 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006005 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006006 };
6007 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006008}
6009
6010/**
6011 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6012 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6013 * command entry to the command queue.
6014 */
6015void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6016 std::string reason) {
6017 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006018 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006019 if (connection.monitor) {
6020 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6021 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006022 pid = findMonitorPidByTokenLocked(connectionToken);
6023 } else {
6024 // The connection is a window
6025 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6026 reason.c_str());
6027 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6028 if (handle != nullptr) {
6029 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006030 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006031 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006032 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006033}
6034
6035/**
6036 * Tell the policy that a connection has become responsive so that it can stop ANR.
6037 */
6038void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6039 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006040 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006041 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006042 pid = findMonitorPidByTokenLocked(connectionToken);
6043 } else {
6044 // The connection is a window
6045 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6046 if (handle != nullptr) {
6047 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006048 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006049 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006050 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006051}
6052
Prabir Pradhancef936d2021-07-21 16:17:52 +00006053bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006054 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006055 KeyEntry& keyEntry, bool handled) {
6056 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006057 if (!handled) {
6058 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006059 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006060 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006061 return false;
6062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006063
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006064 // Get the fallback key state.
6065 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006066 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006067 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006068 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006069 connection->inputState.removeFallbackKey(originalKeyCode);
6070 }
6071
6072 if (handled || !dispatchEntry->hasForegroundTarget()) {
6073 // If the application handles the original key for which we previously
6074 // generated a fallback or if the window is not a foreground window,
6075 // then cancel the associated fallback key, if any.
6076 if (fallbackKeyCode != -1) {
6077 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006078 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6079 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6080 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6081 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6082 keyEntry.policyFlags);
6083 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006084 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006085 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006086
6087 mLock.unlock();
6088
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006089 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006090 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006091
6092 mLock.lock();
6093
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006094 // Cancel the fallback key.
6095 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006096 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006097 "application handled the original non-fallback key "
6098 "or is no longer a foreground target, "
6099 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006100 options.keyCode = fallbackKeyCode;
6101 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006102 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006103 connection->inputState.removeFallbackKey(originalKeyCode);
6104 }
6105 } else {
6106 // If the application did not handle a non-fallback key, first check
6107 // that we are in a good state to perform unhandled key event processing
6108 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006109 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006110 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006111 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6112 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6113 "since this is not an initial down. "
6114 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6115 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6116 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006117 return false;
6118 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006119
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006120 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006121 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6122 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6123 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6124 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6125 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006126 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006127
6128 mLock.unlock();
6129
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006130 bool fallback =
6131 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006132 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006133
6134 mLock.lock();
6135
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006136 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006137 connection->inputState.removeFallbackKey(originalKeyCode);
6138 return false;
6139 }
6140
6141 // Latch the fallback keycode for this key on an initial down.
6142 // The fallback keycode cannot change at any other point in the lifecycle.
6143 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006144 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006145 fallbackKeyCode = event.getKeyCode();
6146 } else {
6147 fallbackKeyCode = AKEYCODE_UNKNOWN;
6148 }
6149 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6150 }
6151
6152 ALOG_ASSERT(fallbackKeyCode != -1);
6153
6154 // Cancel the fallback key if the policy decides not to send it anymore.
6155 // We will continue to dispatch the key to the policy but we will no
6156 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006157 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6158 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006159 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6160 if (fallback) {
6161 ALOGD("Unhandled key event: Policy requested to send key %d"
6162 "as a fallback for %d, but on the DOWN it had requested "
6163 "to send %d instead. Fallback canceled.",
6164 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6165 } else {
6166 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6167 "but on the DOWN it had requested to send %d. "
6168 "Fallback canceled.",
6169 originalKeyCode, fallbackKeyCode);
6170 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006171 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006172
Michael Wrightfb04fd52022-11-24 22:31:11 +00006173 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006174 "canceling fallback, policy no longer desires it");
6175 options.keyCode = fallbackKeyCode;
6176 synthesizeCancelationEventsForConnectionLocked(connection, options);
6177
6178 fallback = false;
6179 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006180 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006181 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006182 }
6183 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006184
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006185 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6186 {
6187 std::string msg;
6188 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6189 connection->inputState.getFallbackKeys();
6190 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6191 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6192 }
6193 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6194 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006195 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006196 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006197
6198 if (fallback) {
6199 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006200 keyEntry.eventTime = event.getEventTime();
6201 keyEntry.deviceId = event.getDeviceId();
6202 keyEntry.source = event.getSource();
6203 keyEntry.displayId = event.getDisplayId();
6204 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6205 keyEntry.keyCode = fallbackKeyCode;
6206 keyEntry.scanCode = event.getScanCode();
6207 keyEntry.metaState = event.getMetaState();
6208 keyEntry.repeatCount = event.getRepeatCount();
6209 keyEntry.downTime = event.getDownTime();
6210 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006211
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006212 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6213 ALOGD("Unhandled key event: Dispatching fallback key. "
6214 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6215 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6216 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006217 return true; // restart the event
6218 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006219 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6220 ALOGD("Unhandled key event: No fallback key.");
6221 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006222
6223 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006224 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006225 }
6226 }
6227 return false;
6228}
6229
Prabir Pradhancef936d2021-07-21 16:17:52 +00006230bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006231 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006232 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006233 return false;
6234}
6235
Michael Wrightd02c5b62014-02-10 15:10:22 -08006236void InputDispatcher::traceInboundQueueLengthLocked() {
6237 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006238 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006239 }
6240}
6241
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006242void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006243 if (ATRACE_ENABLED()) {
6244 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006245 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6246 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006247 }
6248}
6249
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006250void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006251 if (ATRACE_ENABLED()) {
6252 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006253 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6254 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006255 }
6256}
6257
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006258void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006259 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006260
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006261 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006262 dumpDispatchStateLocked(dump);
6263
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006264 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006265 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006266 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006267 }
6268}
6269
6270void InputDispatcher::monitor() {
6271 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006272 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006273 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006274 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006275}
6276
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006277/**
6278 * Wake up the dispatcher and wait until it processes all events and commands.
6279 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6280 * this method can be safely called from any thread, as long as you've ensured that
6281 * the work you are interested in completing has already been queued.
6282 */
6283bool InputDispatcher::waitForIdle() {
6284 /**
6285 * Timeout should represent the longest possible time that a device might spend processing
6286 * events and commands.
6287 */
6288 constexpr std::chrono::duration TIMEOUT = 100ms;
6289 std::unique_lock lock(mLock);
6290 mLooper->wake();
6291 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6292 return result == std::cv_status::no_timeout;
6293}
6294
Vishnu Naire798b472020-07-23 13:52:21 -07006295/**
6296 * Sets focus to the window identified by the token. This must be called
6297 * after updating any input window handles.
6298 *
6299 * Params:
6300 * request.token - input channel token used to identify the window that should gain focus.
6301 * request.focusedToken - the token that the caller expects currently to be focused. If the
6302 * specified token does not match the currently focused window, this request will be dropped.
6303 * If the specified focused token matches the currently focused window, the call will succeed.
6304 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6305 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6306 * when requesting the focus change. This determines which request gets
6307 * precedence if there is a focus change request from another source such as pointer down.
6308 */
Vishnu Nair958da932020-08-21 17:12:37 -07006309void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6310 { // acquire lock
6311 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006312 std::optional<FocusResolver::FocusChanges> changes =
6313 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6314 if (changes) {
6315 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006316 }
6317 } // release lock
6318 // Wake up poll loop since it may need to make new input dispatching choices.
6319 mLooper->wake();
6320}
6321
Vishnu Nairc519ff72021-01-21 08:23:08 -08006322void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6323 if (changes.oldFocus) {
6324 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006325 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006326 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006327 "focus left window");
6328 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006329 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006330 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006331 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006332 if (changes.newFocus) {
6333 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006334 }
6335
Prabir Pradhan99987712020-11-10 18:43:05 -08006336 // If a window has pointer capture, then it must have focus. We need to ensure that this
6337 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6338 // If the window loses focus before it loses pointer capture, then the window can be in a state
6339 // where it has pointer capture but not focus, violating the contract. Therefore we must
6340 // dispatch the pointer capture event before the focus event. Since focus events are added to
6341 // the front of the queue (above), we add the pointer capture event to the front of the queue
6342 // after the focus events are added. This ensures the pointer capture event ends up at the
6343 // front.
6344 disablePointerCaptureForcedLocked();
6345
Vishnu Nairc519ff72021-01-21 08:23:08 -08006346 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006347 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006348 }
6349}
Vishnu Nair958da932020-08-21 17:12:37 -07006350
Prabir Pradhan99987712020-11-10 18:43:05 -08006351void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006352 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006353 return;
6354 }
6355
6356 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6357
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006358 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006359 setPointerCaptureLocked(false);
6360 }
6361
6362 if (!mWindowTokenWithPointerCapture) {
6363 // No need to send capture changes because no window has capture.
6364 return;
6365 }
6366
6367 if (mPendingEvent != nullptr) {
6368 // Move the pending event to the front of the queue. This will give the chance
6369 // for the pending event to be dropped if it is a captured event.
6370 mInboundQueue.push_front(mPendingEvent);
6371 mPendingEvent = nullptr;
6372 }
6373
6374 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006375 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006376 mInboundQueue.push_front(std::move(entry));
6377}
6378
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006379void InputDispatcher::setPointerCaptureLocked(bool enable) {
6380 mCurrentPointerCaptureRequest.enable = enable;
6381 mCurrentPointerCaptureRequest.seq++;
6382 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006383 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006384 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006385 };
6386 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006387}
6388
Vishnu Nair599f1412021-06-21 10:39:58 -07006389void InputDispatcher::displayRemoved(int32_t displayId) {
6390 { // acquire lock
6391 std::scoped_lock _l(mLock);
6392 // Set an empty list to remove all handles from the specific display.
6393 setInputWindowsLocked(/* window handles */ {}, displayId);
6394 setFocusedApplicationLocked(displayId, nullptr);
6395 // Call focus resolver to clean up stale requests. This must be called after input windows
6396 // have been removed for the removed display.
6397 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006398 // Reset pointer capture eligibility, regardless of previous state.
6399 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006400 // Remove the associated touch mode state.
6401 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006402 } // release lock
6403
6404 // Wake up poll loop since it may need to make new input dispatching choices.
6405 mLooper->wake();
6406}
6407
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006408void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6409 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006410 // The listener sends the windows as a flattened array. Separate the windows by display for
6411 // more convenient parsing.
6412 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006413 for (const auto& info : windowInfos) {
6414 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006415 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006416 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006417
6418 { // acquire lock
6419 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006420
6421 // Ensure that we have an entry created for all existing displays so that if a displayId has
6422 // no windows, we can tell that the windows were removed from the display.
6423 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6424 handlesPerDisplay[displayId];
6425 }
6426
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006427 mDisplayInfos.clear();
6428 for (const auto& displayInfo : displayInfos) {
6429 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6430 }
6431
6432 for (const auto& [displayId, handles] : handlesPerDisplay) {
6433 setInputWindowsLocked(handles, displayId);
6434 }
6435 }
6436 // Wake up poll loop since it may need to make new input dispatching choices.
6437 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006438}
6439
Vishnu Nair062a8672021-09-03 16:07:44 -07006440bool InputDispatcher::shouldDropInput(
6441 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006442 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6443 (windowHandle->getInfo()->inputConfig.test(
6444 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006445 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006446 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6447 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006448 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006449 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006450 windowHandle->getInfo()->displayId);
6451 return true;
6452 }
6453 return false;
6454}
6455
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006456void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6457 const std::vector<gui::WindowInfo>& windowInfos,
6458 const std::vector<DisplayInfo>& displayInfos) {
6459 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6460}
6461
Arthur Hungdfd528e2021-12-08 13:23:04 +00006462void InputDispatcher::cancelCurrentTouch() {
6463 {
6464 std::scoped_lock _l(mLock);
6465 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006466 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006467 "cancel current touch");
6468 synthesizeCancelationEventsForAllConnectionsLocked(options);
6469
6470 mTouchStatesByDisplay.clear();
Sam Dubey39d37cf2022-12-07 18:05:35 +00006471 mLastHoverWindowHandle.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006472 }
6473 // Wake up poll loop since there might be work to do.
6474 mLooper->wake();
6475}
6476
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006477void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6478 std::scoped_lock _l(mLock);
6479 mMonitorDispatchingTimeout = timeout;
6480}
6481
Arthur Hungc539dbb2022-12-08 07:45:36 +00006482void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6483 const sp<WindowInfoHandle>& oldWindowHandle,
6484 const sp<WindowInfoHandle>& newWindowHandle,
6485 TouchState& state, const BitSet32& pointerIds) {
6486 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6487 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6488 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6489 newWindowHandle->getInfo()->inputConfig.test(
6490 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6491 const sp<WindowInfoHandle> oldWallpaper =
6492 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6493 const sp<WindowInfoHandle> newWallpaper =
6494 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6495 if (oldWallpaper == newWallpaper) {
6496 return;
6497 }
6498
6499 if (oldWallpaper != nullptr) {
6500 state.addOrUpdateWindow(oldWallpaper, InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6501 BitSet32(0));
6502 }
6503
6504 if (newWallpaper != nullptr) {
6505 state.addOrUpdateWindow(newWallpaper,
6506 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6507 InputTarget::Flags::WINDOW_IS_OBSCURED |
6508 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6509 pointerIds);
6510 }
6511}
6512
6513void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6514 ftl::Flags<InputTarget::Flags> newTargetFlags,
6515 const sp<WindowInfoHandle> fromWindowHandle,
6516 const sp<WindowInfoHandle> toWindowHandle,
6517 TouchState& state, const BitSet32& pointerIds) {
6518 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6519 fromWindowHandle->getInfo()->inputConfig.test(
6520 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6521 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6522 toWindowHandle->getInfo()->inputConfig.test(
6523 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6524
6525 const sp<WindowInfoHandle> oldWallpaper =
6526 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6527 const sp<WindowInfoHandle> newWallpaper =
6528 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6529 if (oldWallpaper == newWallpaper) {
6530 return;
6531 }
6532
6533 if (oldWallpaper != nullptr) {
6534 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6535 "transferring touch focus to another window");
6536 state.removeWindowByToken(oldWallpaper->getToken());
6537 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6538 }
6539
6540 if (newWallpaper != nullptr) {
6541 nsecs_t downTimeInTarget = now();
6542 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6543 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6544 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6545 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6546 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
6547 sp<Connection> wallpaperConnection = getConnectionLocked(newWallpaper->getToken());
6548 if (wallpaperConnection != nullptr) {
6549 sp<Connection> toConnection = getConnectionLocked(toWindowHandle->getToken());
6550 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6551 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6552 wallpaperFlags);
6553 }
6554 }
6555}
6556
6557sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6558 const sp<WindowInfoHandle>& windowHandle) const {
6559 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6560 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6561 bool foundWindow = false;
6562 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6563 if (!foundWindow && otherHandle != windowHandle) {
6564 continue;
6565 }
6566 if (windowHandle == otherHandle) {
6567 foundWindow = true;
6568 continue;
6569 }
6570
6571 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6572 return otherHandle;
6573 }
6574 }
6575 return nullptr;
6576}
6577
Garfield Tane84e6f92019-08-29 17:28:41 -07006578} // namespace android::inputdispatcher