blob: a793f57ade5a09d360bab20e2fa7e81982c9642a [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>
chaviw15fab6f2021-06-07 14:15:52 -050028#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080029#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070030#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010031#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070032#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
Michael Wright44753b12020-07-08 13:48:11 +010034#include <cerrno>
35#include <cinttypes>
36#include <climits>
37#include <cstddef>
38#include <ctime>
39#include <queue>
40#include <sstream>
41
42#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000043#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070044#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010045
Michael Wrightd02c5b62014-02-10 15:10:22 -080046#define INDENT " "
47#define INDENT2 " "
48#define INDENT3 " "
49#define INDENT4 " "
50
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080051using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000052using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080053using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070054using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050055using android::gui::FocusRequest;
56using android::gui::TouchOcclusionMode;
57using android::gui::WindowInfo;
58using android::gui::WindowInfoHandle;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100059using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080060using android::os::InputEventInjectionResult;
61using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080062
Garfield Tane84e6f92019-08-29 17:28:41 -070063namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080064
Prabir Pradhancef936d2021-07-21 16:17:52 +000065namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000066// Temporarily releases a held mutex for the lifetime of the instance.
67// Named to match std::scoped_lock
68class scoped_unlock {
69public:
70 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
71 ~scoped_unlock() { mMutex.lock(); }
72
73private:
74 std::mutex& mMutex;
75};
76
Michael Wrightd02c5b62014-02-10 15:10:22 -080077// Default input dispatching timeout if there is no focused application or paused window
78// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080079const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
80 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
81 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080082
83// Amount of time to allow for all pending events to be processed when an app switch
84// key is on the way. This is used to preempt input dispatch and drop input events
85// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000086constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080087
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080088const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
Michael Wrightd02c5b62014-02-10 15:10:22 -080090// 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 +000091constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
92
93// Log a warning when an interception call takes longer than this to process.
94constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080095
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -070096// Additional key latency in case a connection is still processing some motion events.
97// This will help with the case when a user touched a button that opens a new window,
98// and gives us the chance to dispatch the key to this new window.
99constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
100
Michael Wrightd02c5b62014-02-10 15:10:22 -0800101// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000102constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
103
Antonio Kantekea47acb2021-12-23 12:41:25 -0800104// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000105constexpr int LOGTAG_INPUT_INTERACTION = 62000;
106constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000107constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000108
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000109inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800110 return systemTime(SYSTEM_TIME_MONOTONIC);
111}
112
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000113inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800114 return value ? "true" : "false";
115}
116
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000117inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000118 if (binder == nullptr) {
119 return "<null>";
120 }
121 return StringPrintf("%p", binder.get());
122}
123
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000124inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700125 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
126 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800127}
128
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000129bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800130 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700131 case AKEY_EVENT_ACTION_DOWN:
132 case AKEY_EVENT_ACTION_UP:
133 return true;
134 default:
135 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800136 }
137}
138
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000139bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700140 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800141 ALOGE("Key event has invalid action code 0x%x", action);
142 return false;
143 }
144 return true;
145}
146
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000147bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800148 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700149 case AMOTION_EVENT_ACTION_DOWN:
150 case AMOTION_EVENT_ACTION_UP:
151 case AMOTION_EVENT_ACTION_CANCEL:
152 case AMOTION_EVENT_ACTION_MOVE:
153 case AMOTION_EVENT_ACTION_OUTSIDE:
154 case AMOTION_EVENT_ACTION_HOVER_ENTER:
155 case AMOTION_EVENT_ACTION_HOVER_MOVE:
156 case AMOTION_EVENT_ACTION_HOVER_EXIT:
157 case AMOTION_EVENT_ACTION_SCROLL:
158 return true;
159 case AMOTION_EVENT_ACTION_POINTER_DOWN:
160 case AMOTION_EVENT_ACTION_POINTER_UP: {
161 int32_t index = getMotionEventActionPointerIndex(action);
162 return index >= 0 && index < pointerCount;
163 }
164 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
165 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
166 return actionButton != 0;
167 default:
168 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800169 }
170}
171
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000172int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500173 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
174}
175
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000176bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
177 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700178 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800179 ALOGE("Motion event has invalid action code 0x%x", action);
180 return false;
181 }
182 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800183 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %zu.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700184 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 return false;
186 }
187 BitSet32 pointerIdBits;
188 for (size_t i = 0; i < pointerCount; i++) {
189 int32_t id = pointerProperties[i].id;
190 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700191 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
192 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800193 return false;
194 }
195 if (pointerIdBits.hasBit(id)) {
196 ALOGE("Motion event has duplicate pointer id %d", id);
197 return false;
198 }
199 pointerIdBits.markBit(id);
200 }
201 return true;
202}
203
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000204std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800205 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000206 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800207 }
208
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000209 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800210 bool first = true;
211 Region::const_iterator cur = region.begin();
212 Region::const_iterator const tail = region.end();
213 while (cur != tail) {
214 if (first) {
215 first = false;
216 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800217 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800219 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 cur++;
221 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000222 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223}
224
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000225std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500226 constexpr size_t maxEntries = 50; // max events to print
227 constexpr size_t skipBegin = maxEntries / 2;
228 const size_t skipEnd = queue.size() - maxEntries / 2;
229 // skip from maxEntries / 2 ... size() - maxEntries/2
230 // only print from 0 .. skipBegin and then from skipEnd .. size()
231
232 std::string dump;
233 for (size_t i = 0; i < queue.size(); i++) {
234 const DispatchEntry& entry = *queue[i];
235 if (i >= skipBegin && i < skipEnd) {
236 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
237 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
238 continue;
239 }
240 dump.append(INDENT4);
241 dump += entry.eventEntry->getDescription();
242 dump += StringPrintf(", seq=%" PRIu32
243 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
244 entry.seq, entry.targetFlags, entry.resolvedAction,
245 ns2ms(currentTime - entry.eventEntry->eventTime));
246 if (entry.deliveryTime != 0) {
247 // This entry was delivered, so add information on how long we've been waiting
248 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
249 }
250 dump.append("\n");
251 }
252 return dump;
253}
254
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700255/**
256 * Find the entry in std::unordered_map by key, and return it.
257 * If the entry is not found, return a default constructed entry.
258 *
259 * Useful when the entries are vectors, since an empty vector will be returned
260 * if the entry is not found.
261 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
262 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700263template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000264V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700265 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700266 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800267}
268
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000269bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700270 if (first == second) {
271 return true;
272 }
273
274 if (first == nullptr || second == nullptr) {
275 return false;
276 }
277
278 return first->getToken() == second->getToken();
279}
280
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000281bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000282 if (first == nullptr || second == nullptr) {
283 return false;
284 }
285 return first->applicationInfo.token != nullptr &&
286 first->applicationInfo.token == second->applicationInfo.token;
287}
288
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000289std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
290 std::shared_ptr<EventEntry> eventEntry,
291 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700292 if (inputTarget.useDefaultPointerTransform()) {
293 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700294 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700295 inputTarget.displayTransform,
296 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000297 }
298
299 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
300 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
301
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700302 std::vector<PointerCoords> pointerCoords;
303 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000304
305 // Use the first pointer information to normalize all other pointers. This could be any pointer
306 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700307 // uses the transform for the normalized pointer.
308 const ui::Transform& firstPointerTransform =
309 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
310 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000311
312 // Iterate through all pointers in the event to normalize against the first.
313 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
314 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
315 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700316 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000317
318 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700319 // First, apply the current pointer's transform to update the coordinates into
320 // window space.
321 pointerCoords[pointerIndex].transform(currTransform);
322 // Next, apply the inverse transform of the normalized coordinates so the
323 // current coordinates are transformed into the normalized coordinate space.
324 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000325 }
326
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700327 std::unique_ptr<MotionEntry> combinedMotionEntry =
328 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
329 motionEntry.deviceId, motionEntry.source,
330 motionEntry.displayId, motionEntry.policyFlags,
331 motionEntry.action, motionEntry.actionButton,
332 motionEntry.flags, motionEntry.metaState,
333 motionEntry.buttonState, motionEntry.classification,
334 motionEntry.edgeFlags, motionEntry.xPrecision,
335 motionEntry.yPrecision, motionEntry.xCursorPosition,
336 motionEntry.yCursorPosition, motionEntry.downTime,
337 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000338 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000339
340 if (motionEntry.injectionState) {
341 combinedMotionEntry->injectionState = motionEntry.injectionState;
342 combinedMotionEntry->injectionState->refCount += 1;
343 }
344
345 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700346 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700347 firstPointerTransform, inputTarget.displayTransform,
348 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000349 return dispatchEntry;
350}
351
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000352status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
353 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700354 std::unique_ptr<InputChannel> uniqueServerChannel;
355 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
356
357 serverChannel = std::move(uniqueServerChannel);
358 return result;
359}
360
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500361template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000362bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500363 if (lhs == nullptr && rhs == nullptr) {
364 return true;
365 }
366 if (lhs == nullptr || rhs == nullptr) {
367 return false;
368 }
369 return *lhs == *rhs;
370}
371
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000372KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000373 KeyEvent event;
374 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
375 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
376 entry.repeatCount, entry.downTime, entry.eventTime);
377 return event;
378}
379
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000380bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000381 // Do not keep track of gesture monitors. They receive every event and would disproportionately
382 // affect the statistics.
383 if (connection.monitor) {
384 return false;
385 }
386 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
387 if (!connection.responsive) {
388 return false;
389 }
390 return true;
391}
392
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000393bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000394 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
395 const int32_t& inputEventId = eventEntry.id;
396 if (inputEventId != dispatchEntry.resolvedEventId) {
397 // Event was transmuted
398 return false;
399 }
400 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
401 return false;
402 }
403 // Only track latency for events that originated from hardware
404 if (eventEntry.isSynthesized()) {
405 return false;
406 }
407 const EventEntry::Type& inputEventEntryType = eventEntry.type;
408 if (inputEventEntryType == EventEntry::Type::KEY) {
409 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
410 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
411 return false;
412 }
413 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
414 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
415 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
416 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
417 return false;
418 }
419 } else {
420 // Not a key or a motion
421 return false;
422 }
423 if (!shouldReportMetricsForConnection(connection)) {
424 return false;
425 }
426 return true;
427}
428
Prabir Pradhancef936d2021-07-21 16:17:52 +0000429/**
430 * Connection is responsive if it has no events in the waitQueue that are older than the
431 * current time.
432 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000433bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000434 const nsecs_t currentTime = now();
435 for (const DispatchEntry* entry : connection.waitQueue) {
436 if (entry->timeoutTime < currentTime) {
437 return false;
438 }
439 }
440 return true;
441}
442
Antonio Kantekf16f2832021-09-28 04:39:20 +0000443// Returns true if the event type passed as argument represents a user activity.
444bool isUserActivityEvent(const EventEntry& eventEntry) {
445 switch (eventEntry.type) {
446 case EventEntry::Type::FOCUS:
447 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
448 case EventEntry::Type::DRAG:
449 case EventEntry::Type::TOUCH_MODE_CHANGED:
450 case EventEntry::Type::SENSOR:
451 case EventEntry::Type::CONFIGURATION_CHANGED:
452 return false;
453 case EventEntry::Type::DEVICE_RESET:
454 case EventEntry::Type::KEY:
455 case EventEntry::Type::MOTION:
456 return true;
457 }
458}
459
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800460// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhand65552b2021-10-07 11:23:50 -0700461bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, int32_t x, int32_t y,
462 bool isStylus) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800463 const auto inputConfig = windowInfo.inputConfig;
464 if (windowInfo.displayId != displayId ||
465 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800466 return false;
467 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700468 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800469 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800470 return false;
471 }
Prabir Pradhan06349042022-02-04 09:19:17 -0800472 if (!windowInfo.touchableRegionContainsPoint(x, y)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800473 return false;
474 }
475 return true;
476}
477
Prabir Pradhand65552b2021-10-07 11:23:50 -0700478bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
479 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
480 (entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
481 entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_ERASER);
482}
483
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000484// Determines if the given window can be targeted as InputTarget::FLAG_FOREGROUND.
485// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
486// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
487// be sent to such a window, but it is not a foreground event and doesn't use
488// InputTarget::FLAG_FOREGROUND.
489bool canReceiveForegroundTouches(const WindowInfo& info) {
490 // A non-touchable window can still receive touch events (e.g. in the case of
491 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
492 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
493}
494
Antonio Kantek48710e42022-03-24 14:19:30 -0700495bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
496 if (windowHandle == nullptr) {
497 return false;
498 }
499 const WindowInfo* windowInfo = windowHandle->getInfo();
500 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
501 return true;
502 }
503 return false;
504}
505
Prabir Pradhan5735a322022-04-11 17:23:34 +0000506// Checks targeted injection using the window's owner's uid.
507// Returns an empty string if an entry can be sent to the given window, or an error message if the
508// entry is a targeted injection whose uid target doesn't match the window owner.
509std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
510 const EventEntry& entry) {
511 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
512 // The event was not injected, or the injected event does not target a window.
513 return {};
514 }
515 const int32_t uid = *entry.injectionState->targetUid;
516 if (window == nullptr) {
517 return StringPrintf("No valid window target for injection into uid %d.", uid);
518 }
519 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
520 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
521 "owned by uid %d.",
522 uid, window->getName().c_str(), window->getInfo()->ownerUid);
523 }
524 return {};
525}
526
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700527Point resolveTouchedPosition(const MotionEntry& entry) {
528 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
529 // Always dispatch mouse events to cursor position.
530 if (isFromMouse) {
531 return Point(static_cast<int32_t>(entry.xCursorPosition),
532 static_cast<int32_t>(entry.yCursorPosition));
533 }
534
535 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
536 return Point(static_cast<int32_t>(
537 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X)),
538 static_cast<int32_t>(
539 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)));
540}
541
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000542} // namespace
543
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544// --- InputDispatcher ---
545
Garfield Tan00f511d2019-06-12 16:55:40 -0700546InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800547 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
548
549InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
550 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700551 : mPolicy(policy),
552 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700553 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800554 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700555 mAppSwitchSawKeyDown(false),
556 mAppSwitchDueTime(LONG_LONG_MAX),
557 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800558 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700559 mDispatchEnabled(false),
560 mDispatchFrozen(false),
561 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100562 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000563 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800564 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800565 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000566 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000567 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700568 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800569 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800570
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700571 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700572 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
573
Yi Kong9b14ac62018-07-17 13:48:38 -0700574 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800575 policy->getDispatcherConfiguration(&mConfig);
576}
577
578InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000579 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800580
Prabir Pradhancef936d2021-07-21 16:17:52 +0000581 resetKeyRepeatLocked();
582 releasePendingEventLocked();
583 drainInboundQueueLocked();
584 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800585
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000586 while (!mConnectionsByToken.empty()) {
587 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000588 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
589 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800590 }
591}
592
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700593status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700594 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700595 return ALREADY_EXISTS;
596 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700597 mThread = std::make_unique<InputThread>(
598 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
599 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700600}
601
602status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700603 if (mThread && mThread->isCallingThread()) {
604 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700605 return INVALID_OPERATION;
606 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700607 mThread.reset();
608 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700609}
610
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611void InputDispatcher::dispatchOnce() {
612 nsecs_t nextWakeupTime = LONG_LONG_MAX;
613 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800614 std::scoped_lock _l(mLock);
615 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800616
617 // Run a dispatch loop if there are no pending commands.
618 // The dispatch loop might enqueue commands to run afterwards.
619 if (!haveCommandsLocked()) {
620 dispatchOnceInnerLocked(&nextWakeupTime);
621 }
622
623 // Run all pending commands if there are any.
624 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000625 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 nextWakeupTime = LONG_LONG_MIN;
627 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800628
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700629 // If we are still waiting for ack on some events,
630 // we might have to wake up earlier to check if an app is anr'ing.
631 const nsecs_t nextAnrCheck = processAnrsLocked();
632 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
633
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800634 // We are about to enter an infinitely long sleep, because we have no commands or
635 // pending or queued events
636 if (nextWakeupTime == LONG_LONG_MAX) {
637 mDispatcherEnteredIdle.notify_all();
638 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800639 } // release lock
640
641 // Wait for callback or timeout or wake. (make sure we round up, not down)
642 nsecs_t currentTime = now();
643 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
644 mLooper->pollOnce(timeoutMillis);
645}
646
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700647/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500648 * Raise ANR if there is no focused window.
649 * Before the ANR is raised, do a final state check:
650 * 1. The currently focused application must be the same one we are waiting for.
651 * 2. Ensure we still don't have a focused window.
652 */
653void InputDispatcher::processNoFocusedWindowAnrLocked() {
654 // Check if the application that we are waiting for is still focused.
655 std::shared_ptr<InputApplicationHandle> focusedApplication =
656 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
657 if (focusedApplication == nullptr ||
658 focusedApplication->getApplicationToken() !=
659 mAwaitedFocusedApplication->getApplicationToken()) {
660 // Unexpected because we should have reset the ANR timer when focused application changed
661 ALOGE("Waited for a focused window, but focused application has already changed to %s",
662 focusedApplication->getName().c_str());
663 return; // The focused application has changed.
664 }
665
chaviw98318de2021-05-19 16:45:23 -0500666 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500667 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
668 if (focusedWindowHandle != nullptr) {
669 return; // We now have a focused window. No need for ANR.
670 }
671 onAnrLocked(mAwaitedFocusedApplication);
672}
673
674/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700675 * Check if any of the connections' wait queues have events that are too old.
676 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
677 * Return the time at which we should wake up next.
678 */
679nsecs_t InputDispatcher::processAnrsLocked() {
680 const nsecs_t currentTime = now();
681 nsecs_t nextAnrCheck = LONG_LONG_MAX;
682 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
683 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
684 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500685 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700686 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500687 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700688 return LONG_LONG_MIN;
689 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500690 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700691 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
692 }
693 }
694
695 // Check if any connection ANRs are due
696 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
697 if (currentTime < nextAnrCheck) { // most likely scenario
698 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
699 }
700
701 // If we reached here, we have an unresponsive connection.
702 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
703 if (connection == nullptr) {
704 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
705 return nextAnrCheck;
706 }
707 connection->responsive = false;
708 // Stop waking up for this unresponsive connection
709 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000710 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700711 return LONG_LONG_MIN;
712}
713
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800714std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
715 const sp<Connection>& connection) {
716 if (connection->monitor) {
717 return mMonitorDispatchingTimeout;
718 }
719 const sp<WindowInfoHandle> window =
720 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700721 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500722 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700723 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500724 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700725}
726
Michael Wrightd02c5b62014-02-10 15:10:22 -0800727void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
728 nsecs_t currentTime = now();
729
Jeff Browndc5992e2014-04-11 01:27:26 -0700730 // Reset the key repeat timer whenever normal dispatch is suspended while the
731 // device is in a non-interactive state. This is to ensure that we abort a key
732 // repeat if the device is just coming out of sleep.
733 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800734 resetKeyRepeatLocked();
735 }
736
737 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
738 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100739 if (DEBUG_FOCUS) {
740 ALOGD("Dispatch frozen. Waiting some more.");
741 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742 return;
743 }
744
745 // Optimize latency of app switches.
746 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
747 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
748 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
749 if (mAppSwitchDueTime < *nextWakeupTime) {
750 *nextWakeupTime = mAppSwitchDueTime;
751 }
752
753 // Ready to start a new event.
754 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700755 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700756 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800757 if (isAppSwitchDue) {
758 // The inbound queue is empty so the app switch key we were waiting
759 // for will never arrive. Stop waiting for it.
760 resetPendingAppSwitchLocked(false);
761 isAppSwitchDue = false;
762 }
763
764 // Synthesize a key repeat if appropriate.
765 if (mKeyRepeatState.lastKeyEntry) {
766 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
767 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
768 } else {
769 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
770 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
771 }
772 }
773 }
774
775 // Nothing to do if there is no pending event.
776 if (!mPendingEvent) {
777 return;
778 }
779 } else {
780 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700781 mPendingEvent = mInboundQueue.front();
782 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800783 traceInboundQueueLengthLocked();
784 }
785
786 // Poke user activity for this event.
787 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700788 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800789 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790 }
791
792 // Now we have an event to dispatch.
793 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700794 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800795 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700796 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800797 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700798 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700800 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801 }
802
803 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700804 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805 }
806
807 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700808 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700809 const ConfigurationChangedEntry& typedEntry =
810 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700811 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700812 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700813 break;
814 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800815
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700816 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700817 const DeviceResetEntry& typedEntry =
818 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700819 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700820 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700821 break;
822 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100824 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700825 std::shared_ptr<FocusEntry> typedEntry =
826 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100827 dispatchFocusLocked(currentTime, typedEntry);
828 done = true;
829 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
830 break;
831 }
832
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700833 case EventEntry::Type::TOUCH_MODE_CHANGED: {
834 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
835 dispatchTouchModeChangeLocked(currentTime, typedEntry);
836 done = true;
837 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
838 break;
839 }
840
Prabir Pradhan99987712020-11-10 18:43:05 -0800841 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
842 const auto typedEntry =
843 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
844 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
845 done = true;
846 break;
847 }
848
arthurhungb89ccb02020-12-30 16:19:01 +0800849 case EventEntry::Type::DRAG: {
850 std::shared_ptr<DragEntry> typedEntry =
851 std::static_pointer_cast<DragEntry>(mPendingEvent);
852 dispatchDragLocked(currentTime, typedEntry);
853 done = true;
854 break;
855 }
856
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700857 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700858 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700859 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700860 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700861 resetPendingAppSwitchLocked(true);
862 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700863 } else if (dropReason == DropReason::NOT_DROPPED) {
864 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700865 }
866 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700867 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700868 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700869 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700870 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
871 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700872 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700873 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700874 break;
875 }
876
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700877 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700878 std::shared_ptr<MotionEntry> motionEntry =
879 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700880 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
881 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700883 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
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 = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700890 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891 }
Chris Yef59a2f42020-10-16 12:55:26 -0700892
893 case EventEntry::Type::SENSOR: {
894 std::shared_ptr<SensorEntry> sensorEntry =
895 std::static_pointer_cast<SensorEntry>(mPendingEvent);
896 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
897 dropReason = DropReason::APP_SWITCH;
898 }
899 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
900 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
901 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
902 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
903 dropReason = DropReason::STALE;
904 }
905 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
906 done = true;
907 break;
908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909 }
910
911 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700912 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700913 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914 }
Michael Wright3a981722015-06-10 15:26:13 +0100915 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800916
917 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700918 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800919 }
920}
921
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800922bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
923 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
924}
925
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700926/**
927 * Return true if the events preceding this incoming motion event should be dropped
928 * Return false otherwise (the default behaviour)
929 */
930bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700931 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700932 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700933
934 // Optimize case where the current application is unresponsive and the user
935 // decides to touch a window in a different application.
936 // If the application takes too long to catch up then we drop all events preceding
937 // the touch into the other window.
938 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -0700939 const int32_t displayId = motionEntry.displayId;
940 const auto [x, y] = resolveTouchedPosition(motionEntry);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700941 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -0700942
chaviw98318de2021-05-19 16:45:23 -0500943 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700944 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700945 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700946 touchedWindowHandle->getApplicationToken() !=
947 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700948 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700949 ALOGI("Pruning input queue because user touched a different application while waiting "
950 "for %s",
951 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700952 return true;
953 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700954
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800955 // Alternatively, maybe there's a spy window that could handle this event.
956 const std::vector<sp<WindowInfoHandle>> touchedSpies =
957 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
958 for (const auto& windowHandle : touchedSpies) {
959 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000960 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800961 // This spy window could take more input. Drop all events preceding this
962 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700963 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800964 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700965 mAwaitedFocusedApplication->getName().c_str());
966 return true;
967 }
968 }
969 }
970
971 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
972 // yet been processed by some connections, the dispatcher will wait for these motion
973 // events to be processed before dispatching the key event. This is because these motion events
974 // may cause a new window to be launched, which the user might expect to receive focus.
975 // To prevent waiting forever for such events, just send the key to the currently focused window
976 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
977 ALOGD("Received a new pointer down event, stop waiting for events to process and "
978 "just send the pending key event to the focused window.");
979 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700980 }
981 return false;
982}
983
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700984bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700985 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700986 mInboundQueue.push_back(std::move(newEntry));
987 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988 traceInboundQueueLengthLocked();
989
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700990 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700991 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +0000992 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
993 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700994 // Optimize app switch latency.
995 // If the application takes too long to catch up then we drop all events preceding
996 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700997 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700998 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700999 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001000 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001001 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001002 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001003 if (DEBUG_APP_SWITCH) {
1004 ALOGD("App switch is pending!");
1005 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001006 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001007 mAppSwitchSawKeyDown = false;
1008 needWake = true;
1009 }
1010 }
1011 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001012
1013 // If a new up event comes in, and the pending event with same key code has been asked
1014 // to try again later because of the policy. We have to reset the intercept key wake up
1015 // time for it may have been handled in the policy and could be dropped.
1016 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1017 mPendingEvent->type == EventEntry::Type::KEY) {
1018 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1019 if (pendingKey.keyCode == keyEntry.keyCode &&
1020 pendingKey.interceptKeyResult ==
1021 KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1022 pendingKey.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1023 pendingKey.interceptKeyWakeupTime = 0;
1024 needWake = true;
1025 }
1026 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001027 break;
1028 }
1029
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001030 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001031 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1032 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001033 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1034 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001035 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001037 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001039 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001040 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1041 break;
1042 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001043 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001044 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001045 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001046 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001047 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1048 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001049 // nothing to do
1050 break;
1051 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001052 }
1053
1054 return needWake;
1055}
1056
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001057void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001058 // Do not store sensor event in recent queue to avoid flooding the queue.
1059 if (entry->type != EventEntry::Type::SENSOR) {
1060 mRecentQueue.push_back(entry);
1061 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001062 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001063 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 }
1065}
1066
chaviw98318de2021-05-19 16:45:23 -05001067sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1068 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001069 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001070 bool addOutsideTargets,
1071 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001072 if (addOutsideTargets && touchState == nullptr) {
1073 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001074 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001076 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001077 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001078 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001079 continue;
1080 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001081
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001082 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001083 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001084 return windowHandle;
1085 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001086
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001087 if (addOutsideTargets &&
1088 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001089 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1090 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091 }
1092 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001093 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094}
1095
Prabir Pradhand65552b2021-10-07 11:23:50 -07001096std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1097 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001098 // Traverse windows from front to back and gather the touched spy windows.
1099 std::vector<sp<WindowInfoHandle>> spyWindows;
1100 const auto& windowHandles = getWindowHandlesLocked(displayId);
1101 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1102 const WindowInfo& info = *windowHandle->getInfo();
1103
Prabir Pradhand65552b2021-10-07 11:23:50 -07001104 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001105 continue;
1106 }
1107 if (!info.isSpy()) {
1108 // The first touched non-spy window was found, so return the spy windows touched so far.
1109 return spyWindows;
1110 }
1111 spyWindows.push_back(windowHandle);
1112 }
1113 return spyWindows;
1114}
1115
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001116void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117 const char* reason;
1118 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001119 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001120 if (DEBUG_INBOUND_EVENT_DETAILS) {
1121 ALOGD("Dropped event because policy consumed it.");
1122 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001123 reason = "inbound event was dropped because the policy consumed it";
1124 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001125 case DropReason::DISABLED:
1126 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001127 ALOGI("Dropped event because input dispatch is disabled.");
1128 }
1129 reason = "inbound event was dropped because input dispatch is disabled";
1130 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001131 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001132 ALOGI("Dropped event because of pending overdue app switch.");
1133 reason = "inbound event was dropped because of pending overdue app switch";
1134 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001135 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001136 ALOGI("Dropped event because the current application is not responding and the user "
1137 "has started interacting with a different application.");
1138 reason = "inbound event was dropped because the current application is not responding "
1139 "and the user has started interacting with a different application";
1140 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001141 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001142 ALOGI("Dropped event because it is stale.");
1143 reason = "inbound event was dropped because it is stale";
1144 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001145 case DropReason::NO_POINTER_CAPTURE:
1146 ALOGI("Dropped event because there is no window with Pointer Capture.");
1147 reason = "inbound event was dropped because there is no window with Pointer Capture";
1148 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001149 case DropReason::NOT_DROPPED: {
1150 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001151 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001152 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153 }
1154
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001155 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001156 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001157 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1158 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001159 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001161 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001162 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1163 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001164 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1165 synthesizeCancelationEventsForAllConnectionsLocked(options);
1166 } else {
1167 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1168 synthesizeCancelationEventsForAllConnectionsLocked(options);
1169 }
1170 break;
1171 }
Chris Yef59a2f42020-10-16 12:55:26 -07001172 case EventEntry::Type::SENSOR: {
1173 break;
1174 }
arthurhungb89ccb02020-12-30 16:19:01 +08001175 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1176 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001177 break;
1178 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001179 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001180 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001181 case EventEntry::Type::CONFIGURATION_CHANGED:
1182 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001183 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001184 break;
1185 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186 }
1187}
1188
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001189static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001190 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1191 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192}
1193
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001194bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1195 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1196 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1197 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198}
1199
1200bool InputDispatcher::isAppSwitchPendingLocked() {
1201 return mAppSwitchDueTime != LONG_LONG_MAX;
1202}
1203
1204void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1205 mAppSwitchDueTime = LONG_LONG_MAX;
1206
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001207 if (DEBUG_APP_SWITCH) {
1208 if (handled) {
1209 ALOGD("App switch has arrived.");
1210 } else {
1211 ALOGD("App switch was abandoned.");
1212 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214}
1215
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001217 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218}
1219
Prabir Pradhancef936d2021-07-21 16:17:52 +00001220bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001221 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 return false;
1223 }
1224
1225 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001226 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001227 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001228 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1229 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001230 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001231 return true;
1232}
1233
Prabir Pradhancef936d2021-07-21 16:17:52 +00001234void InputDispatcher::postCommandLocked(Command&& command) {
1235 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236}
1237
1238void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001239 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001240 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001241 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242 releaseInboundEventLocked(entry);
1243 }
1244 traceInboundQueueLengthLocked();
1245}
1246
1247void InputDispatcher::releasePendingEventLocked() {
1248 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001250 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251 }
1252}
1253
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001254void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001256 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001257 if (DEBUG_DISPATCH_CYCLE) {
1258 ALOGD("Injected inbound event was dropped.");
1259 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001260 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261 }
1262 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001263 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 }
1265 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266}
1267
1268void InputDispatcher::resetKeyRepeatLocked() {
1269 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001270 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271 }
1272}
1273
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001274std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1275 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276
Michael Wright2e732952014-09-24 13:26:59 -07001277 uint32_t policyFlags = entry->policyFlags &
1278 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001280 std::shared_ptr<KeyEntry> newEntry =
1281 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1282 entry->source, entry->displayId, policyFlags, entry->action,
1283 entry->flags, entry->keyCode, entry->scanCode,
1284 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001285
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001286 newEntry->syntheticRepeat = true;
1287 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001289 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290}
1291
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001292bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001293 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001294 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1295 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1296 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001297
1298 // Reset key repeating in case a keyboard device was added or removed or something.
1299 resetKeyRepeatLocked();
1300
1301 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001302 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1303 scoped_unlock unlock(mLock);
1304 mPolicy->notifyConfigurationChanged(eventTime);
1305 };
1306 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307 return true;
1308}
1309
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001310bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1311 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001312 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1313 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1314 entry.deviceId);
1315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316
liushenxiang42232912021-05-21 20:24:09 +08001317 // Reset key repeating in case a keyboard device was disabled or enabled.
1318 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1319 resetKeyRepeatLocked();
1320 }
1321
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001322 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001323 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 synthesizeCancelationEventsForAllConnectionsLocked(options);
1325 return true;
1326}
1327
Vishnu Nairad321cd2020-08-20 16:40:21 -07001328void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001329 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001330 if (mPendingEvent != nullptr) {
1331 // Move the pending event to the front of the queue. This will give the chance
1332 // for the pending event to get dispatched to the newly focused window
1333 mInboundQueue.push_front(mPendingEvent);
1334 mPendingEvent = nullptr;
1335 }
1336
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001337 std::unique_ptr<FocusEntry> focusEntry =
1338 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1339 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001340
1341 // This event should go to the front of the queue, but behind all other focus events
1342 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001343 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001344 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001345 [](const std::shared_ptr<EventEntry>& event) {
1346 return event->type == EventEntry::Type::FOCUS;
1347 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001348
1349 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001350 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001351}
1352
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001353void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001354 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001355 if (channel == nullptr) {
1356 return; // Window has gone away
1357 }
1358 InputTarget target;
1359 target.inputChannel = channel;
1360 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1361 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001362 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1363 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001364 std::string reason = std::string("reason=").append(entry->reason);
1365 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001366 dispatchEventLocked(currentTime, entry, {target});
1367}
1368
Prabir Pradhan99987712020-11-10 18:43:05 -08001369void InputDispatcher::dispatchPointerCaptureChangedLocked(
1370 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1371 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001372 dropReason = DropReason::NOT_DROPPED;
1373
Prabir Pradhan99987712020-11-10 18:43:05 -08001374 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001375 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001376
1377 if (entry->pointerCaptureRequest.enable) {
1378 // Enable Pointer Capture.
1379 if (haveWindowWithPointerCapture &&
1380 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001381 // This can happen if pointer capture is disabled and re-enabled before we notify the
1382 // app of the state change, so there is no need to notify the app.
1383 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1384 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001385 }
1386 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001387 // This can happen if a window requests capture and immediately releases capture.
1388 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001389 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001390 return;
1391 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001392 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1393 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1394 return;
1395 }
1396
Vishnu Nairc519ff72021-01-21 08:23:08 -08001397 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001398 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1399 mWindowTokenWithPointerCapture = token;
1400 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001401 // Disable Pointer Capture.
1402 // We do not check if the sequence number matches for requests to disable Pointer Capture
1403 // for two reasons:
1404 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1405 // to disable capture with the same sequence number: one generated by
1406 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1407 // Capture being disabled in InputReader.
1408 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1409 // actual Pointer Capture state that affects events being generated by input devices is
1410 // in InputReader.
1411 if (!haveWindowWithPointerCapture) {
1412 // Pointer capture was already forcefully disabled because of focus change.
1413 dropReason = DropReason::NOT_DROPPED;
1414 return;
1415 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001416 token = mWindowTokenWithPointerCapture;
1417 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001418 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001419 setPointerCaptureLocked(false);
1420 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001421 }
1422
1423 auto channel = getInputChannelLocked(token);
1424 if (channel == nullptr) {
1425 // Window has gone away, clean up Pointer Capture state.
1426 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001427 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001428 setPointerCaptureLocked(false);
1429 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001430 return;
1431 }
1432 InputTarget target;
1433 target.inputChannel = channel;
1434 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1435 entry->dispatchInProgress = true;
1436 dispatchEventLocked(currentTime, entry, {target});
1437
1438 dropReason = DropReason::NOT_DROPPED;
1439}
1440
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001441void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1442 const std::shared_ptr<TouchModeEntry>& entry) {
1443 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001444 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001445 if (windowHandles.empty()) {
1446 return;
1447 }
1448 const std::vector<InputTarget> inputTargets =
1449 getInputTargetsFromWindowHandlesLocked(windowHandles);
1450 if (inputTargets.empty()) {
1451 return;
1452 }
1453 entry->dispatchInProgress = true;
1454 dispatchEventLocked(currentTime, entry, inputTargets);
1455}
1456
1457std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1458 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1459 std::vector<InputTarget> inputTargets;
1460 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001461 const sp<IBinder>& token = handle->getToken();
1462 if (token == nullptr) {
1463 continue;
1464 }
1465 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1466 if (channel == nullptr) {
1467 continue; // Window has gone away
1468 }
1469 InputTarget target;
1470 target.inputChannel = channel;
1471 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1472 inputTargets.push_back(target);
1473 }
1474 return inputTargets;
1475}
1476
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001477bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001478 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001480 if (!entry->dispatchInProgress) {
1481 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1482 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1483 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1484 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001485 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486 // We have seen two identical key downs in a row which indicates that the device
1487 // driver is automatically generating key repeats itself. We take note of the
1488 // repeat here, but we disable our own next key repeat timer since it is clear that
1489 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001490 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1491 // Make sure we don't get key down from a different device. If a different
1492 // device Id has same key pressed down, the new device Id will replace the
1493 // current one to hold the key repeat with repeat count reset.
1494 // In the future when got a KEY_UP on the device id, drop it and do not
1495 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1497 resetKeyRepeatLocked();
1498 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1499 } else {
1500 // Not a repeat. Save key down state in case we do see a repeat later.
1501 resetKeyRepeatLocked();
1502 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1503 }
1504 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001505 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1506 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001507 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001508 if (DEBUG_INBOUND_EVENT_DETAILS) {
1509 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1510 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001511 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 resetKeyRepeatLocked();
1513 }
1514
1515 if (entry->repeatCount == 1) {
1516 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1517 } else {
1518 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1519 }
1520
1521 entry->dispatchInProgress = true;
1522
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001523 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524 }
1525
1526 // Handle case where the policy asked us to try again later last time.
1527 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1528 if (currentTime < entry->interceptKeyWakeupTime) {
1529 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1530 *nextWakeupTime = entry->interceptKeyWakeupTime;
1531 }
1532 return false; // wait until next wakeup
1533 }
1534 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1535 entry->interceptKeyWakeupTime = 0;
1536 }
1537
1538 // Give the policy a chance to intercept the key.
1539 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1540 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001541 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001542 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001543
1544 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1545 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1546 };
1547 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548 return false; // wait for the command to run
1549 } else {
1550 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1551 }
1552 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001553 if (*dropReason == DropReason::NOT_DROPPED) {
1554 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 }
1556 }
1557
1558 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001559 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001560 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001561 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1562 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001563 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564 return true;
1565 }
1566
1567 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001568 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001569 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001570 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001571 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 return false;
1573 }
1574
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001575 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001576 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577 return true;
1578 }
1579
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001580 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001581 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001582
1583 // Dispatch the key.
1584 dispatchEventLocked(currentTime, entry, inputTargets);
1585 return true;
1586}
1587
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001588void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001589 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1590 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1591 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1592 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1593 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1594 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1595 entry.metaState, entry.repeatCount, entry.downTime);
1596 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597}
1598
Prabir Pradhancef936d2021-07-21 16:17:52 +00001599void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1600 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001601 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001602 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1603 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1604 "source=0x%x, sensorType=%s",
1605 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001606 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001607 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001608 auto command = [this, entry]() REQUIRES(mLock) {
1609 scoped_unlock unlock(mLock);
1610
1611 if (entry->accuracyChanged) {
1612 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1613 }
1614 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1615 entry->hwTimestamp, entry->values);
1616 };
1617 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001618}
1619
1620bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001621 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1622 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001623 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001624 }
Chris Yef59a2f42020-10-16 12:55:26 -07001625 { // acquire lock
1626 std::scoped_lock _l(mLock);
1627
1628 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1629 std::shared_ptr<EventEntry> entry = *it;
1630 if (entry->type == EventEntry::Type::SENSOR) {
1631 it = mInboundQueue.erase(it);
1632 releaseInboundEventLocked(entry);
1633 }
1634 }
1635 }
1636 return true;
1637}
1638
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001639bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001640 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001641 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001643 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644 entry->dispatchInProgress = true;
1645
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001646 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 }
1648
1649 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001650 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001651 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001652 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1653 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001654 return true;
1655 }
1656
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001657 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658
1659 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001660 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661
1662 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001663 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 if (isPointerEvent) {
1665 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001666
1667 if (mDragState &&
1668 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1669 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1670 pilferPointersLocked(mDragState->dragWindow->getToken());
1671 }
1672
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001673 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001674 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001675 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 } else {
1677 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001678 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001679 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001681 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 return false;
1683 }
1684
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001685 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001686 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001687 return true;
1688 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001689 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001690 CancelationOptions::Mode mode(isPointerEvent
1691 ? CancelationOptions::CANCEL_POINTER_EVENTS
1692 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1693 CancelationOptions options(mode, "input event injection failed");
1694 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695 return true;
1696 }
1697
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001698 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001699 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001700
1701 // Dispatch the motion.
1702 if (conflictingPointerActions) {
1703 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001704 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001705 synthesizeCancelationEventsForAllConnectionsLocked(options);
1706 }
1707 dispatchEventLocked(currentTime, entry, inputTargets);
1708 return true;
1709}
1710
chaviw98318de2021-05-19 16:45:23 -05001711void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001712 bool isExiting, const int32_t rawX,
1713 const int32_t rawY) {
1714 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001715 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001716 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1717 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001718
1719 enqueueInboundEventLocked(std::move(dragEntry));
1720}
1721
1722void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1723 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1724 if (channel == nullptr) {
1725 return; // Window has gone away
1726 }
1727 InputTarget target;
1728 target.inputChannel = channel;
1729 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1730 entry->dispatchInProgress = true;
1731 dispatchEventLocked(currentTime, entry, {target});
1732}
1733
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001734void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001735 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1736 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1737 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001738 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001739 "metaState=0x%x, buttonState=0x%x,"
1740 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1741 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001742 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1743 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1744 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001746 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1747 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1748 "x=%f, y=%f, pressure=%f, size=%f, "
1749 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1750 "orientation=%f",
1751 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1752 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1753 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1754 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1755 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1756 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1757 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1758 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1759 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1760 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1761 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763}
1764
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001765void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1766 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001767 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001768 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001769 if (DEBUG_DISPATCH_CYCLE) {
1770 ALOGD("dispatchEventToCurrentInputTargets");
1771 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001773 updateInteractionTokensLocked(*eventEntry, inputTargets);
1774
Michael Wrightd02c5b62014-02-10 15:10:22 -08001775 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1776
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001777 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001779 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001780 sp<Connection> connection =
1781 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001782 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001783 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001785 if (DEBUG_FOCUS) {
1786 ALOGD("Dropping event delivery to target with channel '%s' because it "
1787 "is no longer registered with the input dispatcher.",
1788 inputTarget.inputChannel->getName().c_str());
1789 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001790 }
1791 }
1792}
1793
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001794void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1795 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1796 // If the policy decides to close the app, we will get a channel removal event via
1797 // unregisterInputChannel, and will clean up the connection that way. We are already not
1798 // sending new pointers to the connection when it blocked, but focused events will continue to
1799 // pile up.
1800 ALOGW("Canceling events for %s because it is unresponsive",
1801 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001802 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001803 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1804 "application not responding");
1805 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806 }
1807}
1808
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001809void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001810 if (DEBUG_FOCUS) {
1811 ALOGD("Resetting ANR timeouts.");
1812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813
1814 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001815 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001816 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001817}
1818
Tiger Huang721e26f2018-07-24 22:26:19 +08001819/**
1820 * Get the display id that the given event should go to. If this event specifies a valid display id,
1821 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1822 * Focused display is the display that the user most recently interacted with.
1823 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001824int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001825 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001826 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001827 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001828 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1829 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001830 break;
1831 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001832 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001833 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1834 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001835 break;
1836 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001837 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001838 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001839 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001840 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001841 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001842 case EventEntry::Type::SENSOR:
1843 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001844 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001845 return ADISPLAY_ID_NONE;
1846 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001847 }
1848 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1849}
1850
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001851bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1852 const char* focusedWindowName) {
1853 if (mAnrTracker.empty()) {
1854 // already processed all events that we waited for
1855 mKeyIsWaitingForEventsTimeout = std::nullopt;
1856 return false;
1857 }
1858
1859 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1860 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001861 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001862 mKeyIsWaitingForEventsTimeout = currentTime +
1863 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1864 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001865 return true;
1866 }
1867
1868 // We still have pending events, and already started the timer
1869 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1870 return true; // Still waiting
1871 }
1872
1873 // Waited too long, and some connection still hasn't processed all motions
1874 // Just send the key to the focused window
1875 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1876 focusedWindowName);
1877 mKeyIsWaitingForEventsTimeout = std::nullopt;
1878 return false;
1879}
1880
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001881static std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
1882 if (eventEntry.type == EventEntry::Type::KEY) {
1883 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
1884 return keyEntry.downTime;
1885 } else if (eventEntry.type == EventEntry::Type::MOTION) {
1886 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
1887 return motionEntry.downTime;
1888 }
1889 return std::nullopt;
1890}
1891
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001892InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1893 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1894 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001895 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001896
Tiger Huang721e26f2018-07-24 22:26:19 +08001897 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001898 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001899 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001900 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1901
Michael Wrightd02c5b62014-02-10 15:10:22 -08001902 // If there is no currently focused window and no focused application
1903 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001904 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1905 ALOGI("Dropping %s event because there is no focused window or focused application in "
1906 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001907 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001908 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909 }
1910
Vishnu Nair062a8672021-09-03 16:07:44 -07001911 // Drop key events if requested by input feature
1912 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1913 return InputEventInjectionResult::FAILED;
1914 }
1915
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001916 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1917 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1918 // start interacting with another application via touch (app switch). This code can be removed
1919 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1920 // an app is expected to have a focused window.
1921 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1922 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1923 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001924 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1925 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1926 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001927 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001928 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001929 ALOGW("Waiting because no window has focus but %s may eventually add a "
1930 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001931 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001932 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001933 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001934 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1935 // Already raised ANR. Drop the event
1936 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001937 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001938 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001939 } else {
1940 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001941 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001942 }
1943 }
1944
1945 // we have a valid, non-null focused window
1946 resetNoFocusedWindowTimeoutLocked();
1947
Prabir Pradhan5735a322022-04-11 17:23:34 +00001948 // Verify targeted injection.
1949 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
1950 ALOGW("Dropping injected event: %s", (*err).c_str());
1951 return InputEventInjectionResult::TARGET_MISMATCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952 }
1953
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001954 if (focusedWindowHandle->getInfo()->inputConfig.test(
1955 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001956 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001957 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001958 }
1959
1960 // If the event is a key event, then we must wait for all previous events to
1961 // complete before delivering it because previous events may have the
1962 // side-effect of transferring focus to a different window and we want to
1963 // ensure that the following keys are sent to the new window.
1964 //
1965 // Suppose the user touches a button in a window then immediately presses "A".
1966 // If the button causes a pop-up window to appear then we want to ensure that
1967 // the "A" key is delivered to the new pop-up window. This is because users
1968 // often anticipate pending UI changes when typing on a keyboard.
1969 // To obtain this behavior, we must serialize key events with respect to all
1970 // prior input events.
1971 if (entry.type == EventEntry::Type::KEY) {
1972 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1973 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001974 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001975 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976 }
1977
1978 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001979 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001980 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001981 BitSet32(0), getDownTime(entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982
1983 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001984 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985}
1986
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001987/**
1988 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1989 * that are currently unresponsive.
1990 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001991std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1992 const std::vector<Monitor>& monitors) const {
1993 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001994 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001995 [this](const Monitor& monitor) REQUIRES(mLock) {
1996 sp<Connection> connection =
1997 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001998 if (connection == nullptr) {
1999 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002000 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002001 return false;
2002 }
2003 if (!connection->responsive) {
2004 ALOGW("Unresponsive monitor %s will not get the new gesture",
2005 connection->inputChannel->getName().c_str());
2006 return false;
2007 }
2008 return true;
2009 });
2010 return responsiveMonitors;
2011}
2012
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002013InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
2014 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
2015 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002016 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018 // For security reasons, we defer updating the touch state until we are sure that
2019 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002020 const int32_t displayId = entry.displayId;
2021 const int32_t action = entry.action;
2022 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023
2024 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002025 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
chaviw98318de2021-05-19 16:45:23 -05002026 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2027 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002028
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002029 // Copy current touch state into tempTouchState.
2030 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2031 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002032 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002033 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002034 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2035 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002036 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002037 }
2038
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002039 bool isSplit = tempTouchState.split;
2040 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2041 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2042 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002043
2044 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2045 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2046 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2047 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2048 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002049 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002050 bool wrongDevice = false;
2051 if (newGesture) {
2052 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002053 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002054 ALOGI("Dropping event because a pointer for a different device is already down "
2055 "in display %" PRId32,
2056 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002057 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002058 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002059 switchedDevice = false;
2060 wrongDevice = true;
2061 goto Failed;
2062 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002063 tempTouchState.reset();
2064 tempTouchState.down = down;
2065 tempTouchState.deviceId = entry.deviceId;
2066 tempTouchState.source = entry.source;
2067 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002069 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002070 ALOGI("Dropping move event because a pointer for a different device is already active "
2071 "in display %" PRId32,
2072 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002073 // TODO: test multiple simultaneous input streams.
Prabir Pradhan5735a322022-04-11 17:23:34 +00002074 injectionResult = InputEventInjectionResult::FAILED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002075 switchedDevice = false;
2076 wrongDevice = true;
2077 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078 }
2079
2080 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2081 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002082 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002083 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002084 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002085 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002086 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002087 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002088
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002090 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002091 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2092 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002094 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002095 }
2096
Prabir Pradhan5735a322022-04-11 17:23:34 +00002097 // Verify targeted injection.
2098 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2099 ALOGW("Dropping injected touch event: %s", (*err).c_str());
2100 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2101 newTouchedWindowHandle = nullptr;
2102 goto Failed;
2103 }
2104
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002105 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002106 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002107 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2108 // New window supports splitting, but we should never split mouse events.
2109 isSplit = !isFromMouse;
2110 } else if (isSplit) {
2111 // New window does not support splitting but we have already split events.
2112 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002113 newTouchedWindowHandle = nullptr;
2114 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002115 } else {
2116 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002117 // be delivered to a new window which supports split touch. Pointers from a mouse device
2118 // should never be split.
2119 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002120 }
2121
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002122 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002123 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002124 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2125 newHoverWindowHandle = nullptr;
2126 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002127 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002128 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002129 }
2130
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002131 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002132 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002133 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002134 // Process the foreground window first so that it is the first to receive the event.
2135 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002136 }
2137
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002138 if (newTouchedWindows.empty()) {
2139 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2140 x, y, displayId);
2141 injectionResult = InputEventInjectionResult::FAILED;
2142 goto Failed;
2143 }
2144
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002145 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002146 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002147 continue;
2148 }
2149
2150 // Set target flags.
2151 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2152
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002153 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2154 // There should only be one touched window that can be "foreground" for the pointer.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002155 targetFlags |= InputTarget::FLAG_FOREGROUND;
2156 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002157
2158 if (isSplit) {
2159 targetFlags |= InputTarget::FLAG_SPLIT;
2160 }
2161 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2162 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2163 } else if (isWindowObscuredLocked(windowHandle)) {
2164 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2165 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002166
2167 // Update the temporary touch state.
2168 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002169 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002170
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002171 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
2172 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002174
2175 // If any existing window is pilfering pointers from newly added window, remove it
2176 BitSet32 canceledPointers = BitSet32(0);
2177 for (const TouchedWindow& window : tempTouchState.windows) {
2178 if (window.isPilferingPointers) {
2179 canceledPointers |= window.pointerIds;
2180 }
2181 }
2182 tempTouchState.cancelPointersForNonPilferingWindows(canceledPointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183 } else {
2184 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2185
2186 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002187 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002188 if (DEBUG_FOCUS) {
2189 ALOGD("Dropping event because the pointer is not down or we previously "
2190 "dropped the pointer down event in display %" PRId32,
2191 displayId);
2192 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002193 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002194 goto Failed;
2195 }
2196
arthurhung6d4bed92021-03-17 11:59:33 +08002197 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002198
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002200 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002201 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002202 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07002203 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002204 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002205 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002206 newTouchedWindowHandle =
2207 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002208
Prabir Pradhan5735a322022-04-11 17:23:34 +00002209 // Verify targeted injection.
2210 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2211 ALOGW("Dropping injected event: %s", (*err).c_str());
2212 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2213 newTouchedWindowHandle = nullptr;
2214 goto Failed;
2215 }
2216
Vishnu Nair062a8672021-09-03 16:07:44 -07002217 // Drop touch events if requested by input feature
2218 if (newTouchedWindowHandle != nullptr &&
2219 shouldDropInput(entry, newTouchedWindowHandle)) {
2220 newTouchedWindowHandle = nullptr;
2221 }
2222
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002223 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2224 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002225 if (DEBUG_FOCUS) {
2226 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2227 oldTouchedWindowHandle->getName().c_str(),
2228 newTouchedWindowHandle->getName().c_str(), displayId);
2229 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002231 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2232 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2233 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234
2235 // Make a slippery entrance into the new window.
2236 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002237 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238 }
2239
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002240 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
2241 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
2242 targetFlags |= InputTarget::FLAG_FOREGROUND;
2243 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002244 if (isSplit) {
2245 targetFlags |= InputTarget::FLAG_SPLIT;
2246 }
2247 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2248 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002249 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2250 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251 }
2252
2253 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002254 pointerIds.markBit(entry.pointerProperties[0].id);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002255 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2256 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257 }
2258 }
2259 }
2260
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002261 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002263 // Let the previous window know that the hover sequence is over, unless we already did
2264 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002265 if (mLastHoverWindowHandle != nullptr &&
2266 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2267 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002268 if (DEBUG_HOVER) {
2269 ALOGD("Sending hover exit event to window %s.",
2270 mLastHoverWindowHandle->getName().c_str());
2271 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002272 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2273 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274 }
2275
Garfield Tandf26e862020-07-01 20:18:19 -07002276 // Let the new window know that the hover sequence is starting, unless we already did it
2277 // when dispatching it as is to newTouchedWindowHandle.
2278 if (newHoverWindowHandle != nullptr &&
2279 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2280 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002281 if (DEBUG_HOVER) {
2282 ALOGD("Sending hover enter event to window %s.",
2283 newHoverWindowHandle->getName().c_str());
2284 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002285 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2286 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2287 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 }
2289 }
2290
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002291 // Ensure that we have at least one foreground window or at least one window that cannot be a
2292 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2293 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2294 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002295 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2296 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002297 return !canReceiveForegroundTouches(
2298 *touchedWindow.windowHandle->getInfo()) ||
2299 (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002300 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002301 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2302 displayId, entry.getDescription().c_str());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002303 injectionResult = InputEventInjectionResult::FAILED;
2304 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 }
2306
Prabir Pradhan5735a322022-04-11 17:23:34 +00002307 // Ensure that all touched windows are valid for injection.
2308 if (entry.injectionState != nullptr) {
2309 std::string errs;
2310 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
2311 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2312 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2313 // dispatched to any uid, since the coords will be zeroed out later.
2314 continue;
2315 }
2316 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2317 if (err) errs += "\n - " + *err;
2318 }
2319 if (!errs.empty()) {
2320 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2321 "%d:%s",
2322 *entry.injectionState->targetUid, errs.c_str());
2323 injectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2324 goto Failed;
2325 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002326 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002327
Michael Wrightd02c5b62014-02-10 15:10:22 -08002328 // Check whether windows listening for outside touches are owned by the same UID. If it is
2329 // set the policy flag that we will not reveal coordinate information to this window.
2330 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002331 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002332 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002333 if (foregroundWindowHandle) {
2334 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002335 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002336 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002337 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2338 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2339 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002340 InputTarget::FLAG_ZERO_COORDS,
2341 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343 }
2344 }
2345 }
2346 }
2347
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348 // If this is the first pointer going down and the touched window has a wallpaper
2349 // then also add the touched wallpaper windows so they are locked in for the duration
2350 // of the touch gesture.
2351 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2352 // engine only supports touch events. We would need to add a mechanism similar
2353 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2354 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002355 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002356 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002357 if (foregroundWindowHandle &&
2358 foregroundWindowHandle->getInfo()->inputConfig.test(
2359 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002360 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002361 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002362 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2363 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002364 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002365 windowHandle->getInfo()->inputConfig.test(
2366 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002367 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002368 .addOrUpdateWindow(windowHandle,
2369 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2370 InputTarget::
2371 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2372 InputTarget::FLAG_DISPATCH_AS_IS,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002373 BitSet32(0), entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374 }
2375 }
2376 }
2377 }
2378
2379 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002380 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002382 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002383 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002384 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2385 inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002386 }
2387
2388 // Drop the outside or hover touch windows since we will not care about them
2389 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002390 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002391
2392Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002394 if (!wrongDevice) {
2395 if (switchedDevice) {
2396 if (DEBUG_FOCUS) {
2397 ALOGD("Conflicting pointer actions: Switched to a different device.");
2398 }
2399 *outConflictingPointerActions = true;
2400 }
2401
2402 if (isHoverAction) {
2403 // Started hovering, therefore no longer down.
2404 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002405 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002406 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2407 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002408 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002409 *outConflictingPointerActions = true;
2410 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002411 tempTouchState.reset();
2412 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2413 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2414 tempTouchState.deviceId = entry.deviceId;
2415 tempTouchState.source = entry.source;
2416 tempTouchState.displayId = displayId;
2417 }
2418 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2419 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2420 // All pointers up or canceled.
2421 tempTouchState.reset();
2422 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2423 // First pointer went down.
2424 if (oldState && oldState->down) {
2425 if (DEBUG_FOCUS) {
2426 ALOGD("Conflicting pointer actions: Down received while already down.");
2427 }
2428 *outConflictingPointerActions = true;
2429 }
2430 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2431 // One pointer went up.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002432 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2433 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002434
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002435 for (size_t i = 0; i < tempTouchState.windows.size();) {
2436 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2437 touchedWindow.pointerIds.clearBit(pointerId);
2438 if (touchedWindow.pointerIds.isEmpty()) {
2439 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2440 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002442 i += 1;
2443 }
2444 } else if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2445 // If no split, we suppose all touched windows should receive pointer down.
2446 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2447 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2448 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2449 // Ignore drag window for it should just track one pointer.
2450 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2451 continue;
2452 }
2453 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Jeff Brownf086ddb2014-02-11 14:28:48 -08002454 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002455 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002456
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002457 // Save changes unless the action was scroll in which case the temporary touch
2458 // state was only valid for this one action.
2459 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2460 if (tempTouchState.displayId >= 0) {
2461 mTouchStatesByDisplay[displayId] = tempTouchState;
2462 } else {
2463 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002465 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002467 // Update hover state.
2468 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469 }
2470
Michael Wrightd02c5b62014-02-10 15:10:22 -08002471 return injectionResult;
2472}
2473
arthurhung6d4bed92021-03-17 11:59:33 +08002474void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002475 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2476 // have an explicit reason to support it.
2477 constexpr bool isStylus = false;
2478
chaviw98318de2021-05-19 16:45:23 -05002479 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002480 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002481 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002482 if (dropWindow) {
2483 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002484 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002485 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002486 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002487 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002488 }
2489 mDragState.reset();
2490}
2491
2492void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002493 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002494 return;
2495 }
2496
arthurhung6d4bed92021-03-17 11:59:33 +08002497 if (!mDragState->isStartDrag) {
2498 mDragState->isStartDrag = true;
2499 mDragState->isStylusButtonDownAtStart =
2500 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2501 }
2502
Arthur Hung54745652022-04-20 07:17:41 +00002503 // Find the pointer index by id.
2504 int32_t pointerIndex = 0;
2505 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2506 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2507 if (pointerProperties.id == mDragState->pointerId) {
2508 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002509 }
Arthur Hung54745652022-04-20 07:17:41 +00002510 }
arthurhung6d4bed92021-03-17 11:59:33 +08002511
Arthur Hung54745652022-04-20 07:17:41 +00002512 if (uint32_t(pointerIndex) == entry.pointerCount) {
2513 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002514 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002515 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002516 return;
2517 }
2518
2519 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2520 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2521 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2522
2523 switch (maskedAction) {
2524 case AMOTION_EVENT_ACTION_MOVE: {
2525 // Handle the special case : stylus button no longer pressed.
2526 bool isStylusButtonDown =
2527 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2528 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2529 finishDragAndDrop(entry.displayId, x, y);
2530 return;
2531 }
2532
2533 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2534 // until we have an explicit reason to support it.
2535 constexpr bool isStylus = false;
2536
2537 const sp<WindowInfoHandle> hoverWindowHandle =
2538 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2539 isStylus, false /*addOutsideTargets*/,
2540 true /*ignoreDragWindow*/);
2541 // enqueue drag exit if needed.
2542 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2543 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2544 if (mDragState->dragHoverWindowHandle != nullptr) {
2545 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2546 y);
2547 }
2548 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2549 }
2550 // enqueue drag location if needed.
2551 if (hoverWindowHandle != nullptr) {
2552 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2553 }
2554 break;
2555 }
2556
2557 case AMOTION_EVENT_ACTION_POINTER_UP:
2558 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2559 break;
2560 }
2561 // The drag pointer is up.
2562 [[fallthrough]];
2563 case AMOTION_EVENT_ACTION_UP:
2564 finishDragAndDrop(entry.displayId, x, y);
2565 break;
2566 case AMOTION_EVENT_ACTION_CANCEL: {
2567 ALOGD("Receiving cancel when drag and drop.");
2568 sendDropWindowCommandLocked(nullptr, 0, 0);
2569 mDragState.reset();
2570 break;
2571 }
arthurhungb89ccb02020-12-30 16:19:01 +08002572 }
2573}
2574
chaviw98318de2021-05-19 16:45:23 -05002575void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002576 int32_t targetFlags, BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002577 std::optional<nsecs_t> firstDownTimeInTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002578 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002579 std::vector<InputTarget>::iterator it =
2580 std::find_if(inputTargets.begin(), inputTargets.end(),
2581 [&windowHandle](const InputTarget& inputTarget) {
2582 return inputTarget.inputChannel->getConnectionToken() ==
2583 windowHandle->getToken();
2584 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002585
chaviw98318de2021-05-19 16:45:23 -05002586 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002587
2588 if (it == inputTargets.end()) {
2589 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002590 std::shared_ptr<InputChannel> inputChannel =
2591 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002592 if (inputChannel == nullptr) {
2593 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2594 return;
2595 }
2596 inputTarget.inputChannel = inputChannel;
2597 inputTarget.flags = targetFlags;
2598 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002599 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002600 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2601 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002602 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002603 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002604 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002605 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002606 inputTargets.push_back(inputTarget);
2607 it = inputTargets.end() - 1;
2608 }
2609
2610 ALOG_ASSERT(it->flags == targetFlags);
2611 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2612
chaviw1ff3d1e2020-07-01 15:53:47 -07002613 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002614}
2615
Michael Wright3dd60e22019-03-27 22:06:44 +00002616void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002617 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002618 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2619 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002620
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002621 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2622 InputTarget target;
2623 target.inputChannel = monitor.inputChannel;
2624 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002625 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2626 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002627 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2628 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002629 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002630 target.setDefaultPointerTransform(target.displayTransform);
2631 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002632 }
2633}
2634
Robert Carrc9bf1d32020-04-13 17:21:08 -07002635/**
2636 * Indicate whether one window handle should be considered as obscuring
2637 * another window handle. We only check a few preconditions. Actually
2638 * checking the bounds is left to the caller.
2639 */
chaviw98318de2021-05-19 16:45:23 -05002640static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2641 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002642 // Compare by token so cloned layers aren't counted
2643 if (haveSameToken(windowHandle, otherHandle)) {
2644 return false;
2645 }
2646 auto info = windowHandle->getInfo();
2647 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002648 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002649 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002650 } else if (otherInfo->alpha == 0 &&
2651 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002652 // Those act as if they were invisible, so we don't need to flag them.
2653 // We do want to potentially flag touchable windows even if they have 0
2654 // opacity, since they can consume touches and alter the effects of the
2655 // user interaction (eg. apps that rely on
2656 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2657 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2658 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002659 } else if (info->ownerUid == otherInfo->ownerUid) {
2660 // If ownerUid is the same we don't generate occlusion events as there
2661 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002662 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002663 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002664 return false;
2665 } else if (otherInfo->displayId != info->displayId) {
2666 return false;
2667 }
2668 return true;
2669}
2670
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002671/**
2672 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2673 * untrusted, one should check:
2674 *
2675 * 1. If result.hasBlockingOcclusion is true.
2676 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2677 * BLOCK_UNTRUSTED.
2678 *
2679 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2680 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2681 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2682 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2683 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2684 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2685 *
2686 * If neither of those is true, then it means the touch can be allowed.
2687 */
2688InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002689 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2690 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002691 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002692 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002693 TouchOcclusionInfo info;
2694 info.hasBlockingOcclusion = false;
2695 info.obscuringOpacity = 0;
2696 info.obscuringUid = -1;
2697 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002698 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002699 if (windowHandle == otherHandle) {
2700 break; // All future windows are below us. Exit early.
2701 }
chaviw98318de2021-05-19 16:45:23 -05002702 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002703 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2704 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002705 if (DEBUG_TOUCH_OCCLUSION) {
2706 info.debugInfo.push_back(
2707 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2708 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002709 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2710 // we perform the checks below to see if the touch can be propagated or not based on the
2711 // window's touch occlusion mode
2712 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2713 info.hasBlockingOcclusion = true;
2714 info.obscuringUid = otherInfo->ownerUid;
2715 info.obscuringPackage = otherInfo->packageName;
2716 break;
2717 }
2718 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2719 uint32_t uid = otherInfo->ownerUid;
2720 float opacity =
2721 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2722 // Given windows A and B:
2723 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2724 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2725 opacityByUid[uid] = opacity;
2726 if (opacity > info.obscuringOpacity) {
2727 info.obscuringOpacity = opacity;
2728 info.obscuringUid = uid;
2729 info.obscuringPackage = otherInfo->packageName;
2730 }
2731 }
2732 }
2733 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002734 if (DEBUG_TOUCH_OCCLUSION) {
2735 info.debugInfo.push_back(
2736 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2737 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002738 return info;
2739}
2740
chaviw98318de2021-05-19 16:45:23 -05002741std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002742 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002743 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2744 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2745 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2746 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002747 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2748 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2749 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2750 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2751 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002752 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002753 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002754}
2755
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002756bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2757 if (occlusionInfo.hasBlockingOcclusion) {
2758 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2759 occlusionInfo.obscuringUid);
2760 return false;
2761 }
2762 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2763 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2764 "%.2f, maximum allowed = %.2f)",
2765 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2766 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2767 return false;
2768 }
2769 return true;
2770}
2771
chaviw98318de2021-05-19 16:45:23 -05002772bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002773 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002775 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2776 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002777 if (windowHandle == otherHandle) {
2778 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002779 }
chaviw98318de2021-05-19 16:45:23 -05002780 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002781 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002782 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002783 return true;
2784 }
2785 }
2786 return false;
2787}
2788
chaviw98318de2021-05-19 16:45:23 -05002789bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002790 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002791 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2792 const WindowInfo* windowInfo = windowHandle->getInfo();
2793 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002794 if (windowHandle == otherHandle) {
2795 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002796 }
chaviw98318de2021-05-19 16:45:23 -05002797 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002798 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002799 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002800 return true;
2801 }
2802 }
2803 return false;
2804}
2805
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002806std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002807 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002808 if (applicationHandle != nullptr) {
2809 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002810 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002811 } else {
2812 return applicationHandle->getName();
2813 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002814 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002815 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002816 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002817 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818 }
2819}
2820
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002821void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002822 if (!isUserActivityEvent(eventEntry)) {
2823 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002824 return;
2825 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002826 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002827 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002828 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002829 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002830 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002831 if (DEBUG_DISPATCH_CYCLE) {
2832 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2833 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002834 return;
2835 }
2836 }
2837
2838 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002839 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002840 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002841 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2842 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002843 return;
2844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002846 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002847 eventType = USER_ACTIVITY_EVENT_TOUCH;
2848 }
2849 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002851 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002852 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2853 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002854 return;
2855 }
2856 eventType = USER_ACTIVITY_EVENT_BUTTON;
2857 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002859 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002860 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002861 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002862 break;
2863 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864 }
2865
Prabir Pradhancef936d2021-07-21 16:17:52 +00002866 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2867 REQUIRES(mLock) {
2868 scoped_unlock unlock(mLock);
2869 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2870 };
2871 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002872}
2873
2874void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002875 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002876 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002877 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002878 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002879 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002880 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002881 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002882 ATRACE_NAME(message.c_str());
2883 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002884 if (DEBUG_DISPATCH_CYCLE) {
2885 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2886 "globalScaleFactor=%f, pointerIds=0x%x %s",
2887 connection->getInputChannelName().c_str(), inputTarget.flags,
2888 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2889 inputTarget.getPointerInfoString().c_str());
2890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891
2892 // Skip this event if the connection status is not normal.
2893 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002894 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002895 if (DEBUG_DISPATCH_CYCLE) {
2896 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002897 connection->getInputChannelName().c_str(),
2898 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002899 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002900 return;
2901 }
2902
2903 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002904 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2905 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2906 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002907 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002908
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002909 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002910 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002911 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
2912 "Splitting motion events requires a down time to be set for the "
2913 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002914 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002915 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
2916 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002917 if (!splitMotionEntry) {
2918 return; // split event was dropped
2919 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002920 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2921 std::string reason = std::string("reason=pointer cancel on split window");
2922 android_log_event_list(LOGTAG_INPUT_CANCEL)
2923 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2924 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002925 if (DEBUG_FOCUS) {
2926 ALOGD("channel '%s' ~ Split motion event.",
2927 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002928 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002929 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002930 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2931 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002932 return;
2933 }
2934 }
2935
2936 // Not splitting. Enqueue dispatch entries for the event as is.
2937 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2938}
2939
2940void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002941 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002942 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002943 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002944 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002945 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002946 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002947 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002948 ATRACE_NAME(message.c_str());
2949 }
2950
hongzuo liu95785e22022-09-06 02:51:35 +00002951 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002952
2953 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002954 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002955 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002956 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002957 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002958 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002959 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002960 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002961 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002962 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002963 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002964 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002965 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002966
2967 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002968 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002969 startDispatchCycleLocked(currentTime, connection);
2970 }
2971}
2972
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002973void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002974 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002975 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002976 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002977 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002978 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2979 connection->getInputChannelName().c_str(),
2980 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002981 ATRACE_NAME(message.c_str());
2982 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002983 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002984 if (!(inputTargetFlags & dispatchMode)) {
2985 return;
2986 }
2987 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2988
2989 // This is a new event.
2990 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002991 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002992 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002993
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002994 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2995 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002996 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002997 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002998 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002999 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003000 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003001 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003002 dispatchEntry->resolvedAction = keyEntry.action;
3003 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003005 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3006 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003007 if (DEBUG_DISPATCH_CYCLE) {
3008 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3009 "event",
3010 connection->getInputChannelName().c_str());
3011 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003012 return; // skip the inconsistent event
3013 }
3014 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003015 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003016
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003017 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003018 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003019 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3020 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3021 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3022 static_cast<int32_t>(IdGenerator::Source::OTHER);
3023 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003024 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3025 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3026 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3027 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3028 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3029 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3030 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3031 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3032 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3033 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3034 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003035 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003036 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003037 }
3038 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003039 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3040 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003041 if (DEBUG_DISPATCH_CYCLE) {
3042 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3043 "enter event",
3044 connection->getInputChannelName().c_str());
3045 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003046 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3047 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003048 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3049 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003050
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003051 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003052 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3053 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3054 }
3055 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3056 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003058
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003059 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3060 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003061 if (DEBUG_DISPATCH_CYCLE) {
3062 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3063 "event",
3064 connection->getInputChannelName().c_str());
3065 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003066 return; // skip the inconsistent event
3067 }
3068
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003069 dispatchEntry->resolvedEventId =
3070 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3071 ? mIdGenerator.nextId()
3072 : motionEntry.id;
3073 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3074 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3075 ") to MotionEvent(id=0x%" PRIx32 ").",
3076 motionEntry.id, dispatchEntry->resolvedEventId);
3077 ATRACE_NAME(message.c_str());
3078 }
3079
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003080 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3081 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3082 // Skip reporting pointer down outside focus to the policy.
3083 break;
3084 }
3085
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003086 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003087 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003088
3089 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003090 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003091 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003092 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003093 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3094 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003095 break;
3096 }
Chris Yef59a2f42020-10-16 12:55:26 -07003097 case EventEntry::Type::SENSOR: {
3098 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3099 break;
3100 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003101 case EventEntry::Type::CONFIGURATION_CHANGED:
3102 case EventEntry::Type::DEVICE_RESET: {
3103 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003104 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003105 break;
3106 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003107 }
3108
3109 // Remember that we are waiting for this dispatch to complete.
3110 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003111 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003112 }
3113
3114 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003115 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003116 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003117}
3118
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003119/**
3120 * This function is purely for debugging. It helps us understand where the user interaction
3121 * was taking place. For example, if user is touching launcher, we will see a log that user
3122 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3123 * We will see both launcher and wallpaper in that list.
3124 * Once the interaction with a particular set of connections starts, no new logs will be printed
3125 * until the set of interacted connections changes.
3126 *
3127 * The following items are skipped, to reduce the logspam:
3128 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3129 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3130 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3131 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3132 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003133 */
3134void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3135 const std::vector<InputTarget>& targets) {
3136 // Skip ACTION_UP events, and all events other than keys and motions
3137 if (entry.type == EventEntry::Type::KEY) {
3138 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3139 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3140 return;
3141 }
3142 } else if (entry.type == EventEntry::Type::MOTION) {
3143 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3144 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3145 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3146 return;
3147 }
3148 } else {
3149 return; // Not a key or a motion
3150 }
3151
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003152 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003153 std::vector<sp<Connection>> newConnections;
3154 for (const InputTarget& target : targets) {
3155 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3156 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3157 continue; // Skip windows that receive ACTION_OUTSIDE
3158 }
3159
3160 sp<IBinder> token = target.inputChannel->getConnectionToken();
3161 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003162 if (connection == nullptr) {
3163 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003164 }
3165 newConnectionTokens.insert(std::move(token));
3166 newConnections.emplace_back(connection);
3167 }
3168 if (newConnectionTokens == mInteractionConnectionTokens) {
3169 return; // no change
3170 }
3171 mInteractionConnectionTokens = newConnectionTokens;
3172
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003173 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003174 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003175 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003176 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003177 std::string message = "Interaction with: " + targetList;
3178 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003179 message += "<none>";
3180 }
3181 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3182}
3183
chaviwfd6d3512019-03-25 13:23:49 -07003184void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003185 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003186 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003187 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3188 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003189 return;
3190 }
3191
Vishnu Nairc519ff72021-01-21 08:23:08 -08003192 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003193 if (focusedToken == token) {
3194 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003195 return;
3196 }
3197
Prabir Pradhancef936d2021-07-21 16:17:52 +00003198 auto command = [this, token]() REQUIRES(mLock) {
3199 scoped_unlock unlock(mLock);
3200 mPolicy->onPointerDownOutsideFocus(token);
3201 };
3202 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203}
3204
3205void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003206 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003207 if (ATRACE_ENABLED()) {
3208 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003209 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003210 ATRACE_NAME(message.c_str());
3211 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003212 if (DEBUG_DISPATCH_CYCLE) {
3213 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3214 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003216 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003217 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003219 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003220 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221
3222 // Publish the event.
3223 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003224 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3225 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003226 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003227 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3228 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003230 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003231 status = connection->inputPublisher
3232 .publishKeyEvent(dispatchEntry->seq,
3233 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3234 keyEntry.source, keyEntry.displayId,
3235 std::move(hmac), dispatchEntry->resolvedAction,
3236 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3237 keyEntry.scanCode, keyEntry.metaState,
3238 keyEntry.repeatCount, keyEntry.downTime,
3239 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003240 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241 }
3242
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003243 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003244 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003246 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003247 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003248
chaviw82357092020-01-28 13:13:06 -08003249 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003250 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003251 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3252 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003253 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003254 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3255 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003256 // Don't apply window scale here since we don't want scale to affect raw
3257 // coordinates. The scale will be sent back to the client and applied
3258 // later when requesting relative coordinates.
3259 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3260 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003261 }
3262 usingCoords = scaledCoords;
3263 }
3264 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003265 // We don't want the dispatch target to know.
3266 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003267 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003268 scaledCoords[i].clear();
3269 }
3270 usingCoords = scaledCoords;
3271 }
3272 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003273
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003274 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003275
3276 // Publish the motion event.
3277 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003278 .publishMotionEvent(dispatchEntry->seq,
3279 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003280 motionEntry.deviceId, motionEntry.source,
3281 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003282 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003283 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003284 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003285 motionEntry.edgeFlags, motionEntry.metaState,
3286 motionEntry.buttonState,
3287 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003288 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003289 motionEntry.xPrecision, motionEntry.yPrecision,
3290 motionEntry.xCursorPosition,
3291 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003292 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003293 motionEntry.downTime, motionEntry.eventTime,
3294 motionEntry.pointerCount,
3295 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003296 break;
3297 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003298
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003299 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003300 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003301 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003302 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003303 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003304 break;
3305 }
3306
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003307 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3308 const TouchModeEntry& touchModeEntry =
3309 static_cast<const TouchModeEntry&>(eventEntry);
3310 status = connection->inputPublisher
3311 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3312 touchModeEntry.inTouchMode);
3313
3314 break;
3315 }
3316
Prabir Pradhan99987712020-11-10 18:43:05 -08003317 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3318 const auto& captureEntry =
3319 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3320 status = connection->inputPublisher
3321 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003322 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003323 break;
3324 }
3325
arthurhungb89ccb02020-12-30 16:19:01 +08003326 case EventEntry::Type::DRAG: {
3327 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3328 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3329 dragEntry.id, dragEntry.x,
3330 dragEntry.y,
3331 dragEntry.isExiting);
3332 break;
3333 }
3334
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003335 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003336 case EventEntry::Type::DEVICE_RESET:
3337 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003338 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003339 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003340 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003341 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342 }
3343
3344 // Check the result.
3345 if (status) {
3346 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003347 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003349 "This is unexpected because the wait queue is empty, so the pipe "
3350 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003351 "event to it, status=%s(%d)",
3352 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3353 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3355 } else {
3356 // Pipe is full and we are waiting for the app to finish process some events
3357 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003358 if (DEBUG_DISPATCH_CYCLE) {
3359 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3360 "waiting for the application to catch up",
3361 connection->getInputChannelName().c_str());
3362 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003363 }
3364 } else {
3365 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003366 "status=%s(%d)",
3367 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3368 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3370 }
3371 return;
3372 }
3373
3374 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003375 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3376 connection->outboundQueue.end(),
3377 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003378 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003379 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003380 if (connection->responsive) {
3381 mAnrTracker.insert(dispatchEntry->timeoutTime,
3382 connection->inputChannel->getConnectionToken());
3383 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003384 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385 }
3386}
3387
chaviw09c8d2d2020-08-24 15:48:26 -07003388std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3389 size_t size;
3390 switch (event.type) {
3391 case VerifiedInputEvent::Type::KEY: {
3392 size = sizeof(VerifiedKeyEvent);
3393 break;
3394 }
3395 case VerifiedInputEvent::Type::MOTION: {
3396 size = sizeof(VerifiedMotionEvent);
3397 break;
3398 }
3399 }
3400 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3401 return mHmacKeyManager.sign(start, size);
3402}
3403
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003404const std::array<uint8_t, 32> InputDispatcher::getSignature(
3405 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003406 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3407 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003408 // Only sign events up and down events as the purely move events
3409 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003410 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003411 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003412
3413 VerifiedMotionEvent verifiedEvent =
3414 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3415 verifiedEvent.actionMasked = actionMasked;
3416 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3417 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003418}
3419
3420const std::array<uint8_t, 32> InputDispatcher::getSignature(
3421 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3422 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3423 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3424 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003425 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003426}
3427
Michael Wrightd02c5b62014-02-10 15:10:22 -08003428void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003429 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003430 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003431 if (DEBUG_DISPATCH_CYCLE) {
3432 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3433 connection->getInputChannelName().c_str(), seq, toString(handled));
3434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003436 if (connection->status == Connection::Status::BROKEN ||
3437 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438 return;
3439 }
3440
3441 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003442 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3443 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3444 };
3445 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003446}
3447
3448void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003449 const sp<Connection>& connection,
3450 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003451 if (DEBUG_DISPATCH_CYCLE) {
3452 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3453 connection->getInputChannelName().c_str(), toString(notify));
3454 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003455
3456 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003457 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003458 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003459 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003460 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461
3462 // The connection appears to be unrecoverably broken.
3463 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003464 if (connection->status == Connection::Status::NORMAL) {
3465 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003466
3467 if (notify) {
3468 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003469 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3470 connection->getInputChannelName().c_str());
3471
3472 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003473 scoped_unlock unlock(mLock);
3474 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3475 };
3476 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477 }
3478 }
3479}
3480
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003481void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3482 while (!queue.empty()) {
3483 DispatchEntry* dispatchEntry = queue.front();
3484 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003485 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 }
3487}
3488
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003489void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003491 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492 }
3493 delete dispatchEntry;
3494}
3495
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003496int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3497 std::scoped_lock _l(mLock);
3498 sp<Connection> connection = getConnectionLocked(connectionToken);
3499 if (connection == nullptr) {
3500 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3501 connectionToken.get(), events);
3502 return 0; // remove the callback
3503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003504
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003505 bool notify;
3506 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3507 if (!(events & ALOOPER_EVENT_INPUT)) {
3508 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3509 "events=0x%x",
3510 connection->getInputChannelName().c_str(), events);
3511 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512 }
3513
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003514 nsecs_t currentTime = now();
3515 bool gotOne = false;
3516 status_t status = OK;
3517 for (;;) {
3518 Result<InputPublisher::ConsumerResponse> result =
3519 connection->inputPublisher.receiveConsumerResponse();
3520 if (!result.ok()) {
3521 status = result.error().code();
3522 break;
3523 }
3524
3525 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3526 const InputPublisher::Finished& finish =
3527 std::get<InputPublisher::Finished>(*result);
3528 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3529 finish.consumeTime);
3530 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003531 if (shouldReportMetricsForConnection(*connection)) {
3532 const InputPublisher::Timeline& timeline =
3533 std::get<InputPublisher::Timeline>(*result);
3534 mLatencyTracker
3535 .trackGraphicsLatency(timeline.inputEventId,
3536 connection->inputChannel->getConnectionToken(),
3537 std::move(timeline.graphicsTimeline));
3538 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003539 }
3540 gotOne = true;
3541 }
3542 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003543 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003544 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545 return 1;
3546 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003547 }
3548
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003549 notify = status != DEAD_OBJECT || !connection->monitor;
3550 if (notify) {
3551 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3552 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3553 status);
3554 }
3555 } else {
3556 // Monitor channels are never explicitly unregistered.
3557 // We do it automatically when the remote endpoint is closed so don't warn about them.
3558 const bool stillHaveWindowHandle =
3559 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3560 notify = !connection->monitor && stillHaveWindowHandle;
3561 if (notify) {
3562 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3563 connection->getInputChannelName().c_str(), events);
3564 }
3565 }
3566
3567 // Remove the channel.
3568 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3569 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003570}
3571
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003572void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003573 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003574 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003575 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003576 }
3577}
3578
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003579void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003580 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003581 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003582 for (const Monitor& monitor : monitors) {
3583 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003584 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003585 }
3586}
3587
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003589 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003590 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003591 if (connection == nullptr) {
3592 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003593 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003594
3595 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003596}
3597
3598void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3599 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003600 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003601 return;
3602 }
3603
3604 nsecs_t currentTime = now();
3605
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003606 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003607 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003609 if (cancelationEvents.empty()) {
3610 return;
3611 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003612 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3613 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3614 "with reality: %s, mode=%d.",
3615 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3616 options.mode);
3617 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003618
Arthur Hungb3307ee2021-10-14 10:57:37 +00003619 std::string reason = std::string("reason=").append(options.reason);
3620 android_log_event_list(LOGTAG_INPUT_CANCEL)
3621 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3622
Svet Ganov5d3bc372020-01-26 23:11:07 -08003623 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003624 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003625 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3626 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003627 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003628 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003629 target.globalScaleFactor = windowInfo->globalScaleFactor;
3630 }
3631 target.inputChannel = connection->inputChannel;
3632 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3633
hongzuo liu95785e22022-09-06 02:51:35 +00003634 const bool wasEmpty = connection->outboundQueue.empty();
3635
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003636 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003637 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003638 switch (cancelationEventEntry->type) {
3639 case EventEntry::Type::KEY: {
3640 logOutboundKeyDetails("cancel - ",
3641 static_cast<const KeyEntry&>(*cancelationEventEntry));
3642 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003644 case EventEntry::Type::MOTION: {
3645 logOutboundMotionDetails("cancel - ",
3646 static_cast<const MotionEntry&>(*cancelationEventEntry));
3647 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003649 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003650 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003651 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3652 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003653 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003654 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003655 break;
3656 }
3657 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003658 case EventEntry::Type::DEVICE_RESET:
3659 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003660 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003661 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003662 break;
3663 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664 }
3665
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003666 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3667 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003668 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003669
hongzuo liu95785e22022-09-06 02:51:35 +00003670 // If the outbound queue was previously empty, start the dispatch cycle going.
3671 if (wasEmpty && !connection->outboundQueue.empty()) {
3672 startDispatchCycleLocked(currentTime, connection);
3673 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674}
3675
Svet Ganov5d3bc372020-01-26 23:11:07 -08003676void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003677 const nsecs_t downTime, const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003678 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003679 return;
3680 }
3681
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003682 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003683 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003684
3685 if (downEvents.empty()) {
3686 return;
3687 }
3688
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003689 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003690 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3691 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003692 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003693
3694 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003695 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003696 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3697 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003698 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003699 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003700 target.globalScaleFactor = windowInfo->globalScaleFactor;
3701 }
3702 target.inputChannel = connection->inputChannel;
3703 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3704
hongzuo liu95785e22022-09-06 02:51:35 +00003705 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003706 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003707 switch (downEventEntry->type) {
3708 case EventEntry::Type::MOTION: {
3709 logOutboundMotionDetails("down - ",
3710 static_cast<const MotionEntry&>(*downEventEntry));
3711 break;
3712 }
3713
3714 case EventEntry::Type::KEY:
3715 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003716 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003717 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003718 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003719 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003720 case EventEntry::Type::SENSOR:
3721 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003722 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003723 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003724 break;
3725 }
3726 }
3727
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003728 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3729 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003730 }
3731
hongzuo liu95785e22022-09-06 02:51:35 +00003732 // If the outbound queue was previously empty, start the dispatch cycle going.
3733 if (wasEmpty && !connection->outboundQueue.empty()) {
3734 startDispatchCycleLocked(downTime, connection);
3735 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003736}
3737
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003738std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003739 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003740 ALOG_ASSERT(pointerIds.value != 0);
3741
3742 uint32_t splitPointerIndexMap[MAX_POINTERS];
3743 PointerProperties splitPointerProperties[MAX_POINTERS];
3744 PointerCoords splitPointerCoords[MAX_POINTERS];
3745
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003746 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003747 uint32_t splitPointerCount = 0;
3748
3749 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003750 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003752 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753 uint32_t pointerId = uint32_t(pointerProperties.id);
3754 if (pointerIds.hasBit(pointerId)) {
3755 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3756 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3757 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003758 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759 splitPointerCount += 1;
3760 }
3761 }
3762
3763 if (splitPointerCount != pointerIds.count()) {
3764 // This is bad. We are missing some of the pointers that we expected to deliver.
3765 // Most likely this indicates that we received an ACTION_MOVE events that has
3766 // different pointer ids than we expected based on the previous ACTION_DOWN
3767 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3768 // in this way.
3769 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003770 "we expected there to be %d pointers. This probably means we received "
3771 "a broken sequence of pointer ids from the input device.",
3772 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003773 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774 }
3775
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003776 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003778 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3779 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3781 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003782 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783 uint32_t pointerId = uint32_t(pointerProperties.id);
3784 if (pointerIds.hasBit(pointerId)) {
3785 if (pointerIds.count() == 1) {
3786 // The first/last pointer went down/up.
3787 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003788 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003789 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3790 ? AMOTION_EVENT_ACTION_CANCEL
3791 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792 } else {
3793 // A secondary pointer went down/up.
3794 uint32_t splitPointerIndex = 0;
3795 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3796 splitPointerIndex += 1;
3797 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003798 action = maskedAction |
3799 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800 }
3801 } else {
3802 // An unrelated pointer changed.
3803 action = AMOTION_EVENT_ACTION_MOVE;
3804 }
3805 }
3806
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003807 if (action == AMOTION_EVENT_ACTION_DOWN) {
3808 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3809 "Split motion event has mismatching downTime and eventTime for "
3810 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3811 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3812 }
3813
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003814 int32_t newId = mIdGenerator.nextId();
3815 if (ATRACE_ENABLED()) {
3816 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3817 ") to MotionEvent(id=0x%" PRIx32 ").",
3818 originalMotionEntry.id, newId);
3819 ATRACE_NAME(message.c_str());
3820 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003821 std::unique_ptr<MotionEntry> splitMotionEntry =
3822 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3823 originalMotionEntry.deviceId, originalMotionEntry.source,
3824 originalMotionEntry.displayId,
3825 originalMotionEntry.policyFlags, action,
3826 originalMotionEntry.actionButton,
3827 originalMotionEntry.flags, originalMotionEntry.metaState,
3828 originalMotionEntry.buttonState,
3829 originalMotionEntry.classification,
3830 originalMotionEntry.edgeFlags,
3831 originalMotionEntry.xPrecision,
3832 originalMotionEntry.yPrecision,
3833 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003834 originalMotionEntry.yCursorPosition, splitDownTime,
3835 splitPointerCount, splitPointerProperties,
3836 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003837
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003838 if (originalMotionEntry.injectionState) {
3839 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003840 splitMotionEntry->injectionState->refCount += 1;
3841 }
3842
3843 return splitMotionEntry;
3844}
3845
3846void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003847 if (DEBUG_INBOUND_EVENT_DETAILS) {
3848 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3849 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003850
Antonio Kantekf16f2832021-09-28 04:39:20 +00003851 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003852 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003853 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003855 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3856 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3857 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003858 } // release lock
3859
3860 if (needWake) {
3861 mLooper->wake();
3862 }
3863}
3864
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003865/**
3866 * If one of the meta shortcuts is detected, process them here:
3867 * Meta + Backspace -> generate BACK
3868 * Meta + Enter -> generate HOME
3869 * This will potentially overwrite keyCode and metaState.
3870 */
3871void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003872 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003873 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3874 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3875 if (keyCode == AKEYCODE_DEL) {
3876 newKeyCode = AKEYCODE_BACK;
3877 } else if (keyCode == AKEYCODE_ENTER) {
3878 newKeyCode = AKEYCODE_HOME;
3879 }
3880 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003881 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003882 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003883 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003884 keyCode = newKeyCode;
3885 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3886 }
3887 } else if (action == AKEY_EVENT_ACTION_UP) {
3888 // In order to maintain a consistent stream of up and down events, check to see if the key
3889 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3890 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003891 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003892 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003893 auto replacementIt = mReplacedKeys.find(replacement);
3894 if (replacementIt != mReplacedKeys.end()) {
3895 keyCode = replacementIt->second;
3896 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003897 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3898 }
3899 }
3900}
3901
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003903 if (DEBUG_INBOUND_EVENT_DETAILS) {
3904 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3905 "policyFlags=0x%x, action=0x%x, "
3906 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3907 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3908 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3909 args->downTime);
3910 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003911 if (!validateKeyEvent(args->action)) {
3912 return;
3913 }
3914
3915 uint32_t policyFlags = args->policyFlags;
3916 int32_t flags = args->flags;
3917 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003918 // InputDispatcher tracks and generates key repeats on behalf of
3919 // whatever notifies it, so repeatCount should always be set to 0
3920 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3922 policyFlags |= POLICY_FLAG_VIRTUAL;
3923 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3924 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925 if (policyFlags & POLICY_FLAG_FUNCTION) {
3926 metaState |= AMETA_FUNCTION_ON;
3927 }
3928
3929 policyFlags |= POLICY_FLAG_TRUSTED;
3930
Michael Wright78f24442014-08-06 15:55:28 -07003931 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003932 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003933
Michael Wrightd02c5b62014-02-10 15:10:22 -08003934 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003935 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003936 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3937 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938
Michael Wright2b3c3302018-03-02 17:19:13 +00003939 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003941 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3942 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003943 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003944 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003945
Antonio Kantekf16f2832021-09-28 04:39:20 +00003946 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947 { // acquire lock
3948 mLock.lock();
3949
3950 if (shouldSendKeyToInputFilterLocked(args)) {
3951 mLock.unlock();
3952
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003953 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3955 return; // event was consumed by the filter
3956 }
3957
3958 mLock.lock();
3959 }
3960
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003961 std::unique_ptr<KeyEntry> newEntry =
3962 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3963 args->displayId, policyFlags, args->action, flags,
3964 keyCode, args->scanCode, metaState, repeatCount,
3965 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003967 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968 mLock.unlock();
3969 } // release lock
3970
3971 if (needWake) {
3972 mLooper->wake();
3973 }
3974}
3975
3976bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3977 return mInputFilterEnabled;
3978}
3979
3980void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003981 if (DEBUG_INBOUND_EVENT_DETAILS) {
3982 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3983 "displayId=%" PRId32 ", policyFlags=0x%x, "
3984 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3985 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3986 "yCursorPosition=%f, downTime=%" PRId64,
3987 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3988 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3989 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3990 args->xCursorPosition, args->yCursorPosition, args->downTime);
3991 for (uint32_t i = 0; i < args->pointerCount; i++) {
3992 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3993 "x=%f, y=%f, pressure=%f, size=%f, "
3994 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3995 "orientation=%f",
3996 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3997 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3998 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3999 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4000 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4001 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4002 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4003 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4004 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4005 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4006 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004007 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004008 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4009 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004010 return;
4011 }
4012
4013 uint32_t policyFlags = args->policyFlags;
4014 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004015
4016 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004017 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004018 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4019 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004020 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004021 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004022
Antonio Kantekf16f2832021-09-28 04:39:20 +00004023 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004024 { // acquire lock
4025 mLock.lock();
4026
4027 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004028 ui::Transform displayTransform;
4029 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4030 displayTransform = it->second.transform;
4031 }
4032
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033 mLock.unlock();
4034
4035 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004036 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4037 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004038 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004039 displayTransform, args->xPrecision, args->yPrecision,
4040 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004041 args->downTime, args->eventTime, args->pointerCount,
4042 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004043
4044 policyFlags |= POLICY_FLAG_FILTERED;
4045 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4046 return; // event was consumed by the filter
4047 }
4048
4049 mLock.lock();
4050 }
4051
4052 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004053 std::unique_ptr<MotionEntry> newEntry =
4054 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4055 args->source, args->displayId, policyFlags,
4056 args->action, args->actionButton, args->flags,
4057 args->metaState, args->buttonState,
4058 args->classification, args->edgeFlags,
4059 args->xPrecision, args->yPrecision,
4060 args->xCursorPosition, args->yCursorPosition,
4061 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004062 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004064 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4065 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4066 !mInputFilterEnabled) {
4067 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4068 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4069 }
4070
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004071 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072 mLock.unlock();
4073 } // release lock
4074
4075 if (needWake) {
4076 mLooper->wake();
4077 }
4078}
4079
Chris Yef59a2f42020-10-16 12:55:26 -07004080void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004081 if (DEBUG_INBOUND_EVENT_DETAILS) {
4082 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4083 " sensorType=%s",
4084 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004085 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004086 }
Chris Yef59a2f42020-10-16 12:55:26 -07004087
Antonio Kantekf16f2832021-09-28 04:39:20 +00004088 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004089 { // acquire lock
4090 mLock.lock();
4091
4092 // Just enqueue a new sensor event.
4093 std::unique_ptr<SensorEntry> newEntry =
4094 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4095 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4096 args->sensorType, args->accuracy,
4097 args->accuracyChanged, args->values);
4098
4099 needWake = enqueueInboundEventLocked(std::move(newEntry));
4100 mLock.unlock();
4101 } // release lock
4102
4103 if (needWake) {
4104 mLooper->wake();
4105 }
4106}
4107
Chris Yefb552902021-02-03 17:18:37 -08004108void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004109 if (DEBUG_INBOUND_EVENT_DETAILS) {
4110 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4111 args->deviceId, args->isOn);
4112 }
Chris Yefb552902021-02-03 17:18:37 -08004113 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4114}
4115
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004117 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118}
4119
4120void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004121 if (DEBUG_INBOUND_EVENT_DETAILS) {
4122 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4123 "switchMask=0x%08x",
4124 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4125 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126
4127 uint32_t policyFlags = args->policyFlags;
4128 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004129 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130}
4131
4132void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004133 if (DEBUG_INBOUND_EVENT_DETAILS) {
4134 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4135 args->deviceId);
4136 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137
Antonio Kantekf16f2832021-09-28 04:39:20 +00004138 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004140 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004142 std::unique_ptr<DeviceResetEntry> newEntry =
4143 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4144 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004145 } // release lock
4146
4147 if (needWake) {
4148 mLooper->wake();
4149 }
4150}
4151
Prabir Pradhan7e186182020-11-10 13:56:45 -08004152void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004153 if (DEBUG_INBOUND_EVENT_DETAILS) {
4154 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004155 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004156 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004157
Antonio Kantekf16f2832021-09-28 04:39:20 +00004158 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004159 { // acquire lock
4160 std::scoped_lock _l(mLock);
4161 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004162 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004163 needWake = enqueueInboundEventLocked(std::move(entry));
4164 } // release lock
4165
4166 if (needWake) {
4167 mLooper->wake();
4168 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004169}
4170
Prabir Pradhan5735a322022-04-11 17:23:34 +00004171InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4172 std::optional<int32_t> targetUid,
4173 InputEventInjectionSync syncMode,
4174 std::chrono::milliseconds timeout,
4175 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004176 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004177 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4178 "policyFlags=0x%08x",
4179 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4180 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004181 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004182 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183
Prabir Pradhan5735a322022-04-11 17:23:34 +00004184 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004186 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004187 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4188 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4189 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4190 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4191 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004192 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004193 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004194 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004195 }
4196
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004197 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004199 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004200 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4201 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004202 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004203 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004204 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004205
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004206 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004207 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4208 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4209 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004210 int32_t keyCode = incomingKey.getKeyCode();
4211 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004212 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004213 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004214 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004215 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004216 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4217 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4218 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004220 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4221 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004222 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004223
4224 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4225 android::base::Timer t;
4226 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4227 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4228 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4229 std::to_string(t.duration().count()).c_str());
4230 }
4231 }
4232
4233 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004234 std::unique_ptr<KeyEntry> injectedEntry =
4235 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004236 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004237 incomingKey.getDisplayId(), policyFlags, action,
4238 flags, keyCode, incomingKey.getScanCode(), metaState,
4239 incomingKey.getRepeatCount(),
4240 incomingKey.getDownTime());
4241 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004242 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243 }
4244
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004245 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004246 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004247 const int32_t action = motionEvent.getAction();
4248 const bool isPointerEvent =
4249 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4250 // If a pointer event has no displayId specified, inject it to the default display.
4251 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4252 ? ADISPLAY_ID_DEFAULT
4253 : event->getDisplayId();
4254 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004255 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004256 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004257 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004258 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004259 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004260 }
4261
4262 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004263 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004264 android::base::Timer t;
4265 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4266 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4267 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4268 std::to_string(t.duration().count()).c_str());
4269 }
4270 }
4271
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004272 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4273 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4274 }
4275
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004276 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004277 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4278 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004279 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004280 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4281 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004282 displayId, policyFlags, action, actionButton,
4283 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004284 motionEvent.getButtonState(),
4285 motionEvent.getClassification(),
4286 motionEvent.getEdgeFlags(),
4287 motionEvent.getXPrecision(),
4288 motionEvent.getYPrecision(),
4289 motionEvent.getRawXCursorPosition(),
4290 motionEvent.getRawYCursorPosition(),
4291 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004292 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004293 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004294 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004295 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004296 sampleEventTimes += 1;
4297 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004298 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004299 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4300 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004301 displayId, policyFlags, action, actionButton,
4302 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004303 motionEvent.getButtonState(),
4304 motionEvent.getClassification(),
4305 motionEvent.getEdgeFlags(),
4306 motionEvent.getXPrecision(),
4307 motionEvent.getYPrecision(),
4308 motionEvent.getRawXCursorPosition(),
4309 motionEvent.getRawYCursorPosition(),
4310 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004311 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004312 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004313 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4314 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004315 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004316 }
4317 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004320 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004321 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004322 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323 }
4324
Prabir Pradhan5735a322022-04-11 17:23:34 +00004325 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004326 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 injectionState->injectionIsAsync = true;
4328 }
4329
4330 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004331 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332
4333 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004334 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004335 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004336 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004337 }
4338
4339 mLock.unlock();
4340
4341 if (needWake) {
4342 mLooper->wake();
4343 }
4344
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004345 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004346 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004347 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004349 if (syncMode == InputEventInjectionSync::NONE) {
4350 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351 } else {
4352 for (;;) {
4353 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004354 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355 break;
4356 }
4357
4358 nsecs_t remainingTimeout = endTime - now();
4359 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004360 if (DEBUG_INJECTION) {
4361 ALOGD("injectInputEvent - Timed out waiting for injection result "
4362 "to become available.");
4363 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004364 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365 break;
4366 }
4367
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004368 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 }
4370
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004371 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4372 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004374 if (DEBUG_INJECTION) {
4375 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4376 injectionState->pendingForegroundDispatches);
4377 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378 nsecs_t remainingTimeout = endTime - now();
4379 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004380 if (DEBUG_INJECTION) {
4381 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4382 "dispatches to finish.");
4383 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004384 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385 break;
4386 }
4387
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004388 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389 }
4390 }
4391 }
4392
4393 injectionState->release();
4394 } // release lock
4395
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004396 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004397 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004398 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399
4400 return injectionResult;
4401}
4402
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004403std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004404 std::array<uint8_t, 32> calculatedHmac;
4405 std::unique_ptr<VerifiedInputEvent> result;
4406 switch (event.getType()) {
4407 case AINPUT_EVENT_TYPE_KEY: {
4408 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4409 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4410 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004411 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004412 break;
4413 }
4414 case AINPUT_EVENT_TYPE_MOTION: {
4415 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4416 VerifiedMotionEvent verifiedMotionEvent =
4417 verifiedMotionEventFromMotionEvent(motionEvent);
4418 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004419 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004420 break;
4421 }
4422 default: {
4423 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4424 return nullptr;
4425 }
4426 }
4427 if (calculatedHmac == INVALID_HMAC) {
4428 return nullptr;
4429 }
4430 if (calculatedHmac != event.getHmac()) {
4431 return nullptr;
4432 }
4433 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004434}
4435
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004436void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004437 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004438 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004440 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004441 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004442 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004443
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004444 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004445 // Log the outcome since the injector did not wait for the injection result.
4446 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004447 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004448 ALOGV("Asynchronous input event injection succeeded.");
4449 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004450 case InputEventInjectionResult::TARGET_MISMATCH:
4451 ALOGV("Asynchronous input event injection target mismatch.");
4452 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004453 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004454 ALOGW("Asynchronous input event injection failed.");
4455 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004456 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004457 ALOGW("Asynchronous input event injection timed out.");
4458 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004459 case InputEventInjectionResult::PENDING:
4460 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4461 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004462 }
4463 }
4464
4465 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004466 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004467 }
4468}
4469
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004470void InputDispatcher::transformMotionEntryForInjectionLocked(
4471 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004472 // Input injection works in the logical display coordinate space, but the input pipeline works
4473 // display space, so we need to transform the injected events accordingly.
4474 const auto it = mDisplayInfos.find(entry.displayId);
4475 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004476 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004477
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004478 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4479 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4480 const vec2 cursor =
4481 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4482 {entry.xCursorPosition, entry.yCursorPosition});
4483 entry.xCursorPosition = cursor.x;
4484 entry.yCursorPosition = cursor.y;
4485 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004486 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004487 entry.pointerCoords[i] =
4488 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4489 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004490 }
4491}
4492
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004493void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4494 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495 if (injectionState) {
4496 injectionState->pendingForegroundDispatches += 1;
4497 }
4498}
4499
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004500void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4501 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004502 if (injectionState) {
4503 injectionState->pendingForegroundDispatches -= 1;
4504
4505 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004506 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004507 }
4508 }
4509}
4510
chaviw98318de2021-05-19 16:45:23 -05004511const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004512 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004513 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004514 auto it = mWindowHandlesByDisplay.find(displayId);
4515 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004516}
4517
chaviw98318de2021-05-19 16:45:23 -05004518sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004519 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004520 if (windowHandleToken == nullptr) {
4521 return nullptr;
4522 }
4523
Arthur Hungb92218b2018-08-14 12:00:21 +08004524 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004525 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4526 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004527 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004528 return windowHandle;
4529 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004530 }
4531 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004532 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004533}
4534
chaviw98318de2021-05-19 16:45:23 -05004535sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4536 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004537 if (windowHandleToken == nullptr) {
4538 return nullptr;
4539 }
4540
chaviw98318de2021-05-19 16:45:23 -05004541 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004542 if (windowHandle->getToken() == windowHandleToken) {
4543 return windowHandle;
4544 }
4545 }
4546 return nullptr;
4547}
4548
chaviw98318de2021-05-19 16:45:23 -05004549sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4550 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004551 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004552 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4553 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004554 if (handle->getId() == windowHandle->getId() &&
4555 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004556 if (windowHandle->getInfo()->displayId != it.first) {
4557 ALOGE("Found window %s in display %" PRId32
4558 ", but it should belong to display %" PRId32,
4559 windowHandle->getName().c_str(), it.first,
4560 windowHandle->getInfo()->displayId);
4561 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004562 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004563 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004564 }
4565 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004566 return nullptr;
4567}
4568
chaviw98318de2021-05-19 16:45:23 -05004569sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004570 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4571 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572}
4573
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004574bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4575 const MotionEntry& motionEntry) const {
4576 const WindowInfo& info = *window->getInfo();
4577
4578 // Skip spy window targets that are not valid for targeted injection.
4579 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004580 return false;
4581 }
4582
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004583 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4584 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4585 return false;
4586 }
4587
4588 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4589 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4590 window->getName().c_str());
4591 return false;
4592 }
4593
4594 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004595 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004596 ALOGW("Not sending touch to %s because there's no corresponding connection",
4597 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004598 return false;
4599 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004600
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004601 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004602 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004603 return false;
4604 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004605
4606 // Drop events that can't be trusted due to occlusion
4607 const auto [x, y] = resolveTouchedPosition(motionEntry);
4608 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4609 if (!isTouchTrustedLocked(occlusionInfo)) {
4610 if (DEBUG_TOUCH_OCCLUSION) {
4611 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4612 for (const auto& log : occlusionInfo.debugInfo) {
4613 ALOGD("%s", log.c_str());
4614 }
4615 }
4616 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4617 occlusionInfo.obscuringUid);
4618 return false;
4619 }
4620
4621 // Drop touch events if requested by input feature
4622 if (shouldDropInput(motionEntry, window)) {
4623 return false;
4624 }
4625
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004626 return true;
4627}
4628
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004629std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4630 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004631 auto connectionIt = mConnectionsByToken.find(token);
4632 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004633 return nullptr;
4634 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004635 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004636}
4637
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004638void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004639 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4640 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004641 // Remove all handles on a display if there are no windows left.
4642 mWindowHandlesByDisplay.erase(displayId);
4643 return;
4644 }
4645
4646 // Since we compare the pointer of input window handles across window updates, we need
4647 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004648 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4649 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4650 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004651 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004652 }
4653
chaviw98318de2021-05-19 16:45:23 -05004654 std::vector<sp<WindowInfoHandle>> newHandles;
4655 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004656 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004657 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004658 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004659 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004660 const bool canReceiveInput =
4661 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4662 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004663 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004664 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004665 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004666 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004667 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004668 }
4669
4670 if (info->displayId != displayId) {
4671 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4672 handle->getName().c_str(), displayId, info->displayId);
4673 continue;
4674 }
4675
Robert Carredd13602020-04-13 17:24:34 -07004676 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4677 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004678 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004679 oldHandle->updateFrom(handle);
4680 newHandles.push_back(oldHandle);
4681 } else {
4682 newHandles.push_back(handle);
4683 }
4684 }
4685
4686 // Insert or replace
4687 mWindowHandlesByDisplay[displayId] = newHandles;
4688}
4689
Arthur Hung72d8dc32020-03-28 00:48:39 +00004690void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004691 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004692 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004693 { // acquire lock
4694 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004695 for (const auto& [displayId, handles] : handlesPerDisplay) {
4696 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004697 }
4698 }
4699 // Wake up poll loop since it may need to make new input dispatching choices.
4700 mLooper->wake();
4701}
4702
Arthur Hungb92218b2018-08-14 12:00:21 +08004703/**
4704 * Called from InputManagerService, update window handle list by displayId that can receive input.
4705 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4706 * If set an empty list, remove all handles from the specific display.
4707 * For focused handle, check if need to change and send a cancel event to previous one.
4708 * For removed handle, check if need to send a cancel event if already in touch.
4709 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004710void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004711 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004712 if (DEBUG_FOCUS) {
4713 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004714 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004715 windowList += iwh->getName() + " ";
4716 }
4717 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4718 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719
Prabir Pradhand65552b2021-10-07 11:23:50 -07004720 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004721 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004722 const WindowInfo& info = *window->getInfo();
4723
4724 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004725 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004726 if (noInputWindow && window->getToken() != nullptr) {
4727 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4728 window->getName().c_str());
4729 window->releaseChannel();
4730 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004731
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004732 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004733 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4734 !info.inputConfig.test(
4735 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004736 "%s has feature SPY, but is not a trusted overlay.",
4737 window->getName().c_str());
4738
Prabir Pradhand65552b2021-10-07 11:23:50 -07004739 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004740 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4741 !info.inputConfig.test(
4742 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004743 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4744 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004745 }
4746
Arthur Hung72d8dc32020-03-28 00:48:39 +00004747 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004748 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004749
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004750 // Save the old windows' orientation by ID before it gets updated.
4751 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004752 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004753 oldWindowOrientations.emplace(handle->getId(),
4754 handle->getInfo()->transform.getOrientation());
4755 }
4756
chaviw98318de2021-05-19 16:45:23 -05004757 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004758
chaviw98318de2021-05-19 16:45:23 -05004759 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004760 if (mLastHoverWindowHandle &&
4761 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4762 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004763 mLastHoverWindowHandle = nullptr;
4764 }
4765
Vishnu Nairc519ff72021-01-21 08:23:08 -08004766 std::optional<FocusResolver::FocusChanges> changes =
4767 mFocusResolver.setInputWindows(displayId, windowHandles);
4768 if (changes) {
4769 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004771
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004772 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4773 mTouchStatesByDisplay.find(displayId);
4774 if (stateIt != mTouchStatesByDisplay.end()) {
4775 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004776 for (size_t i = 0; i < state.windows.size();) {
4777 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004778 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004779 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004780 ALOGD("Touched window was removed: %s in display %" PRId32,
4781 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004782 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004783 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004784 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4785 if (touchedInputChannel != nullptr) {
4786 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4787 "touched window was removed");
4788 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004789 // Since we are about to drop the touch, cancel the events for the wallpaper as
4790 // well.
4791 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004792 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4793 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004794 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4795 if (wallpaper != nullptr) {
4796 sp<Connection> wallpaperConnection =
4797 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004798 if (wallpaperConnection != nullptr) {
4799 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4800 options);
4801 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004802 }
4803 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004804 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004805 state.windows.erase(state.windows.begin() + i);
4806 } else {
4807 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808 }
4809 }
arthurhungb89ccb02020-12-30 16:19:01 +08004810
arthurhung6d4bed92021-03-17 11:59:33 +08004811 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004812 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004813 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004814 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004815 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004816 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4817 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004818 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004819 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004820 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004821
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004822 // Determine if the orientation of any of the input windows have changed, and cancel all
4823 // pointer events if necessary.
4824 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4825 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4826 if (newWindowHandle != nullptr &&
4827 newWindowHandle->getInfo()->transform.getOrientation() !=
4828 oldWindowOrientations[oldWindowHandle->getId()]) {
4829 std::shared_ptr<InputChannel> inputChannel =
4830 getInputChannelLocked(newWindowHandle->getToken());
4831 if (inputChannel != nullptr) {
4832 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4833 "touched window's orientation changed");
4834 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004835 }
4836 }
4837 }
4838
Arthur Hung72d8dc32020-03-28 00:48:39 +00004839 // Release information for windows that are no longer present.
4840 // This ensures that unused input channels are released promptly.
4841 // Otherwise, they might stick around until the window handle is destroyed
4842 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004843 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004844 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004845 if (DEBUG_FOCUS) {
4846 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004847 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004848 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004849 }
chaviw291d88a2019-02-14 10:33:58 -08004850 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851}
4852
4853void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004854 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004855 if (DEBUG_FOCUS) {
4856 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4857 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4858 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004859 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004860 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004861 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862 } // release lock
4863
4864 // Wake up poll loop since it may need to make new input dispatching choices.
4865 mLooper->wake();
4866}
4867
Vishnu Nair599f1412021-06-21 10:39:58 -07004868void InputDispatcher::setFocusedApplicationLocked(
4869 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4870 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4871 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4872
4873 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4874 return; // This application is already focused. No need to wake up or change anything.
4875 }
4876
4877 // Set the new application handle.
4878 if (inputApplicationHandle != nullptr) {
4879 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4880 } else {
4881 mFocusedApplicationHandlesByDisplay.erase(displayId);
4882 }
4883
4884 // No matter what the old focused application was, stop waiting on it because it is
4885 // no longer focused.
4886 resetNoFocusedWindowTimeoutLocked();
4887}
4888
Tiger Huang721e26f2018-07-24 22:26:19 +08004889/**
4890 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4891 * the display not specified.
4892 *
4893 * We track any unreleased events for each window. If a window loses the ability to receive the
4894 * released event, we will send a cancel event to it. So when the focused display is changed, we
4895 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4896 * display. The display-specified events won't be affected.
4897 */
4898void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004899 if (DEBUG_FOCUS) {
4900 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4901 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004902 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004903 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004904
4905 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004906 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004907 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004908 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004909 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004910 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004911 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004912 CancelationOptions
4913 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4914 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004915 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004916 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4917 }
4918 }
4919 mFocusedDisplayId = displayId;
4920
Chris Ye3c2d6f52020-08-09 10:39:48 -07004921 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004922 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004923 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004924
Vishnu Nairad321cd2020-08-20 16:40:21 -07004925 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004926 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004927 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004928 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004929 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004930 }
4931 }
4932 }
4933
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004934 if (DEBUG_FOCUS) {
4935 logDispatchStateLocked();
4936 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004937 } // release lock
4938
4939 // Wake up poll loop since it may need to make new input dispatching choices.
4940 mLooper->wake();
4941}
4942
Michael Wrightd02c5b62014-02-10 15:10:22 -08004943void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004944 if (DEBUG_FOCUS) {
4945 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4946 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004947
4948 bool changed;
4949 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004950 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004951
4952 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4953 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004954 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955 }
4956
4957 if (mDispatchEnabled && !enabled) {
4958 resetAndDropEverythingLocked("dispatcher is being disabled");
4959 }
4960
4961 mDispatchEnabled = enabled;
4962 mDispatchFrozen = frozen;
4963 changed = true;
4964 } else {
4965 changed = false;
4966 }
4967
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004968 if (DEBUG_FOCUS) {
4969 logDispatchStateLocked();
4970 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004971 } // release lock
4972
4973 if (changed) {
4974 // Wake up poll loop since it may need to make new input dispatching choices.
4975 mLooper->wake();
4976 }
4977}
4978
4979void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004980 if (DEBUG_FOCUS) {
4981 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004983
4984 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004985 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004986
4987 if (mInputFilterEnabled == enabled) {
4988 return;
4989 }
4990
4991 mInputFilterEnabled = enabled;
4992 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4993 } // release lock
4994
4995 // Wake up poll loop since there might be work to do to drop everything.
4996 mLooper->wake();
4997}
4998
Antonio Kanteka042c022022-07-06 16:51:07 -07004999bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5000 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005001 bool needWake = false;
5002 {
5003 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005004 ALOGD_IF(DEBUG_TOUCH_MODE,
5005 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5006 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5007 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5008 mTouchModePerDisplay.count(displayId) == 0
5009 ? "not set"
5010 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5011
5012 // TODO(b/198499018): Ensure that WM can guarantee that touch mode is properly set when
5013 // display is created.
5014 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5015 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005016 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005017 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005018 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005019 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5020 !recentWindowsAreOwnedByLocked(pid, uid)) {
5021 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5022 "window nor none of the previously interacted window",
5023 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005024 return false;
5025 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005026 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005027 mTouchModePerDisplay[displayId] = inTouchMode;
5028 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5029 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005030 needWake = enqueueInboundEventLocked(std::move(entry));
5031 } // release lock
5032
5033 if (needWake) {
5034 mLooper->wake();
5035 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005036 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005037}
5038
Antonio Kantek48710e42022-03-24 14:19:30 -07005039bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5040 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5041 if (focusedToken == nullptr) {
5042 return false;
5043 }
5044 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5045 return isWindowOwnedBy(windowHandle, pid, uid);
5046}
5047
5048bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5049 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5050 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5051 const sp<WindowInfoHandle> windowHandle =
5052 getWindowHandleLocked(connectionToken);
5053 return isWindowOwnedBy(windowHandle, pid, uid);
5054 }) != mInteractionConnectionTokens.end();
5055}
5056
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005057void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5058 if (opacity < 0 || opacity > 1) {
5059 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5060 return;
5061 }
5062
5063 std::scoped_lock lock(mLock);
5064 mMaximumObscuringOpacityForTouch = opacity;
5065}
5066
Arthur Hungabbb9d82021-09-01 14:52:30 +00005067std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
5068 const sp<IBinder>& token) {
5069 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5070 for (TouchedWindow& w : state.windows) {
5071 if (w.windowHandle->getToken() == token) {
5072 return std::make_pair(&state, &w);
5073 }
5074 }
5075 }
5076 return std::make_pair(nullptr, nullptr);
5077}
5078
arthurhungb89ccb02020-12-30 16:19:01 +08005079bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5080 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005081 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005082 if (DEBUG_FOCUS) {
5083 ALOGD("Trivial transfer to same window.");
5084 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005085 return true;
5086 }
5087
Michael Wrightd02c5b62014-02-10 15:10:22 -08005088 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005089 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005090
Arthur Hungabbb9d82021-09-01 14:52:30 +00005091 // Find the target touch state and touched window by fromToken.
5092 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5093 if (state == nullptr || touchedWindow == nullptr) {
5094 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005095 return false;
5096 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005097
5098 const int32_t displayId = state->displayId;
5099 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5100 if (toWindowHandle == nullptr) {
5101 ALOGW("Cannot transfer focus because to window not found.");
5102 return false;
5103 }
5104
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005105 if (DEBUG_FOCUS) {
5106 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005107 touchedWindow->windowHandle->getName().c_str(),
5108 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005109 }
5110
Arthur Hungabbb9d82021-09-01 14:52:30 +00005111 // Erase old window.
5112 int32_t oldTargetFlags = touchedWindow->targetFlags;
5113 BitSet32 pointerIds = touchedWindow->pointerIds;
5114 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005115
Arthur Hungabbb9d82021-09-01 14:52:30 +00005116 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005117 nsecs_t downTimeInTarget = now();
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005118 int32_t newTargetFlags =
5119 oldTargetFlags & (InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
5120 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
5121 newTargetFlags |= InputTarget::FLAG_FOREGROUND;
5122 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005123 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124
Arthur Hungabbb9d82021-09-01 14:52:30 +00005125 // Store the dragging window.
5126 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005127 if (pointerIds.count() != 1) {
5128 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5129 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005130 return false;
5131 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005132 // Track the pointer id for drag window and generate the drag state.
5133 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005134 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005135 }
5136
Arthur Hungabbb9d82021-09-01 14:52:30 +00005137 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005138 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5139 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005140 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005141 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005142 CancelationOptions
5143 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5144 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005146 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005147 }
5148
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005149 if (DEBUG_FOCUS) {
5150 logDispatchStateLocked();
5151 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005152 } // release lock
5153
5154 // Wake up poll loop since it may need to make new input dispatching choices.
5155 mLooper->wake();
5156 return true;
5157}
5158
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005159/**
5160 * Get the touched foreground window on the given display.
5161 * Return null if there are no windows touched on that display, or if more than one foreground
5162 * window is being touched.
5163 */
5164sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5165 auto stateIt = mTouchStatesByDisplay.find(displayId);
5166 if (stateIt == mTouchStatesByDisplay.end()) {
5167 ALOGI("No touch state on display %" PRId32, displayId);
5168 return nullptr;
5169 }
5170
5171 const TouchState& state = stateIt->second;
5172 sp<WindowInfoHandle> touchedForegroundWindow;
5173 // If multiple foreground windows are touched, return nullptr
5174 for (const TouchedWindow& window : state.windows) {
5175 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5176 if (touchedForegroundWindow != nullptr) {
5177 ALOGI("Two or more foreground windows: %s and %s",
5178 touchedForegroundWindow->getName().c_str(),
5179 window.windowHandle->getName().c_str());
5180 return nullptr;
5181 }
5182 touchedForegroundWindow = window.windowHandle;
5183 }
5184 }
5185 return touchedForegroundWindow;
5186}
5187
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005188// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005189bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005190 sp<IBinder> fromToken;
5191 { // acquire lock
5192 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005193 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005194 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005195 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5196 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005197 return false;
5198 }
5199
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005200 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5201 if (from == nullptr) {
5202 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5203 return false;
5204 }
5205
5206 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005207 } // release lock
5208
5209 return transferTouchFocus(fromToken, destChannelToken);
5210}
5211
Michael Wrightd02c5b62014-02-10 15:10:22 -08005212void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005213 if (DEBUG_FOCUS) {
5214 ALOGD("Resetting and dropping all events (%s).", reason);
5215 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005216
5217 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5218 synthesizeCancelationEventsForAllConnectionsLocked(options);
5219
5220 resetKeyRepeatLocked();
5221 releasePendingEventLocked();
5222 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005223 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005224
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005225 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005226 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005227 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005228 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005229}
5230
5231void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005232 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005233 dumpDispatchStateLocked(dump);
5234
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005235 std::istringstream stream(dump);
5236 std::string line;
5237
5238 while (std::getline(stream, line, '\n')) {
5239 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005240 }
5241}
5242
Prabir Pradhan99987712020-11-10 18:43:05 -08005243std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5244 std::string dump;
5245
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005246 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5247 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005248
5249 std::string windowName = "None";
5250 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005251 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005252 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5253 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5254 : "token has capture without window";
5255 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005256 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005257
5258 return dump;
5259}
5260
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005261void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005262 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5263 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5264 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005265 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266
Tiger Huang721e26f2018-07-24 22:26:19 +08005267 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5268 dump += StringPrintf(INDENT "FocusedApplications:\n");
5269 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5270 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005271 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005272 const std::chrono::duration timeout =
5273 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005274 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005275 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005276 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005277 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005278 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005279 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005280 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005281
Vishnu Nairc519ff72021-01-21 08:23:08 -08005282 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005283 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005284
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005285 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005286 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005287 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5288 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005289 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005290 state.displayId, toString(state.down), toString(state.split),
5291 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005292 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005293 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005294 for (size_t i = 0; i < state.windows.size(); i++) {
5295 const TouchedWindow& touchedWindow = state.windows[i];
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005296 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, "
5297 "targetFlags=0x%x, firstDownTimeInTarget=%" PRId64
5298 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005299 i, touchedWindow.windowHandle->getName().c_str(),
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005300 touchedWindow.pointerIds.value, touchedWindow.targetFlags,
5301 ns2ms(touchedWindow.firstDownTimeInTarget.value_or(0)));
Jeff Brownf086ddb2014-02-11 14:28:48 -08005302 }
5303 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005304 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005305 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005306 }
5307 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005308 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005309 }
5310
arthurhung6d4bed92021-03-17 11:59:33 +08005311 if (mDragState) {
5312 dump += StringPrintf(INDENT "DragState:\n");
5313 mDragState->dump(dump, INDENT2);
5314 }
5315
Arthur Hungb92218b2018-08-14 12:00:21 +08005316 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005317 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5318 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5319 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5320 const auto& displayInfo = it->second;
5321 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5322 displayInfo.logicalHeight);
5323 displayInfo.transform.dump(dump, "transform", INDENT4);
5324 } else {
5325 dump += INDENT2 "No DisplayInfo found!\n";
5326 }
5327
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005328 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005329 dump += INDENT2 "Windows:\n";
5330 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005331 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5332 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005333
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005334 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005335 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005336 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005337 "applicationInfo.name=%s, "
5338 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005339 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005340 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005341 windowInfo->displayId,
5342 windowInfo->inputConfig.string().c_str(),
5343 windowInfo->alpha, windowInfo->frameLeft,
5344 windowInfo->frameTop, windowInfo->frameRight,
5345 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005346 windowInfo->applicationInfo.name.c_str(),
5347 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005348 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005349 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005350 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005351 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005352 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005353 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005354 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005355 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005356 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005357 }
5358 } else {
5359 dump += INDENT2 "Windows: <none>\n";
5360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005361 }
5362 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005363 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005364 }
5365
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005366 if (!mGlobalMonitorsByDisplay.empty()) {
5367 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5368 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005369 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005371 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005372 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005373 }
5374
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005375 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005376
5377 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005378 if (!mRecentQueue.empty()) {
5379 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005380 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005381 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005382 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005383 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005384 }
5385 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005386 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005387 }
5388
5389 // Dump event currently being dispatched.
5390 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005391 dump += INDENT "PendingEvent:\n";
5392 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005393 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005394 dump += StringPrintf(", age=%" PRId64 "ms\n",
5395 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005396 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005397 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005398 }
5399
5400 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005401 if (!mInboundQueue.empty()) {
5402 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005403 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005404 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005405 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005406 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005407 }
5408 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005409 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410 }
5411
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005412 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005413 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005414 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5415 const KeyReplacement& replacement = pair.first;
5416 int32_t newKeyCode = pair.second;
5417 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005418 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005419 }
5420 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005421 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005422 }
5423
Prabir Pradhancef936d2021-07-21 16:17:52 +00005424 if (!mCommandQueue.empty()) {
5425 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5426 } else {
5427 dump += INDENT "CommandQueue: <empty>\n";
5428 }
5429
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005430 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005431 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005432 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005433 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005434 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005435 connection->inputChannel->getFd().get(),
5436 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005437 connection->getWindowName().c_str(),
5438 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005439 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005440
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005441 if (!connection->outboundQueue.empty()) {
5442 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5443 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005444 dump += dumpQueue(connection->outboundQueue, currentTime);
5445
Michael Wrightd02c5b62014-02-10 15:10:22 -08005446 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005447 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005448 }
5449
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005450 if (!connection->waitQueue.empty()) {
5451 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5452 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005453 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005454 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005455 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005456 }
5457 }
5458 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005459 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460 }
5461
5462 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005463 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5464 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005465 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005466 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005467 }
5468
Antonio Kantek15beb512022-06-13 22:35:41 +00005469 if (!mTouchModePerDisplay.empty()) {
5470 dump += INDENT "TouchModePerDisplay:\n";
5471 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5472 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5473 std::to_string(touchMode).c_str());
5474 }
5475 } else {
5476 dump += INDENT "TouchModePerDisplay: <none>\n";
5477 }
5478
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005479 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005480 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5481 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5482 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005483 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005484 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485}
5486
Michael Wright3dd60e22019-03-27 22:06:44 +00005487void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5488 const size_t numMonitors = monitors.size();
5489 for (size_t i = 0; i < numMonitors; i++) {
5490 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005491 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005492 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5493 dump += "\n";
5494 }
5495}
5496
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005497class LooperEventCallback : public LooperCallback {
5498public:
5499 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5500 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5501
5502private:
5503 std::function<int(int events)> mCallback;
5504};
5505
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005506Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005507 if (DEBUG_CHANNEL_CREATION) {
5508 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005510
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005511 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005512 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005513 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005514
5515 if (result) {
5516 return base::Error(result) << "Failed to open input channel pair with name " << name;
5517 }
5518
Michael Wrightd02c5b62014-02-10 15:10:22 -08005519 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005520 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005521 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005522 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005523 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005524 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005525
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005526 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5527 ALOGE("Created a new connection, but the token %p is already known", token.get());
5528 }
5529 mConnectionsByToken.emplace(token, connection);
5530
5531 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5532 this, std::placeholders::_1, token);
5533
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005534 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5535 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005536 } // release lock
5537
5538 // Wake the looper because some connections have changed.
5539 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005540 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005541}
5542
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005543Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005544 const std::string& name,
5545 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005546 std::shared_ptr<InputChannel> serverChannel;
5547 std::unique_ptr<InputChannel> clientChannel;
5548 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5549 if (result) {
5550 return base::Error(result) << "Failed to open input channel pair with name " << name;
5551 }
5552
Michael Wright3dd60e22019-03-27 22:06:44 +00005553 { // acquire lock
5554 std::scoped_lock _l(mLock);
5555
5556 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005557 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5558 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005559 }
5560
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005561 sp<Connection> connection =
5562 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005563 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005564 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005565
5566 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5567 ALOGE("Created a new connection, but the token %p is already known", token.get());
5568 }
5569 mConnectionsByToken.emplace(token, connection);
5570 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5571 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005572
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005573 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005574
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005575 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5576 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005577 }
Garfield Tan15601662020-09-22 15:32:38 -07005578
Michael Wright3dd60e22019-03-27 22:06:44 +00005579 // Wake the looper because some connections have changed.
5580 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005581 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005582}
5583
Garfield Tan15601662020-09-22 15:32:38 -07005584status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005585 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005586 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005587
Garfield Tan15601662020-09-22 15:32:38 -07005588 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005589 if (status) {
5590 return status;
5591 }
5592 } // release lock
5593
5594 // Wake the poll loop because removing the connection may have changed the current
5595 // synchronization state.
5596 mLooper->wake();
5597 return OK;
5598}
5599
Garfield Tan15601662020-09-22 15:32:38 -07005600status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5601 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005602 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005603 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005604 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005605 return BAD_VALUE;
5606 }
5607
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005608 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005609
Michael Wrightd02c5b62014-02-10 15:10:22 -08005610 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005611 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005612 }
5613
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005614 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005615
5616 nsecs_t currentTime = now();
5617 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5618
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005619 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005620 return OK;
5621}
5622
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005623void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005624 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5625 auto& [displayId, monitors] = *it;
5626 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5627 return monitor.inputChannel->getConnectionToken() == connectionToken;
5628 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005629
Michael Wright3dd60e22019-03-27 22:06:44 +00005630 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005631 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005632 } else {
5633 ++it;
5634 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005635 }
5636}
5637
Michael Wright3dd60e22019-03-27 22:06:44 +00005638status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005639 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005640 return pilferPointersLocked(token);
5641}
Michael Wright3dd60e22019-03-27 22:06:44 +00005642
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005643status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005644 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5645 if (!requestingChannel) {
5646 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5647 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005648 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005649
5650 auto [statePtr, windowPtr] = findTouchStateAndWindowLocked(token);
5651 if (statePtr == nullptr || windowPtr == nullptr || !statePtr->down) {
5652 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5653 " Ignoring.");
5654 return BAD_VALUE;
5655 }
5656
5657 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005658 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005659 // Send cancel events to all the input channels we're stealing from.
5660 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5661 "input channel stole pointer stream");
5662 options.deviceId = state.deviceId;
5663 options.displayId = state.displayId;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005664 if (state.split) {
5665 // If split pointers then selectively cancel pointers otherwise cancel all pointers
5666 options.pointerIds = window.pointerIds;
5667 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005668 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005669 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005670 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005671 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005672 if (channel != nullptr && channel->getConnectionToken() != token) {
5673 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5674 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5675 canceledWindows += channel->getName();
5676 }
5677 }
5678 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5679 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5680 canceledWindows.c_str());
5681
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005682 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005683 // This only blocks relevant pointers to be sent to other windows
5684 window.isPilferingPointers = true;
5685
5686 if (state.split) {
5687 state.cancelPointersForWindowsExcept(window.pointerIds, token);
5688 } else {
5689 state.filterWindowsExcept(token);
5690 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005691 return OK;
5692}
5693
Prabir Pradhan99987712020-11-10 18:43:05 -08005694void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5695 { // acquire lock
5696 std::scoped_lock _l(mLock);
5697 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005698 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005699 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5700 windowHandle != nullptr ? windowHandle->getName().c_str()
5701 : "token without window");
5702 }
5703
Vishnu Nairc519ff72021-01-21 08:23:08 -08005704 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005705 if (focusedToken != windowToken) {
5706 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5707 enabled ? "enable" : "disable");
5708 return;
5709 }
5710
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005711 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005712 ALOGW("Ignoring request to %s Pointer Capture: "
5713 "window has %s requested pointer capture.",
5714 enabled ? "enable" : "disable", enabled ? "already" : "not");
5715 return;
5716 }
5717
Christine Franksb768bb42021-11-29 12:11:31 -08005718 if (enabled) {
5719 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5720 mIneligibleDisplaysForPointerCapture.end(),
5721 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5722 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5723 return;
5724 }
5725 }
5726
Prabir Pradhan99987712020-11-10 18:43:05 -08005727 setPointerCaptureLocked(enabled);
5728 } // release lock
5729
5730 // Wake the thread to process command entries.
5731 mLooper->wake();
5732}
5733
Christine Franksb768bb42021-11-29 12:11:31 -08005734void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5735 { // acquire lock
5736 std::scoped_lock _l(mLock);
5737 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5738 if (!isEligible) {
5739 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5740 }
5741 } // release lock
5742}
5743
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005744std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5745 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005746 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005747 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005748 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005749 }
5750 }
5751 }
5752 return std::nullopt;
5753}
5754
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005755sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005756 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005757 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005758 }
5759
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005760 for (const auto& [token, connection] : mConnectionsByToken) {
5761 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005762 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005763 }
5764 }
Robert Carr4e670e52018-08-15 13:26:12 -07005765
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005766 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005767}
5768
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005769std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5770 sp<Connection> connection = getConnectionLocked(connectionToken);
5771 if (connection == nullptr) {
5772 return "<nullptr>";
5773 }
5774 return connection->getInputChannelName();
5775}
5776
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005777void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005778 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005779 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005780}
5781
Prabir Pradhancef936d2021-07-21 16:17:52 +00005782void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5783 const sp<Connection>& connection, uint32_t seq,
5784 bool handled, nsecs_t consumeTime) {
5785 // Handle post-event policy actions.
5786 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5787 if (dispatchEntryIt == connection->waitQueue.end()) {
5788 return;
5789 }
5790 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5791 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5792 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5793 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5794 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5795 }
5796 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5797 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5798 connection->inputChannel->getConnectionToken(),
5799 dispatchEntry->deliveryTime, consumeTime, finishTime);
5800 }
5801
5802 bool restartEvent;
5803 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5804 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5805 restartEvent =
5806 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5807 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5808 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5809 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5810 handled);
5811 } else {
5812 restartEvent = false;
5813 }
5814
5815 // Dequeue the event and start the next cycle.
5816 // Because the lock might have been released, it is possible that the
5817 // contents of the wait queue to have been drained, so we need to double-check
5818 // a few things.
5819 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5820 if (dispatchEntryIt != connection->waitQueue.end()) {
5821 dispatchEntry = *dispatchEntryIt;
5822 connection->waitQueue.erase(dispatchEntryIt);
5823 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5824 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5825 if (!connection->responsive) {
5826 connection->responsive = isConnectionResponsive(*connection);
5827 if (connection->responsive) {
5828 // The connection was unresponsive, and now it's responsive.
5829 processConnectionResponsiveLocked(*connection);
5830 }
5831 }
5832 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005833 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005834 connection->outboundQueue.push_front(dispatchEntry);
5835 traceOutboundQueueLength(*connection);
5836 } else {
5837 releaseDispatchEntry(dispatchEntry);
5838 }
5839 }
5840
5841 // Start the next dispatch cycle for this connection.
5842 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005843}
5844
Prabir Pradhancef936d2021-07-21 16:17:52 +00005845void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5846 const sp<IBinder>& newToken) {
5847 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5848 scoped_unlock unlock(mLock);
5849 mPolicy->notifyFocusChanged(oldToken, newToken);
5850 };
5851 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005852}
5853
Prabir Pradhancef936d2021-07-21 16:17:52 +00005854void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5855 auto command = [this, token, x, y]() REQUIRES(mLock) {
5856 scoped_unlock unlock(mLock);
5857 mPolicy->notifyDropWindow(token, x, y);
5858 };
5859 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005860}
5861
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005862void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5863 if (connection == nullptr) {
5864 LOG_ALWAYS_FATAL("Caller must check for nullness");
5865 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005866 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5867 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005868 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005869 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005870 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005871 return;
5872 }
5873 /**
5874 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5875 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5876 * has changed. This could cause newer entries to time out before the already dispatched
5877 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5878 * processes the events linearly. So providing information about the oldest entry seems to be
5879 * most useful.
5880 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005881 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005882 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5883 std::string reason =
5884 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005885 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005886 ns2ms(currentWait),
5887 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005888 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005889 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005890
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005891 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5892
5893 // Stop waking up for events on this connection, it is already unresponsive
5894 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005895}
5896
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005897void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5898 std::string reason =
5899 StringPrintf("%s does not have a focused window", application->getName().c_str());
5900 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005901
Prabir Pradhancef936d2021-07-21 16:17:52 +00005902 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5903 scoped_unlock unlock(mLock);
5904 mPolicy->notifyNoFocusedWindowAnr(application);
5905 };
5906 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005907}
5908
chaviw98318de2021-05-19 16:45:23 -05005909void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005910 const std::string& reason) {
5911 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5912 updateLastAnrStateLocked(windowLabel, reason);
5913}
5914
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005915void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5916 const std::string& reason) {
5917 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005918 updateLastAnrStateLocked(windowLabel, reason);
5919}
5920
5921void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5922 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005923 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005924 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005925 struct tm tm;
5926 localtime_r(&t, &tm);
5927 char timestr[64];
5928 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005929 mLastAnrState.clear();
5930 mLastAnrState += INDENT "ANR:\n";
5931 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005932 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5933 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005934 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005935}
5936
Prabir Pradhancef936d2021-07-21 16:17:52 +00005937void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5938 KeyEntry& entry) {
5939 const KeyEvent event = createKeyEvent(entry);
5940 nsecs_t delay = 0;
5941 { // release lock
5942 scoped_unlock unlock(mLock);
5943 android::base::Timer t;
5944 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5945 entry.policyFlags);
5946 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5947 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5948 std::to_string(t.duration().count()).c_str());
5949 }
5950 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005951
5952 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005953 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005954 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005955 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005956 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005957 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5958 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005959 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005960}
5961
Prabir Pradhancef936d2021-07-21 16:17:52 +00005962void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005963 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005964 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005965 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005966 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005967 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005968 };
5969 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005970}
5971
Prabir Pradhanedd96402022-02-15 01:46:16 -08005972void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5973 std::optional<int32_t> pid) {
5974 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005975 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005976 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005977 };
5978 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005979}
5980
5981/**
5982 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5983 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5984 * command entry to the command queue.
5985 */
5986void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5987 std::string reason) {
5988 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005989 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005990 if (connection.monitor) {
5991 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5992 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005993 pid = findMonitorPidByTokenLocked(connectionToken);
5994 } else {
5995 // The connection is a window
5996 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5997 reason.c_str());
5998 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
5999 if (handle != nullptr) {
6000 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006001 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006002 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006003 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006004}
6005
6006/**
6007 * Tell the policy that a connection has become responsive so that it can stop ANR.
6008 */
6009void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6010 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006011 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006012 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006013 pid = findMonitorPidByTokenLocked(connectionToken);
6014 } else {
6015 // The connection is a window
6016 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6017 if (handle != nullptr) {
6018 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006019 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006020 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006021 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006022}
6023
Prabir Pradhancef936d2021-07-21 16:17:52 +00006024bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006025 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006026 KeyEntry& keyEntry, bool handled) {
6027 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006028 if (!handled) {
6029 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006030 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006031 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006032 return false;
6033 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006034
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006035 // Get the fallback key state.
6036 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006037 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006038 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006039 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006040 connection->inputState.removeFallbackKey(originalKeyCode);
6041 }
6042
6043 if (handled || !dispatchEntry->hasForegroundTarget()) {
6044 // If the application handles the original key for which we previously
6045 // generated a fallback or if the window is not a foreground window,
6046 // then cancel the associated fallback key, if any.
6047 if (fallbackKeyCode != -1) {
6048 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006049 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6050 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6051 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6052 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6053 keyEntry.policyFlags);
6054 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006055 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006056 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006057
6058 mLock.unlock();
6059
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006060 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006061 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006062
6063 mLock.lock();
6064
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006065 // Cancel the fallback key.
6066 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006067 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006068 "application handled the original non-fallback key "
6069 "or is no longer a foreground target, "
6070 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006071 options.keyCode = fallbackKeyCode;
6072 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006073 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006074 connection->inputState.removeFallbackKey(originalKeyCode);
6075 }
6076 } else {
6077 // If the application did not handle a non-fallback key, first check
6078 // that we are in a good state to perform unhandled key event processing
6079 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006080 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006081 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006082 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6083 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6084 "since this is not an initial down. "
6085 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6086 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6087 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006088 return false;
6089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006090
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006091 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006092 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6093 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6094 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6095 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6096 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006097 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006098
6099 mLock.unlock();
6100
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006101 bool fallback =
6102 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006103 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006104
6105 mLock.lock();
6106
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006107 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006108 connection->inputState.removeFallbackKey(originalKeyCode);
6109 return false;
6110 }
6111
6112 // Latch the fallback keycode for this key on an initial down.
6113 // The fallback keycode cannot change at any other point in the lifecycle.
6114 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006115 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006116 fallbackKeyCode = event.getKeyCode();
6117 } else {
6118 fallbackKeyCode = AKEYCODE_UNKNOWN;
6119 }
6120 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6121 }
6122
6123 ALOG_ASSERT(fallbackKeyCode != -1);
6124
6125 // Cancel the fallback key if the policy decides not to send it anymore.
6126 // We will continue to dispatch the key to the policy but we will no
6127 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006128 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6129 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006130 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6131 if (fallback) {
6132 ALOGD("Unhandled key event: Policy requested to send key %d"
6133 "as a fallback for %d, but on the DOWN it had requested "
6134 "to send %d instead. Fallback canceled.",
6135 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6136 } else {
6137 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6138 "but on the DOWN it had requested to send %d. "
6139 "Fallback canceled.",
6140 originalKeyCode, fallbackKeyCode);
6141 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006142 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006143
6144 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6145 "canceling fallback, policy no longer desires it");
6146 options.keyCode = fallbackKeyCode;
6147 synthesizeCancelationEventsForConnectionLocked(connection, options);
6148
6149 fallback = false;
6150 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006151 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006152 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006153 }
6154 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006155
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006156 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6157 {
6158 std::string msg;
6159 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6160 connection->inputState.getFallbackKeys();
6161 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6162 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6163 }
6164 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6165 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006166 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006167 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006168
6169 if (fallback) {
6170 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006171 keyEntry.eventTime = event.getEventTime();
6172 keyEntry.deviceId = event.getDeviceId();
6173 keyEntry.source = event.getSource();
6174 keyEntry.displayId = event.getDisplayId();
6175 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6176 keyEntry.keyCode = fallbackKeyCode;
6177 keyEntry.scanCode = event.getScanCode();
6178 keyEntry.metaState = event.getMetaState();
6179 keyEntry.repeatCount = event.getRepeatCount();
6180 keyEntry.downTime = event.getDownTime();
6181 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006182
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006183 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6184 ALOGD("Unhandled key event: Dispatching fallback key. "
6185 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6186 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6187 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006188 return true; // restart the event
6189 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006190 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6191 ALOGD("Unhandled key event: No fallback key.");
6192 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006193
6194 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006195 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006196 }
6197 }
6198 return false;
6199}
6200
Prabir Pradhancef936d2021-07-21 16:17:52 +00006201bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006202 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006203 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006204 return false;
6205}
6206
Michael Wrightd02c5b62014-02-10 15:10:22 -08006207void InputDispatcher::traceInboundQueueLengthLocked() {
6208 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006209 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006210 }
6211}
6212
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006213void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006214 if (ATRACE_ENABLED()) {
6215 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006216 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6217 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006218 }
6219}
6220
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006221void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006222 if (ATRACE_ENABLED()) {
6223 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006224 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6225 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006226 }
6227}
6228
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006229void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006230 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006231
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006232 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006233 dumpDispatchStateLocked(dump);
6234
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006235 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006236 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006237 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006238 }
6239}
6240
6241void InputDispatcher::monitor() {
6242 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006243 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006244 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006245 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006246}
6247
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006248/**
6249 * Wake up the dispatcher and wait until it processes all events and commands.
6250 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6251 * this method can be safely called from any thread, as long as you've ensured that
6252 * the work you are interested in completing has already been queued.
6253 */
6254bool InputDispatcher::waitForIdle() {
6255 /**
6256 * Timeout should represent the longest possible time that a device might spend processing
6257 * events and commands.
6258 */
6259 constexpr std::chrono::duration TIMEOUT = 100ms;
6260 std::unique_lock lock(mLock);
6261 mLooper->wake();
6262 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6263 return result == std::cv_status::no_timeout;
6264}
6265
Vishnu Naire798b472020-07-23 13:52:21 -07006266/**
6267 * Sets focus to the window identified by the token. This must be called
6268 * after updating any input window handles.
6269 *
6270 * Params:
6271 * request.token - input channel token used to identify the window that should gain focus.
6272 * request.focusedToken - the token that the caller expects currently to be focused. If the
6273 * specified token does not match the currently focused window, this request will be dropped.
6274 * If the specified focused token matches the currently focused window, the call will succeed.
6275 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6276 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6277 * when requesting the focus change. This determines which request gets
6278 * precedence if there is a focus change request from another source such as pointer down.
6279 */
Vishnu Nair958da932020-08-21 17:12:37 -07006280void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6281 { // acquire lock
6282 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006283 std::optional<FocusResolver::FocusChanges> changes =
6284 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6285 if (changes) {
6286 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006287 }
6288 } // release lock
6289 // Wake up poll loop since it may need to make new input dispatching choices.
6290 mLooper->wake();
6291}
6292
Vishnu Nairc519ff72021-01-21 08:23:08 -08006293void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6294 if (changes.oldFocus) {
6295 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006296 if (focusedInputChannel) {
6297 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6298 "focus left window");
6299 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006300 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006301 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006302 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006303 if (changes.newFocus) {
6304 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006305 }
6306
Prabir Pradhan99987712020-11-10 18:43:05 -08006307 // If a window has pointer capture, then it must have focus. We need to ensure that this
6308 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6309 // If the window loses focus before it loses pointer capture, then the window can be in a state
6310 // where it has pointer capture but not focus, violating the contract. Therefore we must
6311 // dispatch the pointer capture event before the focus event. Since focus events are added to
6312 // the front of the queue (above), we add the pointer capture event to the front of the queue
6313 // after the focus events are added. This ensures the pointer capture event ends up at the
6314 // front.
6315 disablePointerCaptureForcedLocked();
6316
Vishnu Nairc519ff72021-01-21 08:23:08 -08006317 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006318 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006319 }
6320}
Vishnu Nair958da932020-08-21 17:12:37 -07006321
Prabir Pradhan99987712020-11-10 18:43:05 -08006322void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006323 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006324 return;
6325 }
6326
6327 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6328
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006329 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006330 setPointerCaptureLocked(false);
6331 }
6332
6333 if (!mWindowTokenWithPointerCapture) {
6334 // No need to send capture changes because no window has capture.
6335 return;
6336 }
6337
6338 if (mPendingEvent != nullptr) {
6339 // Move the pending event to the front of the queue. This will give the chance
6340 // for the pending event to be dropped if it is a captured event.
6341 mInboundQueue.push_front(mPendingEvent);
6342 mPendingEvent = nullptr;
6343 }
6344
6345 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006346 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006347 mInboundQueue.push_front(std::move(entry));
6348}
6349
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006350void InputDispatcher::setPointerCaptureLocked(bool enable) {
6351 mCurrentPointerCaptureRequest.enable = enable;
6352 mCurrentPointerCaptureRequest.seq++;
6353 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006354 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006355 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006356 };
6357 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006358}
6359
Vishnu Nair599f1412021-06-21 10:39:58 -07006360void InputDispatcher::displayRemoved(int32_t displayId) {
6361 { // acquire lock
6362 std::scoped_lock _l(mLock);
6363 // Set an empty list to remove all handles from the specific display.
6364 setInputWindowsLocked(/* window handles */ {}, displayId);
6365 setFocusedApplicationLocked(displayId, nullptr);
6366 // Call focus resolver to clean up stale requests. This must be called after input windows
6367 // have been removed for the removed display.
6368 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006369 // Reset pointer capture eligibility, regardless of previous state.
6370 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006371 // Remove the associated touch mode state.
6372 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006373 } // release lock
6374
6375 // Wake up poll loop since it may need to make new input dispatching choices.
6376 mLooper->wake();
6377}
6378
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006379void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6380 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006381 // The listener sends the windows as a flattened array. Separate the windows by display for
6382 // more convenient parsing.
6383 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006384 for (const auto& info : windowInfos) {
6385 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006386 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006387 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006388
6389 { // acquire lock
6390 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006391
6392 // Ensure that we have an entry created for all existing displays so that if a displayId has
6393 // no windows, we can tell that the windows were removed from the display.
6394 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6395 handlesPerDisplay[displayId];
6396 }
6397
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006398 mDisplayInfos.clear();
6399 for (const auto& displayInfo : displayInfos) {
6400 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6401 }
6402
6403 for (const auto& [displayId, handles] : handlesPerDisplay) {
6404 setInputWindowsLocked(handles, displayId);
6405 }
6406 }
6407 // Wake up poll loop since it may need to make new input dispatching choices.
6408 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006409}
6410
Vishnu Nair062a8672021-09-03 16:07:44 -07006411bool InputDispatcher::shouldDropInput(
6412 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006413 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6414 (windowHandle->getInfo()->inputConfig.test(
6415 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006416 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006417 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6418 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006419 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006420 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006421 windowHandle->getInfo()->displayId);
6422 return true;
6423 }
6424 return false;
6425}
6426
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006427void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6428 const std::vector<gui::WindowInfo>& windowInfos,
6429 const std::vector<DisplayInfo>& displayInfos) {
6430 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6431}
6432
Arthur Hungdfd528e2021-12-08 13:23:04 +00006433void InputDispatcher::cancelCurrentTouch() {
6434 {
6435 std::scoped_lock _l(mLock);
6436 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6437 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6438 "cancel current touch");
6439 synthesizeCancelationEventsForAllConnectionsLocked(options);
6440
6441 mTouchStatesByDisplay.clear();
6442 mLastHoverWindowHandle.clear();
6443 }
6444 // Wake up poll loop since there might be work to do.
6445 mLooper->wake();
6446}
6447
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006448void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6449 std::scoped_lock _l(mLock);
6450 mMonitorDispatchingTimeout = timeout;
6451}
6452
Garfield Tane84e6f92019-08-29 17:28:41 -07006453} // namespace android::inputdispatcher