blob: f73e90753b5bc4ff3600e73de75d1eb8b8d967a5 [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
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000527} // namespace
528
Michael Wrightd02c5b62014-02-10 15:10:22 -0800529// --- InputDispatcher ---
530
Garfield Tan00f511d2019-06-12 16:55:40 -0700531InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800532 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
533
534InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
535 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700536 : mPolicy(policy),
537 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700538 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800539 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700540 mAppSwitchSawKeyDown(false),
541 mAppSwitchDueTime(LONG_LONG_MAX),
542 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800543 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700544 mDispatchEnabled(false),
545 mDispatchFrozen(false),
546 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800547 // mInTouchMode will be initialized by the WindowManager to the default device config.
548 // To avoid leaking stack in case that call never comes, and for tests,
549 // initialize it here anyways.
Antonio Kantekf16f2832021-09-28 04:39:20 +0000550 mInTouchMode(kDefaultInTouchMode),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100551 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000552 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800553 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800554 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000555 mLatencyAggregator(),
Antonio Kanteka042c022022-07-06 16:51:07 -0700556 mLatencyTracker(&mLatencyAggregator),
557 kPerDisplayTouchModeEnabled(mPolicy->isPerDisplayTouchModeEnabled()) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700558 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800559 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800560
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700561 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700562 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
563
Yi Kong9b14ac62018-07-17 13:48:38 -0700564 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800565
566 policy->getDispatcherConfiguration(&mConfig);
567}
568
569InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000570 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800571
Prabir Pradhancef936d2021-07-21 16:17:52 +0000572 resetKeyRepeatLocked();
573 releasePendingEventLocked();
574 drainInboundQueueLocked();
575 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000577 while (!mConnectionsByToken.empty()) {
578 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000579 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
580 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800581 }
582}
583
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700584status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700585 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700586 return ALREADY_EXISTS;
587 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700588 mThread = std::make_unique<InputThread>(
589 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
590 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700591}
592
593status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700594 if (mThread && mThread->isCallingThread()) {
595 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700596 return INVALID_OPERATION;
597 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700598 mThread.reset();
599 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700600}
601
Michael Wrightd02c5b62014-02-10 15:10:22 -0800602void InputDispatcher::dispatchOnce() {
603 nsecs_t nextWakeupTime = LONG_LONG_MAX;
604 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800605 std::scoped_lock _l(mLock);
606 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800607
608 // Run a dispatch loop if there are no pending commands.
609 // The dispatch loop might enqueue commands to run afterwards.
610 if (!haveCommandsLocked()) {
611 dispatchOnceInnerLocked(&nextWakeupTime);
612 }
613
614 // Run all pending commands if there are any.
615 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000616 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617 nextWakeupTime = LONG_LONG_MIN;
618 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800619
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700620 // If we are still waiting for ack on some events,
621 // we might have to wake up earlier to check if an app is anr'ing.
622 const nsecs_t nextAnrCheck = processAnrsLocked();
623 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
624
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800625 // We are about to enter an infinitely long sleep, because we have no commands or
626 // pending or queued events
627 if (nextWakeupTime == LONG_LONG_MAX) {
628 mDispatcherEnteredIdle.notify_all();
629 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800630 } // release lock
631
632 // Wait for callback or timeout or wake. (make sure we round up, not down)
633 nsecs_t currentTime = now();
634 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
635 mLooper->pollOnce(timeoutMillis);
636}
637
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700638/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500639 * Raise ANR if there is no focused window.
640 * Before the ANR is raised, do a final state check:
641 * 1. The currently focused application must be the same one we are waiting for.
642 * 2. Ensure we still don't have a focused window.
643 */
644void InputDispatcher::processNoFocusedWindowAnrLocked() {
645 // Check if the application that we are waiting for is still focused.
646 std::shared_ptr<InputApplicationHandle> focusedApplication =
647 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
648 if (focusedApplication == nullptr ||
649 focusedApplication->getApplicationToken() !=
650 mAwaitedFocusedApplication->getApplicationToken()) {
651 // Unexpected because we should have reset the ANR timer when focused application changed
652 ALOGE("Waited for a focused window, but focused application has already changed to %s",
653 focusedApplication->getName().c_str());
654 return; // The focused application has changed.
655 }
656
chaviw98318de2021-05-19 16:45:23 -0500657 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500658 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
659 if (focusedWindowHandle != nullptr) {
660 return; // We now have a focused window. No need for ANR.
661 }
Vishnu Nair2f5bc8b2022-08-09 00:03:11 +0000662 std::optional<FocusRequest> pendingRequest =
663 mFocusResolver.getFocusRequest(mAwaitedApplicationDisplayId);
664 if (pendingRequest.has_value() && onAnrLocked(*pendingRequest)) {
665 // We don't have a focusable window but we know which window should have
666 // been focused. Blame that process in case it doesn't belong to the focused app.
667 return;
668 }
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500669 onAnrLocked(mAwaitedFocusedApplication);
670}
671
672/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700673 * Check if any of the connections' wait queues have events that are too old.
674 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
675 * Return the time at which we should wake up next.
676 */
677nsecs_t InputDispatcher::processAnrsLocked() {
678 const nsecs_t currentTime = now();
679 nsecs_t nextAnrCheck = LONG_LONG_MAX;
680 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
681 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
682 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500683 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700684 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500685 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700686 return LONG_LONG_MIN;
687 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500688 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700689 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
690 }
691 }
692
693 // Check if any connection ANRs are due
694 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
695 if (currentTime < nextAnrCheck) { // most likely scenario
696 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
697 }
698
699 // If we reached here, we have an unresponsive connection.
700 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
701 if (connection == nullptr) {
702 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
703 return nextAnrCheck;
704 }
705 connection->responsive = false;
706 // Stop waking up for this unresponsive connection
707 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000708 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700709 return LONG_LONG_MIN;
710}
711
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800712std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
713 const sp<Connection>& connection) {
714 if (connection->monitor) {
715 return mMonitorDispatchingTimeout;
716 }
717 const sp<WindowInfoHandle> window =
718 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700719 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500720 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700721 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500722 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700723}
724
Michael Wrightd02c5b62014-02-10 15:10:22 -0800725void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
726 nsecs_t currentTime = now();
727
Jeff Browndc5992e2014-04-11 01:27:26 -0700728 // Reset the key repeat timer whenever normal dispatch is suspended while the
729 // device is in a non-interactive state. This is to ensure that we abort a key
730 // repeat if the device is just coming out of sleep.
731 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800732 resetKeyRepeatLocked();
733 }
734
735 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
736 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100737 if (DEBUG_FOCUS) {
738 ALOGD("Dispatch frozen. Waiting some more.");
739 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800740 return;
741 }
742
743 // Optimize latency of app switches.
744 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
745 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
746 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
747 if (mAppSwitchDueTime < *nextWakeupTime) {
748 *nextWakeupTime = mAppSwitchDueTime;
749 }
750
751 // Ready to start a new event.
752 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700753 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700754 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755 if (isAppSwitchDue) {
756 // The inbound queue is empty so the app switch key we were waiting
757 // for will never arrive. Stop waiting for it.
758 resetPendingAppSwitchLocked(false);
759 isAppSwitchDue = false;
760 }
761
762 // Synthesize a key repeat if appropriate.
763 if (mKeyRepeatState.lastKeyEntry) {
764 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
765 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
766 } else {
767 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
768 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
769 }
770 }
771 }
772
773 // Nothing to do if there is no pending event.
774 if (!mPendingEvent) {
775 return;
776 }
777 } else {
778 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700779 mPendingEvent = mInboundQueue.front();
780 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781 traceInboundQueueLengthLocked();
782 }
783
784 // Poke user activity for this event.
785 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700786 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 }
789
790 // Now we have an event to dispatch.
791 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700792 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800793 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700794 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800795 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700796 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800797 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700798 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 }
800
801 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700802 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800803 }
804
805 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700806 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700807 const ConfigurationChangedEntry& typedEntry =
808 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700809 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700810 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700811 break;
812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700814 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700815 const DeviceResetEntry& typedEntry =
816 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700817 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700818 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700819 break;
820 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100822 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700823 std::shared_ptr<FocusEntry> typedEntry =
824 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100825 dispatchFocusLocked(currentTime, typedEntry);
826 done = true;
827 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
828 break;
829 }
830
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700831 case EventEntry::Type::TOUCH_MODE_CHANGED: {
832 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
833 dispatchTouchModeChangeLocked(currentTime, typedEntry);
834 done = true;
835 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
836 break;
837 }
838
Prabir Pradhan99987712020-11-10 18:43:05 -0800839 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
840 const auto typedEntry =
841 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
842 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
843 done = true;
844 break;
845 }
846
arthurhungb89ccb02020-12-30 16:19:01 +0800847 case EventEntry::Type::DRAG: {
848 std::shared_ptr<DragEntry> typedEntry =
849 std::static_pointer_cast<DragEntry>(mPendingEvent);
850 dispatchDragLocked(currentTime, typedEntry);
851 done = true;
852 break;
853 }
854
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700855 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700856 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700857 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700858 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700859 resetPendingAppSwitchLocked(true);
860 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700861 } else if (dropReason == DropReason::NOT_DROPPED) {
862 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700863 }
864 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700865 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700866 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700867 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700868 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
869 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700870 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700871 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700872 break;
873 }
874
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700875 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700876 std::shared_ptr<MotionEntry> motionEntry =
877 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700878 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
879 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700881 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700882 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700883 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700884 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
885 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700886 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700887 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700888 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889 }
Chris Yef59a2f42020-10-16 12:55:26 -0700890
891 case EventEntry::Type::SENSOR: {
892 std::shared_ptr<SensorEntry> sensorEntry =
893 std::static_pointer_cast<SensorEntry>(mPendingEvent);
894 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
895 dropReason = DropReason::APP_SWITCH;
896 }
897 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
898 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
899 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
900 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
901 dropReason = DropReason::STALE;
902 }
903 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
904 done = true;
905 break;
906 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907 }
908
909 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700910 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700911 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912 }
Michael Wright3a981722015-06-10 15:26:13 +0100913 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914
915 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700916 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800917 }
918}
919
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800920bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
921 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
922}
923
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700924/**
925 * Return true if the events preceding this incoming motion event should be dropped
926 * Return false otherwise (the default behaviour)
927 */
928bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700929 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700930 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700931
932 // Optimize case where the current application is unresponsive and the user
933 // decides to touch a window in a different application.
934 // If the application takes too long to catch up then we drop all events preceding
935 // the touch into the other window.
936 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700937 int32_t displayId = motionEntry.displayId;
938 int32_t x = static_cast<int32_t>(
939 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
940 int32_t y = static_cast<int32_t>(
941 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Prabir Pradhand65552b2021-10-07 11:23:50 -0700942
943 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -0500944 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700945 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700946 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700947 touchedWindowHandle->getApplicationToken() !=
948 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700949 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700950 ALOGI("Pruning input queue because user touched a different application while waiting "
951 "for %s",
952 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700953 return true;
954 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700955
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800956 // Alternatively, maybe there's a spy window that could handle this event.
957 const std::vector<sp<WindowInfoHandle>> touchedSpies =
958 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
959 for (const auto& windowHandle : touchedSpies) {
960 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000961 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800962 // This spy window could take more input. Drop all events preceding this
963 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700964 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800965 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700966 mAwaitedFocusedApplication->getName().c_str());
967 return true;
968 }
969 }
970 }
971
972 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
973 // yet been processed by some connections, the dispatcher will wait for these motion
974 // events to be processed before dispatching the key event. This is because these motion events
975 // may cause a new window to be launched, which the user might expect to receive focus.
976 // To prevent waiting forever for such events, just send the key to the currently focused window
977 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
978 ALOGD("Received a new pointer down event, stop waiting for events to process and "
979 "just send the pending key event to the focused window.");
980 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700981 }
982 return false;
983}
984
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700985bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700986 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700987 mInboundQueue.push_back(std::move(newEntry));
988 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 traceInboundQueueLengthLocked();
990
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700991 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700992 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +0000993 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
994 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700995 // Optimize app switch latency.
996 // If the application takes too long to catch up then we drop all events preceding
997 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700998 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700999 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001000 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001001 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001002 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001003 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001004 if (DEBUG_APP_SWITCH) {
1005 ALOGD("App switch is pending!");
1006 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001007 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001008 mAppSwitchSawKeyDown = false;
1009 needWake = true;
1010 }
1011 }
1012 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001013
1014 // If a new up event comes in, and the pending event with same key code has been asked
1015 // to try again later because of the policy. We have to reset the intercept key wake up
1016 // time for it may have been handled in the policy and could be dropped.
1017 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1018 mPendingEvent->type == EventEntry::Type::KEY) {
1019 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1020 if (pendingKey.keyCode == keyEntry.keyCode &&
1021 pendingKey.interceptKeyResult ==
1022 KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1023 pendingKey.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1024 pendingKey.interceptKeyWakeupTime = 0;
1025 needWake = true;
1026 }
1027 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001028 break;
1029 }
1030
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001031 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001032 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1033 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001034 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1035 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001036 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001038 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001040 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001041 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1042 break;
1043 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001044 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001045 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001046 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001047 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001048 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1049 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001050 // nothing to do
1051 break;
1052 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 }
1054
1055 return needWake;
1056}
1057
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001058void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001059 // Do not store sensor event in recent queue to avoid flooding the queue.
1060 if (entry->type != EventEntry::Type::SENSOR) {
1061 mRecentQueue.push_back(entry);
1062 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001063 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001064 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 }
1066}
1067
chaviw98318de2021-05-19 16:45:23 -05001068sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1069 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001070 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001071 bool addOutsideTargets,
1072 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001073 if (addOutsideTargets && touchState == nullptr) {
1074 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001075 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001077 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001078 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001079 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001080 continue;
1081 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001083 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001084 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001085 return windowHandle;
1086 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001087
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001088 if (addOutsideTargets &&
1089 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001090 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1091 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092 }
1093 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001094 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001095}
1096
Prabir Pradhand65552b2021-10-07 11:23:50 -07001097std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1098 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001099 // Traverse windows from front to back and gather the touched spy windows.
1100 std::vector<sp<WindowInfoHandle>> spyWindows;
1101 const auto& windowHandles = getWindowHandlesLocked(displayId);
1102 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1103 const WindowInfo& info = *windowHandle->getInfo();
1104
Prabir Pradhand65552b2021-10-07 11:23:50 -07001105 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001106 continue;
1107 }
1108 if (!info.isSpy()) {
1109 // The first touched non-spy window was found, so return the spy windows touched so far.
1110 return spyWindows;
1111 }
1112 spyWindows.push_back(windowHandle);
1113 }
1114 return spyWindows;
1115}
1116
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001117void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118 const char* reason;
1119 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001120 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001121 if (DEBUG_INBOUND_EVENT_DETAILS) {
1122 ALOGD("Dropped event because policy consumed it.");
1123 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001124 reason = "inbound event was dropped because the policy consumed it";
1125 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001126 case DropReason::DISABLED:
1127 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001128 ALOGI("Dropped event because input dispatch is disabled.");
1129 }
1130 reason = "inbound event was dropped because input dispatch is disabled";
1131 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001132 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001133 ALOGI("Dropped event because of pending overdue app switch.");
1134 reason = "inbound event was dropped because of pending overdue app switch";
1135 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001136 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001137 ALOGI("Dropped event because the current application is not responding and the user "
1138 "has started interacting with a different application.");
1139 reason = "inbound event was dropped because the current application is not responding "
1140 "and the user has started interacting with a different application";
1141 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001142 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001143 ALOGI("Dropped event because it is stale.");
1144 reason = "inbound event was dropped because it is stale";
1145 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001146 case DropReason::NO_POINTER_CAPTURE:
1147 ALOGI("Dropped event because there is no window with Pointer Capture.");
1148 reason = "inbound event was dropped because there is no window with Pointer Capture";
1149 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001150 case DropReason::NOT_DROPPED: {
1151 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001152 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001153 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 }
1155
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001156 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001157 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001158 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1159 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001160 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001162 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001163 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1164 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001165 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1166 synthesizeCancelationEventsForAllConnectionsLocked(options);
1167 } else {
1168 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1169 synthesizeCancelationEventsForAllConnectionsLocked(options);
1170 }
1171 break;
1172 }
Chris Yef59a2f42020-10-16 12:55:26 -07001173 case EventEntry::Type::SENSOR: {
1174 break;
1175 }
arthurhungb89ccb02020-12-30 16:19:01 +08001176 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1177 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001178 break;
1179 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001180 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001181 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001182 case EventEntry::Type::CONFIGURATION_CHANGED:
1183 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001184 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001185 break;
1186 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187 }
1188}
1189
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001190static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001191 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1192 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193}
1194
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001195bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1196 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1197 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1198 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199}
1200
1201bool InputDispatcher::isAppSwitchPendingLocked() {
1202 return mAppSwitchDueTime != LONG_LONG_MAX;
1203}
1204
1205void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1206 mAppSwitchDueTime = LONG_LONG_MAX;
1207
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001208 if (DEBUG_APP_SWITCH) {
1209 if (handled) {
1210 ALOGD("App switch has arrived.");
1211 } else {
1212 ALOGD("App switch was abandoned.");
1213 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215}
1216
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001218 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219}
1220
Prabir Pradhancef936d2021-07-21 16:17:52 +00001221bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001222 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 return false;
1224 }
1225
1226 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001227 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001228 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001229 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1230 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001231 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 return true;
1233}
1234
Prabir Pradhancef936d2021-07-21 16:17:52 +00001235void InputDispatcher::postCommandLocked(Command&& command) {
1236 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237}
1238
1239void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001240 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001241 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001242 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 releaseInboundEventLocked(entry);
1244 }
1245 traceInboundQueueLengthLocked();
1246}
1247
1248void InputDispatcher::releasePendingEventLocked() {
1249 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001251 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 }
1253}
1254
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001255void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001257 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001258 if (DEBUG_DISPATCH_CYCLE) {
1259 ALOGD("Injected inbound event was dropped.");
1260 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001261 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 }
1263 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001264 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 }
1266 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267}
1268
1269void InputDispatcher::resetKeyRepeatLocked() {
1270 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001271 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272 }
1273}
1274
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001275std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1276 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277
Michael Wright2e732952014-09-24 13:26:59 -07001278 uint32_t policyFlags = entry->policyFlags &
1279 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001281 std::shared_ptr<KeyEntry> newEntry =
1282 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1283 entry->source, entry->displayId, policyFlags, entry->action,
1284 entry->flags, entry->keyCode, entry->scanCode,
1285 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001287 newEntry->syntheticRepeat = true;
1288 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001289 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001290 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291}
1292
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001293bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001294 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001295 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1296 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1297 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298
1299 // Reset key repeating in case a keyboard device was added or removed or something.
1300 resetKeyRepeatLocked();
1301
1302 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001303 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1304 scoped_unlock unlock(mLock);
1305 mPolicy->notifyConfigurationChanged(eventTime);
1306 };
1307 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308 return true;
1309}
1310
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001311bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1312 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001313 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1314 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1315 entry.deviceId);
1316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317
liushenxiang42232912021-05-21 20:24:09 +08001318 // Reset key repeating in case a keyboard device was disabled or enabled.
1319 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1320 resetKeyRepeatLocked();
1321 }
1322
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001323 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001324 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325 synthesizeCancelationEventsForAllConnectionsLocked(options);
1326 return true;
1327}
1328
Vishnu Nairad321cd2020-08-20 16:40:21 -07001329void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001330 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001331 if (mPendingEvent != nullptr) {
1332 // Move the pending event to the front of the queue. This will give the chance
1333 // for the pending event to get dispatched to the newly focused window
1334 mInboundQueue.push_front(mPendingEvent);
1335 mPendingEvent = nullptr;
1336 }
1337
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001338 std::unique_ptr<FocusEntry> focusEntry =
1339 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1340 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001341
1342 // This event should go to the front of the queue, but behind all other focus events
1343 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001344 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001345 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001346 [](const std::shared_ptr<EventEntry>& event) {
1347 return event->type == EventEntry::Type::FOCUS;
1348 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001349
1350 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001351 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001352}
1353
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001354void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001355 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001356 if (channel == nullptr) {
1357 return; // Window has gone away
1358 }
1359 InputTarget target;
1360 target.inputChannel = channel;
1361 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1362 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001363 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1364 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001365 std::string reason = std::string("reason=").append(entry->reason);
1366 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001367 dispatchEventLocked(currentTime, entry, {target});
1368}
1369
Prabir Pradhan99987712020-11-10 18:43:05 -08001370void InputDispatcher::dispatchPointerCaptureChangedLocked(
1371 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1372 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001373 dropReason = DropReason::NOT_DROPPED;
1374
Prabir Pradhan99987712020-11-10 18:43:05 -08001375 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001376 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001377
1378 if (entry->pointerCaptureRequest.enable) {
1379 // Enable Pointer Capture.
1380 if (haveWindowWithPointerCapture &&
1381 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001382 // This can happen if pointer capture is disabled and re-enabled before we notify the
1383 // app of the state change, so there is no need to notify the app.
1384 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1385 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001386 }
1387 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001388 // This can happen if a window requests capture and immediately releases capture.
1389 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001390 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001391 return;
1392 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001393 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1394 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1395 return;
1396 }
1397
Vishnu Nairc519ff72021-01-21 08:23:08 -08001398 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001399 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1400 mWindowTokenWithPointerCapture = token;
1401 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001402 // Disable Pointer Capture.
1403 // We do not check if the sequence number matches for requests to disable Pointer Capture
1404 // for two reasons:
1405 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1406 // to disable capture with the same sequence number: one generated by
1407 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1408 // Capture being disabled in InputReader.
1409 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1410 // actual Pointer Capture state that affects events being generated by input devices is
1411 // in InputReader.
1412 if (!haveWindowWithPointerCapture) {
1413 // Pointer capture was already forcefully disabled because of focus change.
1414 dropReason = DropReason::NOT_DROPPED;
1415 return;
1416 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001417 token = mWindowTokenWithPointerCapture;
1418 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001419 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001420 setPointerCaptureLocked(false);
1421 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001422 }
1423
1424 auto channel = getInputChannelLocked(token);
1425 if (channel == nullptr) {
1426 // Window has gone away, clean up Pointer Capture state.
1427 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001428 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001429 setPointerCaptureLocked(false);
1430 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001431 return;
1432 }
1433 InputTarget target;
1434 target.inputChannel = channel;
1435 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1436 entry->dispatchInProgress = true;
1437 dispatchEventLocked(currentTime, entry, {target});
1438
1439 dropReason = DropReason::NOT_DROPPED;
1440}
1441
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001442void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1443 const std::shared_ptr<TouchModeEntry>& entry) {
1444 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1445 getWindowHandlesLocked(mFocusedDisplayId);
1446 if (windowHandles.empty()) {
1447 return;
1448 }
1449 const std::vector<InputTarget> inputTargets =
1450 getInputTargetsFromWindowHandlesLocked(windowHandles);
1451 if (inputTargets.empty()) {
1452 return;
1453 }
1454 entry->dispatchInProgress = true;
1455 dispatchEventLocked(currentTime, entry, inputTargets);
1456}
1457
1458std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1459 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1460 std::vector<InputTarget> inputTargets;
1461 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1462 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1463 const sp<IBinder>& token = handle->getToken();
1464 if (token == nullptr) {
1465 continue;
1466 }
1467 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1468 if (channel == nullptr) {
1469 continue; // Window has gone away
1470 }
1471 InputTarget target;
1472 target.inputChannel = channel;
1473 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1474 inputTargets.push_back(target);
1475 }
1476 return inputTargets;
1477}
1478
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001479bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001480 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001482 if (!entry->dispatchInProgress) {
1483 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1484 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1485 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1486 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001487 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 // We have seen two identical key downs in a row which indicates that the device
1489 // driver is automatically generating key repeats itself. We take note of the
1490 // repeat here, but we disable our own next key repeat timer since it is clear that
1491 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001492 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1493 // Make sure we don't get key down from a different device. If a different
1494 // device Id has same key pressed down, the new device Id will replace the
1495 // current one to hold the key repeat with repeat count reset.
1496 // In the future when got a KEY_UP on the device id, drop it and do not
1497 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001498 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1499 resetKeyRepeatLocked();
1500 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1501 } else {
1502 // Not a repeat. Save key down state in case we do see a repeat later.
1503 resetKeyRepeatLocked();
1504 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1505 }
1506 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001507 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1508 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001509 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001510 if (DEBUG_INBOUND_EVENT_DETAILS) {
1511 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1512 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001513 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 resetKeyRepeatLocked();
1515 }
1516
1517 if (entry->repeatCount == 1) {
1518 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1519 } else {
1520 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1521 }
1522
1523 entry->dispatchInProgress = true;
1524
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001525 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 }
1527
1528 // Handle case where the policy asked us to try again later last time.
1529 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1530 if (currentTime < entry->interceptKeyWakeupTime) {
1531 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1532 *nextWakeupTime = entry->interceptKeyWakeupTime;
1533 }
1534 return false; // wait until next wakeup
1535 }
1536 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1537 entry->interceptKeyWakeupTime = 0;
1538 }
1539
1540 // Give the policy a chance to intercept the key.
1541 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1542 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001543 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001544 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001545
1546 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1547 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1548 };
1549 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 return false; // wait for the command to run
1551 } else {
1552 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1553 }
1554 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001555 if (*dropReason == DropReason::NOT_DROPPED) {
1556 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 }
1558 }
1559
1560 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001561 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001562 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001563 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1564 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001565 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001566 return true;
1567 }
1568
1569 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001570 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001571 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001572 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001573 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574 return false;
1575 }
1576
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001577 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001578 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579 return true;
1580 }
1581
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001582 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001583 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584
1585 // Dispatch the key.
1586 dispatchEventLocked(currentTime, entry, inputTargets);
1587 return true;
1588}
1589
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001590void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001591 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1592 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1593 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1594 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1595 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1596 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1597 entry.metaState, entry.repeatCount, entry.downTime);
1598 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599}
1600
Prabir Pradhancef936d2021-07-21 16:17:52 +00001601void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1602 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001603 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001604 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1605 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1606 "source=0x%x, sensorType=%s",
1607 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001608 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001609 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001610 auto command = [this, entry]() REQUIRES(mLock) {
1611 scoped_unlock unlock(mLock);
1612
1613 if (entry->accuracyChanged) {
1614 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1615 }
1616 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1617 entry->hwTimestamp, entry->values);
1618 };
1619 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001620}
1621
1622bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001623 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1624 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001625 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001626 }
Chris Yef59a2f42020-10-16 12:55:26 -07001627 { // acquire lock
1628 std::scoped_lock _l(mLock);
1629
1630 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1631 std::shared_ptr<EventEntry> entry = *it;
1632 if (entry->type == EventEntry::Type::SENSOR) {
1633 it = mInboundQueue.erase(it);
1634 releaseInboundEventLocked(entry);
1635 }
1636 }
1637 }
1638 return true;
1639}
1640
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001641bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001642 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001643 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001645 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001646 entry->dispatchInProgress = true;
1647
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001648 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 }
1650
1651 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001652 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001653 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001654 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1655 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656 return true;
1657 }
1658
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001659 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660
1661 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001662 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001663
1664 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001665 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 if (isPointerEvent) {
1667 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001668
1669 if (mDragState &&
1670 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1671 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1672 pilferPointersLocked(mDragState->dragWindow->getToken());
1673 }
1674
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001675 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001676 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001677 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 } else {
1679 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001680 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001681 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001683 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684 return false;
1685 }
1686
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001687 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001688 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001689 return true;
1690 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001691 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001692 CancelationOptions::Mode mode(isPointerEvent
1693 ? CancelationOptions::CANCEL_POINTER_EVENTS
1694 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1695 CancelationOptions options(mode, "input event injection failed");
1696 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697 return true;
1698 }
1699
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001700 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001701 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001702
1703 // Dispatch the motion.
1704 if (conflictingPointerActions) {
1705 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001706 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 synthesizeCancelationEventsForAllConnectionsLocked(options);
1708 }
1709 dispatchEventLocked(currentTime, entry, inputTargets);
1710 return true;
1711}
1712
chaviw98318de2021-05-19 16:45:23 -05001713void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001714 bool isExiting, const int32_t rawX,
1715 const int32_t rawY) {
1716 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001717 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001718 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1719 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001720
1721 enqueueInboundEventLocked(std::move(dragEntry));
1722}
1723
1724void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1725 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1726 if (channel == nullptr) {
1727 return; // Window has gone away
1728 }
1729 InputTarget target;
1730 target.inputChannel = channel;
1731 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1732 entry->dispatchInProgress = true;
1733 dispatchEventLocked(currentTime, entry, {target});
1734}
1735
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001736void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001737 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1738 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1739 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001740 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001741 "metaState=0x%x, buttonState=0x%x,"
1742 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1743 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001744 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1745 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1746 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001748 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1749 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1750 "x=%f, y=%f, pressure=%f, size=%f, "
1751 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1752 "orientation=%f",
1753 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1754 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1755 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1756 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1757 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1758 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1759 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1760 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1761 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1762 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1763 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001764 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765}
1766
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001767void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1768 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001769 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001770 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001771 if (DEBUG_DISPATCH_CYCLE) {
1772 ALOGD("dispatchEventToCurrentInputTargets");
1773 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001775 updateInteractionTokensLocked(*eventEntry, inputTargets);
1776
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1778
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001779 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001781 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001782 sp<Connection> connection =
1783 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001784 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001785 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001786 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001787 if (DEBUG_FOCUS) {
1788 ALOGD("Dropping event delivery to target with channel '%s' because it "
1789 "is no longer registered with the input dispatcher.",
1790 inputTarget.inputChannel->getName().c_str());
1791 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792 }
1793 }
1794}
1795
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001796void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1797 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1798 // If the policy decides to close the app, we will get a channel removal event via
1799 // unregisterInputChannel, and will clean up the connection that way. We are already not
1800 // sending new pointers to the connection when it blocked, but focused events will continue to
1801 // pile up.
1802 ALOGW("Canceling events for %s because it is unresponsive",
1803 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001804 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001805 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1806 "application not responding");
1807 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 }
1809}
1810
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001811void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001812 if (DEBUG_FOCUS) {
1813 ALOGD("Resetting ANR timeouts.");
1814 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001815
1816 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001817 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001818 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819}
1820
Tiger Huang721e26f2018-07-24 22:26:19 +08001821/**
1822 * Get the display id that the given event should go to. If this event specifies a valid display id,
1823 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1824 * Focused display is the display that the user most recently interacted with.
1825 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001826int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001827 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001828 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001829 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001830 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1831 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001832 break;
1833 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001834 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001835 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1836 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001837 break;
1838 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001839 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001840 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001841 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001842 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001843 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001844 case EventEntry::Type::SENSOR:
1845 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001846 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001847 return ADISPLAY_ID_NONE;
1848 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001849 }
1850 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1851}
1852
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001853bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1854 const char* focusedWindowName) {
1855 if (mAnrTracker.empty()) {
1856 // already processed all events that we waited for
1857 mKeyIsWaitingForEventsTimeout = std::nullopt;
1858 return false;
1859 }
1860
1861 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1862 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001863 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001864 mKeyIsWaitingForEventsTimeout = currentTime +
1865 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1866 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001867 return true;
1868 }
1869
1870 // We still have pending events, and already started the timer
1871 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1872 return true; // Still waiting
1873 }
1874
1875 // Waited too long, and some connection still hasn't processed all motions
1876 // Just send the key to the focused window
1877 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1878 focusedWindowName);
1879 mKeyIsWaitingForEventsTimeout = std::nullopt;
1880 return false;
1881}
1882
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001883static std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
1884 if (eventEntry.type == EventEntry::Type::KEY) {
1885 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
1886 return keyEntry.downTime;
1887 } else if (eventEntry.type == EventEntry::Type::MOTION) {
1888 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
1889 return motionEntry.downTime;
1890 }
1891 return std::nullopt;
1892}
1893
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001894InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1895 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1896 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001897 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898
Tiger Huang721e26f2018-07-24 22:26:19 +08001899 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001900 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001901 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001902 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1903
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 // If there is no currently focused window and no focused application
1905 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001906 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1907 ALOGI("Dropping %s event because there is no focused window or focused application in "
1908 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001909 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001910 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911 }
1912
Vishnu Nair062a8672021-09-03 16:07:44 -07001913 // Drop key events if requested by input feature
1914 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1915 return InputEventInjectionResult::FAILED;
1916 }
1917
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001918 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1919 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1920 // start interacting with another application via touch (app switch). This code can be removed
1921 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1922 // an app is expected to have a focused window.
1923 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1924 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1925 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001926 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1927 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1928 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001929 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001930 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001931 ALOGW("Waiting because no window has focus but %s may eventually add a "
1932 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001933 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001934 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001935 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001936 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1937 // Already raised ANR. Drop the event
1938 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001939 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001940 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001941 } else {
1942 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001943 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001944 }
1945 }
1946
1947 // we have a valid, non-null focused window
1948 resetNoFocusedWindowTimeoutLocked();
1949
Prabir Pradhan5735a322022-04-11 17:23:34 +00001950 // Verify targeted injection.
1951 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
1952 ALOGW("Dropping injected event: %s", (*err).c_str());
1953 return InputEventInjectionResult::TARGET_MISMATCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954 }
1955
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001956 if (focusedWindowHandle->getInfo()->inputConfig.test(
1957 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001958 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001959 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001960 }
1961
1962 // If the event is a key event, then we must wait for all previous events to
1963 // complete before delivering it because previous events may have the
1964 // side-effect of transferring focus to a different window and we want to
1965 // ensure that the following keys are sent to the new window.
1966 //
1967 // Suppose the user touches a button in a window then immediately presses "A".
1968 // If the button causes a pop-up window to appear then we want to ensure that
1969 // the "A" key is delivered to the new pop-up window. This is because users
1970 // often anticipate pending UI changes when typing on a keyboard.
1971 // To obtain this behavior, we must serialize key events with respect to all
1972 // prior input events.
1973 if (entry.type == EventEntry::Type::KEY) {
1974 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1975 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001976 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978 }
1979
1980 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001981 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001982 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001983 BitSet32(0), getDownTime(entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984
1985 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001986 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987}
1988
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001989/**
1990 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1991 * that are currently unresponsive.
1992 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001993std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1994 const std::vector<Monitor>& monitors) const {
1995 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001996 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001997 [this](const Monitor& monitor) REQUIRES(mLock) {
1998 sp<Connection> connection =
1999 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002000 if (connection == nullptr) {
2001 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002002 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002003 return false;
2004 }
2005 if (!connection->responsive) {
2006 ALOGW("Unresponsive monitor %s will not get the new gesture",
2007 connection->inputChannel->getName().c_str());
2008 return false;
2009 }
2010 return true;
2011 });
2012 return responsiveMonitors;
2013}
2014
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002015InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
2016 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
2017 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002018 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 // For security reasons, we defer updating the touch state until we are sure that
2021 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002022 const int32_t displayId = entry.displayId;
2023 const int32_t action = entry.action;
2024 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025
2026 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002027 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
chaviw98318de2021-05-19 16:45:23 -05002028 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2029 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002031 // Copy current touch state into tempTouchState.
2032 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2033 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002034 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002035 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002036 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2037 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002038 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002039 }
2040
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002041 bool isSplit = tempTouchState.split;
2042 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2043 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2044 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002045
2046 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2047 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2048 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2049 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2050 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002051 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002052 bool wrongDevice = false;
2053 if (newGesture) {
2054 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002055 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002056 ALOGI("Dropping event because a pointer for a different device is already down "
2057 "in display %" PRId32,
2058 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002059 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002060 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061 switchedDevice = false;
2062 wrongDevice = true;
2063 goto Failed;
2064 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002065 tempTouchState.reset();
2066 tempTouchState.down = down;
2067 tempTouchState.deviceId = entry.deviceId;
2068 tempTouchState.source = entry.source;
2069 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002071 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002072 ALOGI("Dropping move event because a pointer for a different device is already active "
2073 "in display %" PRId32,
2074 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002075 // TODO: test multiple simultaneous input streams.
Prabir Pradhan5735a322022-04-11 17:23:34 +00002076 injectionResult = InputEventInjectionResult::FAILED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002077 switchedDevice = false;
2078 wrongDevice = true;
2079 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 }
2081
2082 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2083 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2084
Garfield Tan00f511d2019-06-12 16:55:40 -07002085 int32_t x;
2086 int32_t y;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002087 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002088 // Always dispatch mouse events to cursor position.
2089 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002090 x = int32_t(entry.xCursorPosition);
2091 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002092 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002093 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2094 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002095 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002096 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002097 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002098 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002099 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002100
Michael Wrightd02c5b62014-02-10 15:10:22 -08002101 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002102 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002103 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2104 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002106 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002107 }
2108
Prabir Pradhan5735a322022-04-11 17:23:34 +00002109 // Verify targeted injection.
2110 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2111 ALOGW("Dropping injected touch event: %s", (*err).c_str());
2112 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2113 newTouchedWindowHandle = nullptr;
2114 goto Failed;
2115 }
2116
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002117 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002118 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002119 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2120 // New window supports splitting, but we should never split mouse events.
2121 isSplit = !isFromMouse;
2122 } else if (isSplit) {
2123 // New window does not support splitting but we have already split events.
2124 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002125 newTouchedWindowHandle = nullptr;
2126 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002127 } else {
2128 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002129 // be delivered to a new window which supports split touch. Pointers from a mouse device
2130 // should never be split.
2131 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002132 }
2133
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002134 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002135 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002136 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2137 newHoverWindowHandle = nullptr;
2138 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002139 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002140 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002141 }
2142
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002143 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002144 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002145 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002146 // Process the foreground window first so that it is the first to receive the event.
2147 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002148 }
2149
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002150 if (newTouchedWindows.empty()) {
2151 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2152 x, y, displayId);
2153 injectionResult = InputEventInjectionResult::FAILED;
2154 goto Failed;
2155 }
2156
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002157 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2158 const WindowInfo& info = *windowHandle->getInfo();
2159
Prabir Pradhan5735a322022-04-11 17:23:34 +00002160 // Skip spy window targets that are not valid for targeted injection.
2161 if (const auto err = verifyTargetedInjection(windowHandle, entry); err) {
2162 continue;
2163 }
2164
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002165 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002166 ALOGI("Not sending touch event to %s because it is paused",
2167 windowHandle->getName().c_str());
2168 continue;
2169 }
2170
2171 // Ensure the window has a connection and the connection is responsive
2172 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2173 if (!isResponsive) {
2174 ALOGW("Not sending touch gesture to %s because it is not responsive",
2175 windowHandle->getName().c_str());
2176 continue;
2177 }
2178
2179 // Drop events that can't be trusted due to occlusion
Hani Kazmi3ce9c3a2022-04-25 09:40:23 +00002180 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(windowHandle, x, y);
2181 if (!isTouchTrustedLocked(occlusionInfo)) {
2182 if (DEBUG_TOUCH_OCCLUSION) {
2183 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2184 for (const auto& log : occlusionInfo.debugInfo) {
2185 ALOGD("%s", log.c_str());
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002186 }
2187 }
Hani Kazmi3ce9c3a2022-04-25 09:40:23 +00002188 ALOGW("Dropping untrusted touch event due to %s/%d",
2189 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2190 continue;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002191 }
2192
2193 // Drop touch events if requested by input feature
2194 if (shouldDropInput(entry, windowHandle)) {
2195 continue;
2196 }
2197
2198 // Set target flags.
2199 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2200
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002201 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2202 // There should only be one touched window that can be "foreground" for the pointer.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002203 targetFlags |= InputTarget::FLAG_FOREGROUND;
2204 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002205
2206 if (isSplit) {
2207 targetFlags |= InputTarget::FLAG_SPLIT;
2208 }
2209 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2210 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2211 } else if (isWindowObscuredLocked(windowHandle)) {
2212 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2213 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002214
2215 // Update the temporary touch state.
2216 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002217 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002218
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002219 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
2220 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002222
2223 // If any existing window is pilfering pointers from newly added window, remove it
2224 BitSet32 canceledPointers = BitSet32(0);
2225 for (const TouchedWindow& window : tempTouchState.windows) {
2226 if (window.isPilferingPointers) {
2227 canceledPointers |= window.pointerIds;
2228 }
2229 }
2230 tempTouchState.cancelPointersForNonPilferingWindows(canceledPointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231 } else {
2232 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2233
2234 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002235 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002236 if (DEBUG_FOCUS) {
2237 ALOGD("Dropping event because the pointer is not down or we previously "
2238 "dropped the pointer down event in display %" PRId32,
2239 displayId);
2240 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002241 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 goto Failed;
2243 }
2244
arthurhung6d4bed92021-03-17 11:59:33 +08002245 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002246
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002248 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002249 tempTouchState.isSlippery()) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002250 const int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2251 const int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252
Prabir Pradhand65552b2021-10-07 11:23:50 -07002253 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002254 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002255 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002256 newTouchedWindowHandle =
2257 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002258
Prabir Pradhan5735a322022-04-11 17:23:34 +00002259 // Verify targeted injection.
2260 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2261 ALOGW("Dropping injected event: %s", (*err).c_str());
2262 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2263 newTouchedWindowHandle = nullptr;
2264 goto Failed;
2265 }
2266
Vishnu Nair062a8672021-09-03 16:07:44 -07002267 // Drop touch events if requested by input feature
2268 if (newTouchedWindowHandle != nullptr &&
2269 shouldDropInput(entry, newTouchedWindowHandle)) {
2270 newTouchedWindowHandle = nullptr;
2271 }
2272
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002273 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2274 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002275 if (DEBUG_FOCUS) {
2276 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2277 oldTouchedWindowHandle->getName().c_str(),
2278 newTouchedWindowHandle->getName().c_str(), displayId);
2279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002281 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2282 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2283 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284
2285 // Make a slippery entrance into the new window.
2286 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002287 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 }
2289
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002290 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
2291 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
2292 targetFlags |= InputTarget::FLAG_FOREGROUND;
2293 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 if (isSplit) {
2295 targetFlags |= InputTarget::FLAG_SPLIT;
2296 }
2297 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2298 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002299 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2300 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 }
2302
2303 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002304 pointerIds.markBit(entry.pointerProperties[0].id);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002305 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2306 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002307 }
2308 }
2309 }
2310
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002311 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002313 // Let the previous window know that the hover sequence is over, unless we already did
2314 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002315 if (mLastHoverWindowHandle != nullptr &&
2316 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2317 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002318 if (DEBUG_HOVER) {
2319 ALOGD("Sending hover exit event to window %s.",
2320 mLastHoverWindowHandle->getName().c_str());
2321 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002322 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2323 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324 }
2325
Garfield Tandf26e862020-07-01 20:18:19 -07002326 // Let the new window know that the hover sequence is starting, unless we already did it
2327 // when dispatching it as is to newTouchedWindowHandle.
2328 if (newHoverWindowHandle != nullptr &&
2329 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2330 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002331 if (DEBUG_HOVER) {
2332 ALOGD("Sending hover enter event to window %s.",
2333 newHoverWindowHandle->getName().c_str());
2334 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002335 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2336 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2337 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338 }
2339 }
2340
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002341 // Ensure that we have at least one foreground window or at least one window that cannot be a
2342 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2343 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2344 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002345 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2346 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002347 return !canReceiveForegroundTouches(
2348 *touchedWindow.windowHandle->getInfo()) ||
2349 (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002350 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002351 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2352 displayId, entry.getDescription().c_str());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002353 injectionResult = InputEventInjectionResult::FAILED;
2354 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 }
2356
Prabir Pradhan5735a322022-04-11 17:23:34 +00002357 // Ensure that all touched windows are valid for injection.
2358 if (entry.injectionState != nullptr) {
2359 std::string errs;
2360 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
2361 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2362 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2363 // dispatched to any uid, since the coords will be zeroed out later.
2364 continue;
2365 }
2366 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2367 if (err) errs += "\n - " + *err;
2368 }
2369 if (!errs.empty()) {
2370 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2371 "%d:%s",
2372 *entry.injectionState->targetUid, errs.c_str());
2373 injectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2374 goto Failed;
2375 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002376 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002377
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378 // Check whether windows listening for outside touches are owned by the same UID. If it is
2379 // set the policy flag that we will not reveal coordinate information to this window.
2380 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002381 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002382 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002383 if (foregroundWindowHandle) {
2384 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002385 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002386 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002387 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2388 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2389 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002390 InputTarget::FLAG_ZERO_COORDS,
2391 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393 }
2394 }
2395 }
2396 }
2397
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398 // If this is the first pointer going down and the touched window has a wallpaper
2399 // then also add the touched wallpaper windows so they are locked in for the duration
2400 // of the touch gesture.
2401 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2402 // engine only supports touch events. We would need to add a mechanism similar
2403 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2404 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002405 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002406 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002407 if (foregroundWindowHandle &&
2408 foregroundWindowHandle->getInfo()->inputConfig.test(
2409 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002410 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002411 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002412 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2413 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002414 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002415 windowHandle->getInfo()->inputConfig.test(
2416 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002417 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002418 .addOrUpdateWindow(windowHandle,
2419 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2420 InputTarget::
2421 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2422 InputTarget::FLAG_DISPATCH_AS_IS,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002423 BitSet32(0), entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424 }
2425 }
2426 }
2427 }
2428
2429 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002430 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002431
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002432 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002434 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2435 inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436 }
2437
2438 // Drop the outside or hover touch windows since we will not care about them
2439 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002440 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441
2442Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002443 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002444 if (!wrongDevice) {
2445 if (switchedDevice) {
2446 if (DEBUG_FOCUS) {
2447 ALOGD("Conflicting pointer actions: Switched to a different device.");
2448 }
2449 *outConflictingPointerActions = true;
2450 }
2451
2452 if (isHoverAction) {
2453 // Started hovering, therefore no longer down.
2454 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002455 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002456 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2457 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002458 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002459 *outConflictingPointerActions = true;
2460 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002461 tempTouchState.reset();
2462 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2463 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2464 tempTouchState.deviceId = entry.deviceId;
2465 tempTouchState.source = entry.source;
2466 tempTouchState.displayId = displayId;
2467 }
2468 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2469 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2470 // All pointers up or canceled.
2471 tempTouchState.reset();
2472 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2473 // First pointer went down.
2474 if (oldState && oldState->down) {
2475 if (DEBUG_FOCUS) {
2476 ALOGD("Conflicting pointer actions: Down received while already down.");
2477 }
2478 *outConflictingPointerActions = true;
2479 }
2480 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2481 // One pointer went up.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002482 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2483 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002485 for (size_t i = 0; i < tempTouchState.windows.size();) {
2486 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2487 touchedWindow.pointerIds.clearBit(pointerId);
2488 if (touchedWindow.pointerIds.isEmpty()) {
2489 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2490 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002492 i += 1;
2493 }
2494 } else if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2495 // If no split, we suppose all touched windows should receive pointer down.
2496 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2497 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2498 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2499 // Ignore drag window for it should just track one pointer.
2500 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2501 continue;
2502 }
2503 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Jeff Brownf086ddb2014-02-11 14:28:48 -08002504 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002505 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002506
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002507 // Save changes unless the action was scroll in which case the temporary touch
2508 // state was only valid for this one action.
2509 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2510 if (tempTouchState.displayId >= 0) {
2511 mTouchStatesByDisplay[displayId] = tempTouchState;
2512 } else {
2513 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002514 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002515 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002517 // Update hover state.
2518 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002519 }
2520
Michael Wrightd02c5b62014-02-10 15:10:22 -08002521 return injectionResult;
2522}
2523
arthurhung6d4bed92021-03-17 11:59:33 +08002524void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002525 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2526 // have an explicit reason to support it.
2527 constexpr bool isStylus = false;
2528
chaviw98318de2021-05-19 16:45:23 -05002529 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002530 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002531 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002532 if (dropWindow) {
2533 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002534 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002535 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002536 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002537 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002538 }
2539 mDragState.reset();
2540}
2541
2542void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002543 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002544 return;
2545 }
2546
arthurhung6d4bed92021-03-17 11:59:33 +08002547 if (!mDragState->isStartDrag) {
2548 mDragState->isStartDrag = true;
2549 mDragState->isStylusButtonDownAtStart =
2550 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2551 }
2552
Arthur Hung54745652022-04-20 07:17:41 +00002553 // Find the pointer index by id.
2554 int32_t pointerIndex = 0;
2555 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2556 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2557 if (pointerProperties.id == mDragState->pointerId) {
2558 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002559 }
Arthur Hung54745652022-04-20 07:17:41 +00002560 }
arthurhung6d4bed92021-03-17 11:59:33 +08002561
Arthur Hung54745652022-04-20 07:17:41 +00002562 if (uint32_t(pointerIndex) == entry.pointerCount) {
2563 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002564 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002565 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002566 return;
2567 }
2568
2569 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2570 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2571 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2572
2573 switch (maskedAction) {
2574 case AMOTION_EVENT_ACTION_MOVE: {
2575 // Handle the special case : stylus button no longer pressed.
2576 bool isStylusButtonDown =
2577 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2578 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2579 finishDragAndDrop(entry.displayId, x, y);
2580 return;
2581 }
2582
2583 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2584 // until we have an explicit reason to support it.
2585 constexpr bool isStylus = false;
2586
2587 const sp<WindowInfoHandle> hoverWindowHandle =
2588 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2589 isStylus, false /*addOutsideTargets*/,
2590 true /*ignoreDragWindow*/);
2591 // enqueue drag exit if needed.
2592 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2593 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2594 if (mDragState->dragHoverWindowHandle != nullptr) {
2595 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2596 y);
2597 }
2598 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2599 }
2600 // enqueue drag location if needed.
2601 if (hoverWindowHandle != nullptr) {
2602 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2603 }
2604 break;
2605 }
2606
2607 case AMOTION_EVENT_ACTION_POINTER_UP:
2608 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2609 break;
2610 }
2611 // The drag pointer is up.
2612 [[fallthrough]];
2613 case AMOTION_EVENT_ACTION_UP:
2614 finishDragAndDrop(entry.displayId, x, y);
2615 break;
2616 case AMOTION_EVENT_ACTION_CANCEL: {
2617 ALOGD("Receiving cancel when drag and drop.");
2618 sendDropWindowCommandLocked(nullptr, 0, 0);
2619 mDragState.reset();
2620 break;
2621 }
arthurhungb89ccb02020-12-30 16:19:01 +08002622 }
2623}
2624
chaviw98318de2021-05-19 16:45:23 -05002625void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002626 int32_t targetFlags, BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002627 std::optional<nsecs_t> firstDownTimeInTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002628 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002629 std::vector<InputTarget>::iterator it =
2630 std::find_if(inputTargets.begin(), inputTargets.end(),
2631 [&windowHandle](const InputTarget& inputTarget) {
2632 return inputTarget.inputChannel->getConnectionToken() ==
2633 windowHandle->getToken();
2634 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002635
chaviw98318de2021-05-19 16:45:23 -05002636 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002637
2638 if (it == inputTargets.end()) {
2639 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002640 std::shared_ptr<InputChannel> inputChannel =
2641 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002642 if (inputChannel == nullptr) {
2643 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2644 return;
2645 }
2646 inputTarget.inputChannel = inputChannel;
2647 inputTarget.flags = targetFlags;
2648 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002649 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002650 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2651 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002652 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002653 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002654 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002655 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002656 inputTargets.push_back(inputTarget);
2657 it = inputTargets.end() - 1;
2658 }
2659
2660 ALOG_ASSERT(it->flags == targetFlags);
2661 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2662
chaviw1ff3d1e2020-07-01 15:53:47 -07002663 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002664}
2665
Michael Wright3dd60e22019-03-27 22:06:44 +00002666void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002667 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002668 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2669 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002670
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002671 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2672 InputTarget target;
2673 target.inputChannel = monitor.inputChannel;
2674 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002675 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2676 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002677 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2678 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002679 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002680 target.setDefaultPointerTransform(target.displayTransform);
2681 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682 }
2683}
2684
Robert Carrc9bf1d32020-04-13 17:21:08 -07002685/**
2686 * Indicate whether one window handle should be considered as obscuring
2687 * another window handle. We only check a few preconditions. Actually
2688 * checking the bounds is left to the caller.
2689 */
chaviw98318de2021-05-19 16:45:23 -05002690static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2691 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002692 // Compare by token so cloned layers aren't counted
2693 if (haveSameToken(windowHandle, otherHandle)) {
2694 return false;
2695 }
2696 auto info = windowHandle->getInfo();
2697 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002698 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002699 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002700 } else if (otherInfo->alpha == 0 &&
2701 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002702 // Those act as if they were invisible, so we don't need to flag them.
2703 // We do want to potentially flag touchable windows even if they have 0
2704 // opacity, since they can consume touches and alter the effects of the
2705 // user interaction (eg. apps that rely on
2706 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2707 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2708 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002709 } else if (info->ownerUid == otherInfo->ownerUid) {
2710 // If ownerUid is the same we don't generate occlusion events as there
2711 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002712 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002713 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002714 return false;
2715 } else if (otherInfo->displayId != info->displayId) {
2716 return false;
2717 }
2718 return true;
2719}
2720
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002721/**
2722 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2723 * untrusted, one should check:
2724 *
2725 * 1. If result.hasBlockingOcclusion is true.
2726 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2727 * BLOCK_UNTRUSTED.
2728 *
2729 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2730 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2731 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2732 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2733 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2734 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2735 *
2736 * If neither of those is true, then it means the touch can be allowed.
2737 */
2738InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002739 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2740 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002741 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002742 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002743 TouchOcclusionInfo info;
2744 info.hasBlockingOcclusion = false;
2745 info.obscuringOpacity = 0;
2746 info.obscuringUid = -1;
2747 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002748 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002749 if (windowHandle == otherHandle) {
2750 break; // All future windows are below us. Exit early.
2751 }
chaviw98318de2021-05-19 16:45:23 -05002752 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002753 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2754 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002755 if (DEBUG_TOUCH_OCCLUSION) {
2756 info.debugInfo.push_back(
2757 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2758 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002759 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2760 // we perform the checks below to see if the touch can be propagated or not based on the
2761 // window's touch occlusion mode
2762 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2763 info.hasBlockingOcclusion = true;
2764 info.obscuringUid = otherInfo->ownerUid;
2765 info.obscuringPackage = otherInfo->packageName;
2766 break;
2767 }
2768 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2769 uint32_t uid = otherInfo->ownerUid;
2770 float opacity =
2771 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2772 // Given windows A and B:
2773 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2774 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2775 opacityByUid[uid] = opacity;
2776 if (opacity > info.obscuringOpacity) {
2777 info.obscuringOpacity = opacity;
2778 info.obscuringUid = uid;
2779 info.obscuringPackage = otherInfo->packageName;
2780 }
2781 }
2782 }
2783 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002784 if (DEBUG_TOUCH_OCCLUSION) {
2785 info.debugInfo.push_back(
2786 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2787 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002788 return info;
2789}
2790
chaviw98318de2021-05-19 16:45:23 -05002791std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002792 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002793 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2794 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2795 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2796 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002797 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2798 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2799 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2800 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2801 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002802 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002803 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002804}
2805
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002806bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2807 if (occlusionInfo.hasBlockingOcclusion) {
2808 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2809 occlusionInfo.obscuringUid);
2810 return false;
2811 }
2812 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2813 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2814 "%.2f, maximum allowed = %.2f)",
2815 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2816 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2817 return false;
2818 }
2819 return true;
2820}
2821
chaviw98318de2021-05-19 16:45:23 -05002822bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002823 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002825 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2826 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002827 if (windowHandle == otherHandle) {
2828 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002829 }
chaviw98318de2021-05-19 16:45:23 -05002830 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002831 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002832 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002833 return true;
2834 }
2835 }
2836 return false;
2837}
2838
chaviw98318de2021-05-19 16:45:23 -05002839bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002840 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002841 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2842 const WindowInfo* windowInfo = windowHandle->getInfo();
2843 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002844 if (windowHandle == otherHandle) {
2845 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002846 }
chaviw98318de2021-05-19 16:45:23 -05002847 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002848 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002849 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002850 return true;
2851 }
2852 }
2853 return false;
2854}
2855
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002856std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002857 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002858 if (applicationHandle != nullptr) {
2859 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002860 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002861 } else {
2862 return applicationHandle->getName();
2863 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002864 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002865 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002867 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868 }
2869}
2870
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002871void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002872 if (!isUserActivityEvent(eventEntry)) {
2873 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002874 return;
2875 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002876 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002877 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002878 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002879 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002880 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002881 if (DEBUG_DISPATCH_CYCLE) {
2882 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2883 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002884 return;
2885 }
2886 }
2887
2888 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002889 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002890 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002891 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2892 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002893 return;
2894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002895
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002896 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002897 eventType = USER_ACTIVITY_EVENT_TOUCH;
2898 }
2899 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002900 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002901 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002902 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2903 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002904 return;
2905 }
2906 eventType = USER_ACTIVITY_EVENT_BUTTON;
2907 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002908 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002909 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002910 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002911 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002912 break;
2913 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914 }
2915
Prabir Pradhancef936d2021-07-21 16:17:52 +00002916 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2917 REQUIRES(mLock) {
2918 scoped_unlock unlock(mLock);
2919 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2920 };
2921 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922}
2923
2924void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002925 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002926 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002927 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002928 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002930 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002931 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002932 ATRACE_NAME(message.c_str());
2933 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002934 if (DEBUG_DISPATCH_CYCLE) {
2935 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2936 "globalScaleFactor=%f, pointerIds=0x%x %s",
2937 connection->getInputChannelName().c_str(), inputTarget.flags,
2938 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2939 inputTarget.getPointerInfoString().c_str());
2940 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002941
2942 // Skip this event if the connection status is not normal.
2943 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002944 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002945 if (DEBUG_DISPATCH_CYCLE) {
2946 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002947 connection->getInputChannelName().c_str(),
2948 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002950 return;
2951 }
2952
2953 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002954 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2955 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2956 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002957 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002958
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002959 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002960 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002961 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
2962 "Splitting motion events requires a down time to be set for the "
2963 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002964 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002965 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
2966 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002967 if (!splitMotionEntry) {
2968 return; // split event was dropped
2969 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002970 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2971 std::string reason = std::string("reason=pointer cancel on split window");
2972 android_log_event_list(LOGTAG_INPUT_CANCEL)
2973 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2974 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002975 if (DEBUG_FOCUS) {
2976 ALOGD("channel '%s' ~ Split motion event.",
2977 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002978 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002979 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002980 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2981 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002982 return;
2983 }
2984 }
2985
2986 // Not splitting. Enqueue dispatch entries for the event as is.
2987 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2988}
2989
2990void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002991 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002992 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002993 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002994 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002995 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002996 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002997 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002998 ATRACE_NAME(message.c_str());
2999 }
3000
hongzuo liu95785e22022-09-06 02:51:35 +00003001 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003002
3003 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003004 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003005 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003006 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003007 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003008 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003009 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003010 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003011 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003012 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003013 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003014 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003015 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003016
3017 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003018 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003019 startDispatchCycleLocked(currentTime, connection);
3020 }
3021}
3022
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003023void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003024 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003025 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003026 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003027 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003028 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3029 connection->getInputChannelName().c_str(),
3030 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003031 ATRACE_NAME(message.c_str());
3032 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003033 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003034 if (!(inputTargetFlags & dispatchMode)) {
3035 return;
3036 }
3037 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
3038
3039 // This is a new event.
3040 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003041 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003042 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003043
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003044 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3045 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003046 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003048 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003049 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003050 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003051 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003052 dispatchEntry->resolvedAction = keyEntry.action;
3053 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003055 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3056 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003057 if (DEBUG_DISPATCH_CYCLE) {
3058 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3059 "event",
3060 connection->getInputChannelName().c_str());
3061 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003062 return; // skip the inconsistent event
3063 }
3064 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003065 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003067 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003068 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003069 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3070 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3071 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3072 static_cast<int32_t>(IdGenerator::Source::OTHER);
3073 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003074 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3075 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3076 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3077 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3078 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3079 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3080 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3081 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3082 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3083 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3084 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003085 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003086 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003087 }
3088 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003089 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3090 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003091 if (DEBUG_DISPATCH_CYCLE) {
3092 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3093 "enter event",
3094 connection->getInputChannelName().c_str());
3095 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003096 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3097 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003098 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3099 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003101 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003102 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3103 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3104 }
3105 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3106 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3107 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003108
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003109 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3110 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003111 if (DEBUG_DISPATCH_CYCLE) {
3112 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3113 "event",
3114 connection->getInputChannelName().c_str());
3115 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003116 return; // skip the inconsistent event
3117 }
3118
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003119 dispatchEntry->resolvedEventId =
3120 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3121 ? mIdGenerator.nextId()
3122 : motionEntry.id;
3123 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3124 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3125 ") to MotionEvent(id=0x%" PRIx32 ").",
3126 motionEntry.id, dispatchEntry->resolvedEventId);
3127 ATRACE_NAME(message.c_str());
3128 }
3129
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003130 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3131 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3132 // Skip reporting pointer down outside focus to the policy.
3133 break;
3134 }
3135
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003136 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003137 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003138
3139 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003140 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003141 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003142 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003143 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3144 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003145 break;
3146 }
Chris Yef59a2f42020-10-16 12:55:26 -07003147 case EventEntry::Type::SENSOR: {
3148 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3149 break;
3150 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003151 case EventEntry::Type::CONFIGURATION_CHANGED:
3152 case EventEntry::Type::DEVICE_RESET: {
3153 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003154 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003155 break;
3156 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 }
3158
3159 // Remember that we are waiting for this dispatch to complete.
3160 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003161 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162 }
3163
3164 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003165 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003166 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003167}
3168
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003169/**
3170 * This function is purely for debugging. It helps us understand where the user interaction
3171 * was taking place. For example, if user is touching launcher, we will see a log that user
3172 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3173 * We will see both launcher and wallpaper in that list.
3174 * Once the interaction with a particular set of connections starts, no new logs will be printed
3175 * until the set of interacted connections changes.
3176 *
3177 * The following items are skipped, to reduce the logspam:
3178 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3179 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3180 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3181 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3182 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003183 */
3184void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3185 const std::vector<InputTarget>& targets) {
3186 // Skip ACTION_UP events, and all events other than keys and motions
3187 if (entry.type == EventEntry::Type::KEY) {
3188 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3189 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3190 return;
3191 }
3192 } else if (entry.type == EventEntry::Type::MOTION) {
3193 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3194 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3195 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3196 return;
3197 }
3198 } else {
3199 return; // Not a key or a motion
3200 }
3201
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003202 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003203 std::vector<sp<Connection>> newConnections;
3204 for (const InputTarget& target : targets) {
3205 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3206 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3207 continue; // Skip windows that receive ACTION_OUTSIDE
3208 }
3209
3210 sp<IBinder> token = target.inputChannel->getConnectionToken();
3211 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003212 if (connection == nullptr) {
3213 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003214 }
3215 newConnectionTokens.insert(std::move(token));
3216 newConnections.emplace_back(connection);
3217 }
3218 if (newConnectionTokens == mInteractionConnectionTokens) {
3219 return; // no change
3220 }
3221 mInteractionConnectionTokens = newConnectionTokens;
3222
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003223 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003224 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003225 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003226 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003227 std::string message = "Interaction with: " + targetList;
3228 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003229 message += "<none>";
3230 }
3231 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3232}
3233
chaviwfd6d3512019-03-25 13:23:49 -07003234void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003235 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003236 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003237 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3238 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003239 return;
3240 }
3241
Vishnu Nairc519ff72021-01-21 08:23:08 -08003242 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003243 if (focusedToken == token) {
3244 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003245 return;
3246 }
3247
Prabir Pradhancef936d2021-07-21 16:17:52 +00003248 auto command = [this, token]() REQUIRES(mLock) {
3249 scoped_unlock unlock(mLock);
3250 mPolicy->onPointerDownOutsideFocus(token);
3251 };
3252 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253}
3254
3255void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003256 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003257 if (ATRACE_ENABLED()) {
3258 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003259 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003260 ATRACE_NAME(message.c_str());
3261 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003262 if (DEBUG_DISPATCH_CYCLE) {
3263 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3264 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003266 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003267 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003268 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003269 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003270 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271
3272 // Publish the event.
3273 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003274 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3275 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003276 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003277 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3278 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003279
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003280 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003281 status = connection->inputPublisher
3282 .publishKeyEvent(dispatchEntry->seq,
3283 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3284 keyEntry.source, keyEntry.displayId,
3285 std::move(hmac), dispatchEntry->resolvedAction,
3286 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3287 keyEntry.scanCode, keyEntry.metaState,
3288 keyEntry.repeatCount, keyEntry.downTime,
3289 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003290 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291 }
3292
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003293 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003294 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003296 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003297 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003298
chaviw82357092020-01-28 13:13:06 -08003299 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003300 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003301 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3302 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003303 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003304 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3305 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003306 // Don't apply window scale here since we don't want scale to affect raw
3307 // coordinates. The scale will be sent back to the client and applied
3308 // later when requesting relative coordinates.
3309 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3310 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003311 }
3312 usingCoords = scaledCoords;
3313 }
3314 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003315 // We don't want the dispatch target to know.
3316 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003317 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 scaledCoords[i].clear();
3319 }
3320 usingCoords = scaledCoords;
3321 }
3322 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003323
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003324 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003325
3326 // Publish the motion event.
3327 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003328 .publishMotionEvent(dispatchEntry->seq,
3329 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003330 motionEntry.deviceId, motionEntry.source,
3331 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003332 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003333 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003334 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003335 motionEntry.edgeFlags, motionEntry.metaState,
3336 motionEntry.buttonState,
3337 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003338 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003339 motionEntry.xPrecision, motionEntry.yPrecision,
3340 motionEntry.xCursorPosition,
3341 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003342 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003343 motionEntry.downTime, motionEntry.eventTime,
3344 motionEntry.pointerCount,
3345 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003346 break;
3347 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003348
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003349 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003350 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003351 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003352 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003353 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003354 break;
3355 }
3356
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003357 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3358 const TouchModeEntry& touchModeEntry =
3359 static_cast<const TouchModeEntry&>(eventEntry);
3360 status = connection->inputPublisher
3361 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3362 touchModeEntry.inTouchMode);
3363
3364 break;
3365 }
3366
Prabir Pradhan99987712020-11-10 18:43:05 -08003367 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3368 const auto& captureEntry =
3369 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3370 status = connection->inputPublisher
3371 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003372 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003373 break;
3374 }
3375
arthurhungb89ccb02020-12-30 16:19:01 +08003376 case EventEntry::Type::DRAG: {
3377 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3378 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3379 dragEntry.id, dragEntry.x,
3380 dragEntry.y,
3381 dragEntry.isExiting);
3382 break;
3383 }
3384
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003385 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003386 case EventEntry::Type::DEVICE_RESET:
3387 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003388 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003389 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003390 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392 }
3393
3394 // Check the result.
3395 if (status) {
3396 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003397 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003398 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003399 "This is unexpected because the wait queue is empty, so the pipe "
3400 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003401 "event to it, status=%s(%d)",
3402 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3403 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3405 } else {
3406 // Pipe is full and we are waiting for the app to finish process some events
3407 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003408 if (DEBUG_DISPATCH_CYCLE) {
3409 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3410 "waiting for the application to catch up",
3411 connection->getInputChannelName().c_str());
3412 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413 }
3414 } else {
3415 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003416 "status=%s(%d)",
3417 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3418 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3420 }
3421 return;
3422 }
3423
3424 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003425 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3426 connection->outboundQueue.end(),
3427 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003428 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003429 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003430 if (connection->responsive) {
3431 mAnrTracker.insert(dispatchEntry->timeoutTime,
3432 connection->inputChannel->getConnectionToken());
3433 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003434 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435 }
3436}
3437
chaviw09c8d2d2020-08-24 15:48:26 -07003438std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3439 size_t size;
3440 switch (event.type) {
3441 case VerifiedInputEvent::Type::KEY: {
3442 size = sizeof(VerifiedKeyEvent);
3443 break;
3444 }
3445 case VerifiedInputEvent::Type::MOTION: {
3446 size = sizeof(VerifiedMotionEvent);
3447 break;
3448 }
3449 }
3450 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3451 return mHmacKeyManager.sign(start, size);
3452}
3453
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003454const std::array<uint8_t, 32> InputDispatcher::getSignature(
3455 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003456 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3457 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003458 // Only sign events up and down events as the purely move events
3459 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003460 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003461 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003462
3463 VerifiedMotionEvent verifiedEvent =
3464 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3465 verifiedEvent.actionMasked = actionMasked;
3466 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3467 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003468}
3469
3470const std::array<uint8_t, 32> InputDispatcher::getSignature(
3471 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3472 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3473 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3474 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003475 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003476}
3477
Michael Wrightd02c5b62014-02-10 15:10:22 -08003478void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003479 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003480 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003481 if (DEBUG_DISPATCH_CYCLE) {
3482 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3483 connection->getInputChannelName().c_str(), seq, toString(handled));
3484 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003485
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003486 if (connection->status == Connection::Status::BROKEN ||
3487 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003488 return;
3489 }
3490
3491 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003492 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3493 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3494 };
3495 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496}
3497
3498void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003499 const sp<Connection>& connection,
3500 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003501 if (DEBUG_DISPATCH_CYCLE) {
3502 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3503 connection->getInputChannelName().c_str(), toString(notify));
3504 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505
3506 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003507 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003508 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003509 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003510 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511
3512 // The connection appears to be unrecoverably broken.
3513 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003514 if (connection->status == Connection::Status::NORMAL) {
3515 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516
3517 if (notify) {
3518 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003519 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3520 connection->getInputChannelName().c_str());
3521
3522 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003523 scoped_unlock unlock(mLock);
3524 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3525 };
3526 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 }
3528 }
3529}
3530
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003531void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3532 while (!queue.empty()) {
3533 DispatchEntry* dispatchEntry = queue.front();
3534 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003535 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003536 }
3537}
3538
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003539void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003541 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542 }
3543 delete dispatchEntry;
3544}
3545
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003546int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3547 std::scoped_lock _l(mLock);
3548 sp<Connection> connection = getConnectionLocked(connectionToken);
3549 if (connection == nullptr) {
3550 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3551 connectionToken.get(), events);
3552 return 0; // remove the callback
3553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003554
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003555 bool notify;
3556 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3557 if (!(events & ALOOPER_EVENT_INPUT)) {
3558 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3559 "events=0x%x",
3560 connection->getInputChannelName().c_str(), events);
3561 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003562 }
3563
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003564 nsecs_t currentTime = now();
3565 bool gotOne = false;
3566 status_t status = OK;
3567 for (;;) {
3568 Result<InputPublisher::ConsumerResponse> result =
3569 connection->inputPublisher.receiveConsumerResponse();
3570 if (!result.ok()) {
3571 status = result.error().code();
3572 break;
3573 }
3574
3575 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3576 const InputPublisher::Finished& finish =
3577 std::get<InputPublisher::Finished>(*result);
3578 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3579 finish.consumeTime);
3580 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003581 if (shouldReportMetricsForConnection(*connection)) {
3582 const InputPublisher::Timeline& timeline =
3583 std::get<InputPublisher::Timeline>(*result);
3584 mLatencyTracker
3585 .trackGraphicsLatency(timeline.inputEventId,
3586 connection->inputChannel->getConnectionToken(),
3587 std::move(timeline.graphicsTimeline));
3588 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003589 }
3590 gotOne = true;
3591 }
3592 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003593 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003594 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595 return 1;
3596 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 }
3598
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003599 notify = status != DEAD_OBJECT || !connection->monitor;
3600 if (notify) {
3601 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3602 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3603 status);
3604 }
3605 } else {
3606 // Monitor channels are never explicitly unregistered.
3607 // We do it automatically when the remote endpoint is closed so don't warn about them.
3608 const bool stillHaveWindowHandle =
3609 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3610 notify = !connection->monitor && stillHaveWindowHandle;
3611 if (notify) {
3612 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3613 connection->getInputChannelName().c_str(), events);
3614 }
3615 }
3616
3617 // Remove the channel.
3618 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3619 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620}
3621
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003622void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003624 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003625 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 }
3627}
3628
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003629void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003630 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003631 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003632 for (const Monitor& monitor : monitors) {
3633 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003634 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003635 }
3636}
3637
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003639 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003640 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003641 if (connection == nullptr) {
3642 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003644
3645 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646}
3647
3648void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3649 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003650 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003651 return;
3652 }
3653
3654 nsecs_t currentTime = now();
3655
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003656 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003657 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003659 if (cancelationEvents.empty()) {
3660 return;
3661 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003662 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3663 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3664 "with reality: %s, mode=%d.",
3665 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3666 options.mode);
3667 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003668
Arthur Hungb3307ee2021-10-14 10:57:37 +00003669 std::string reason = std::string("reason=").append(options.reason);
3670 android_log_event_list(LOGTAG_INPUT_CANCEL)
3671 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3672
Svet Ganov5d3bc372020-01-26 23:11:07 -08003673 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003674 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003675 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3676 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003677 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003678 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003679 target.globalScaleFactor = windowInfo->globalScaleFactor;
3680 }
3681 target.inputChannel = connection->inputChannel;
3682 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3683
hongzuo liu95785e22022-09-06 02:51:35 +00003684 const bool wasEmpty = connection->outboundQueue.empty();
3685
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003686 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003687 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003688 switch (cancelationEventEntry->type) {
3689 case EventEntry::Type::KEY: {
3690 logOutboundKeyDetails("cancel - ",
3691 static_cast<const KeyEntry&>(*cancelationEventEntry));
3692 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003694 case EventEntry::Type::MOTION: {
3695 logOutboundMotionDetails("cancel - ",
3696 static_cast<const MotionEntry&>(*cancelationEventEntry));
3697 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003699 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003700 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003701 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3702 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003703 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003704 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003705 break;
3706 }
3707 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003708 case EventEntry::Type::DEVICE_RESET:
3709 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003710 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003711 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003712 break;
3713 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714 }
3715
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003716 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3717 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003718 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003719
hongzuo liu95785e22022-09-06 02:51:35 +00003720 // If the outbound queue was previously empty, start the dispatch cycle going.
3721 if (wasEmpty && !connection->outboundQueue.empty()) {
3722 startDispatchCycleLocked(currentTime, connection);
3723 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724}
3725
Svet Ganov5d3bc372020-01-26 23:11:07 -08003726void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003727 const nsecs_t downTime, const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003728 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003729 return;
3730 }
3731
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003732 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003733 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003734
3735 if (downEvents.empty()) {
3736 return;
3737 }
3738
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003739 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003740 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3741 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003742 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003743
3744 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003745 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003746 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3747 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003748 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003749 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003750 target.globalScaleFactor = windowInfo->globalScaleFactor;
3751 }
3752 target.inputChannel = connection->inputChannel;
3753 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3754
hongzuo liu95785e22022-09-06 02:51:35 +00003755 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003756 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003757 switch (downEventEntry->type) {
3758 case EventEntry::Type::MOTION: {
3759 logOutboundMotionDetails("down - ",
3760 static_cast<const MotionEntry&>(*downEventEntry));
3761 break;
3762 }
3763
3764 case EventEntry::Type::KEY:
3765 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003766 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003767 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003768 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003769 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003770 case EventEntry::Type::SENSOR:
3771 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003772 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003773 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003774 break;
3775 }
3776 }
3777
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003778 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3779 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003780 }
3781
hongzuo liu95785e22022-09-06 02:51:35 +00003782 // If the outbound queue was previously empty, start the dispatch cycle going.
3783 if (wasEmpty && !connection->outboundQueue.empty()) {
3784 startDispatchCycleLocked(downTime, connection);
3785 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003786}
3787
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003788std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003789 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790 ALOG_ASSERT(pointerIds.value != 0);
3791
3792 uint32_t splitPointerIndexMap[MAX_POINTERS];
3793 PointerProperties splitPointerProperties[MAX_POINTERS];
3794 PointerCoords splitPointerCoords[MAX_POINTERS];
3795
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003796 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797 uint32_t splitPointerCount = 0;
3798
3799 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003800 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003801 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003802 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803 uint32_t pointerId = uint32_t(pointerProperties.id);
3804 if (pointerIds.hasBit(pointerId)) {
3805 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3806 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3807 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003808 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003809 splitPointerCount += 1;
3810 }
3811 }
3812
3813 if (splitPointerCount != pointerIds.count()) {
3814 // This is bad. We are missing some of the pointers that we expected to deliver.
3815 // Most likely this indicates that we received an ACTION_MOVE events that has
3816 // different pointer ids than we expected based on the previous ACTION_DOWN
3817 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3818 // in this way.
3819 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003820 "we expected there to be %d pointers. This probably means we received "
3821 "a broken sequence of pointer ids from the input device.",
3822 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003823 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824 }
3825
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003826 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003827 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003828 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3829 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003830 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3831 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003832 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833 uint32_t pointerId = uint32_t(pointerProperties.id);
3834 if (pointerIds.hasBit(pointerId)) {
3835 if (pointerIds.count() == 1) {
3836 // The first/last pointer went down/up.
3837 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003838 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003839 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3840 ? AMOTION_EVENT_ACTION_CANCEL
3841 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003842 } else {
3843 // A secondary pointer went down/up.
3844 uint32_t splitPointerIndex = 0;
3845 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3846 splitPointerIndex += 1;
3847 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003848 action = maskedAction |
3849 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003850 }
3851 } else {
3852 // An unrelated pointer changed.
3853 action = AMOTION_EVENT_ACTION_MOVE;
3854 }
3855 }
3856
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003857 if (action == AMOTION_EVENT_ACTION_DOWN) {
3858 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3859 "Split motion event has mismatching downTime and eventTime for "
3860 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3861 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3862 }
3863
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003864 int32_t newId = mIdGenerator.nextId();
3865 if (ATRACE_ENABLED()) {
3866 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3867 ") to MotionEvent(id=0x%" PRIx32 ").",
3868 originalMotionEntry.id, newId);
3869 ATRACE_NAME(message.c_str());
3870 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003871 std::unique_ptr<MotionEntry> splitMotionEntry =
3872 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3873 originalMotionEntry.deviceId, originalMotionEntry.source,
3874 originalMotionEntry.displayId,
3875 originalMotionEntry.policyFlags, action,
3876 originalMotionEntry.actionButton,
3877 originalMotionEntry.flags, originalMotionEntry.metaState,
3878 originalMotionEntry.buttonState,
3879 originalMotionEntry.classification,
3880 originalMotionEntry.edgeFlags,
3881 originalMotionEntry.xPrecision,
3882 originalMotionEntry.yPrecision,
3883 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003884 originalMotionEntry.yCursorPosition, splitDownTime,
3885 splitPointerCount, splitPointerProperties,
3886 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003888 if (originalMotionEntry.injectionState) {
3889 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003890 splitMotionEntry->injectionState->refCount += 1;
3891 }
3892
3893 return splitMotionEntry;
3894}
3895
3896void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003897 if (DEBUG_INBOUND_EVENT_DETAILS) {
3898 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3899 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900
Antonio Kantekf16f2832021-09-28 04:39:20 +00003901 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003903 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003905 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3906 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3907 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908 } // release lock
3909
3910 if (needWake) {
3911 mLooper->wake();
3912 }
3913}
3914
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003915/**
3916 * If one of the meta shortcuts is detected, process them here:
3917 * Meta + Backspace -> generate BACK
3918 * Meta + Enter -> generate HOME
3919 * This will potentially overwrite keyCode and metaState.
3920 */
3921void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003922 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003923 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3924 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3925 if (keyCode == AKEYCODE_DEL) {
3926 newKeyCode = AKEYCODE_BACK;
3927 } else if (keyCode == AKEYCODE_ENTER) {
3928 newKeyCode = AKEYCODE_HOME;
3929 }
3930 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003931 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003932 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003933 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003934 keyCode = newKeyCode;
3935 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3936 }
3937 } else if (action == AKEY_EVENT_ACTION_UP) {
3938 // In order to maintain a consistent stream of up and down events, check to see if the key
3939 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3940 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003941 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003942 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003943 auto replacementIt = mReplacedKeys.find(replacement);
3944 if (replacementIt != mReplacedKeys.end()) {
3945 keyCode = replacementIt->second;
3946 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003947 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3948 }
3949 }
3950}
3951
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003953 if (DEBUG_INBOUND_EVENT_DETAILS) {
3954 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3955 "policyFlags=0x%x, action=0x%x, "
3956 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3957 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3958 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3959 args->downTime);
3960 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961 if (!validateKeyEvent(args->action)) {
3962 return;
3963 }
3964
3965 uint32_t policyFlags = args->policyFlags;
3966 int32_t flags = args->flags;
3967 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003968 // InputDispatcher tracks and generates key repeats on behalf of
3969 // whatever notifies it, so repeatCount should always be set to 0
3970 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3972 policyFlags |= POLICY_FLAG_VIRTUAL;
3973 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 if (policyFlags & POLICY_FLAG_FUNCTION) {
3976 metaState |= AMETA_FUNCTION_ON;
3977 }
3978
3979 policyFlags |= POLICY_FLAG_TRUSTED;
3980
Michael Wright78f24442014-08-06 15:55:28 -07003981 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003982 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003983
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003985 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003986 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3987 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988
Michael Wright2b3c3302018-03-02 17:19:13 +00003989 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003991 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3992 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003993 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003994 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995
Antonio Kantekf16f2832021-09-28 04:39:20 +00003996 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003997 { // acquire lock
3998 mLock.lock();
3999
4000 if (shouldSendKeyToInputFilterLocked(args)) {
4001 mLock.unlock();
4002
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004003 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4005 return; // event was consumed by the filter
4006 }
4007
4008 mLock.lock();
4009 }
4010
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004011 std::unique_ptr<KeyEntry> newEntry =
4012 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4013 args->displayId, policyFlags, args->action, flags,
4014 keyCode, args->scanCode, metaState, repeatCount,
4015 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004017 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018 mLock.unlock();
4019 } // release lock
4020
4021 if (needWake) {
4022 mLooper->wake();
4023 }
4024}
4025
4026bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4027 return mInputFilterEnabled;
4028}
4029
4030void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004031 if (DEBUG_INBOUND_EVENT_DETAILS) {
4032 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4033 "displayId=%" PRId32 ", policyFlags=0x%x, "
4034 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
4035 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4036 "yCursorPosition=%f, downTime=%" PRId64,
4037 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
4038 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
4039 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
4040 args->xCursorPosition, args->yCursorPosition, args->downTime);
4041 for (uint32_t i = 0; i < args->pointerCount; i++) {
4042 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4043 "x=%f, y=%f, pressure=%f, size=%f, "
4044 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4045 "orientation=%f",
4046 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4047 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4048 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4049 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4050 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4051 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4052 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4053 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4054 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4055 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004057 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004058 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4059 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060 return;
4061 }
4062
4063 uint32_t policyFlags = args->policyFlags;
4064 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004065
4066 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004067 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004068 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4069 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004070 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004071 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072
Antonio Kantekf16f2832021-09-28 04:39:20 +00004073 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074 { // acquire lock
4075 mLock.lock();
4076
4077 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004078 ui::Transform displayTransform;
4079 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4080 displayTransform = it->second.transform;
4081 }
4082
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083 mLock.unlock();
4084
4085 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004086 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4087 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004088 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004089 displayTransform, args->xPrecision, args->yPrecision,
4090 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004091 args->downTime, args->eventTime, args->pointerCount,
4092 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004093
4094 policyFlags |= POLICY_FLAG_FILTERED;
4095 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4096 return; // event was consumed by the filter
4097 }
4098
4099 mLock.lock();
4100 }
4101
4102 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004103 std::unique_ptr<MotionEntry> newEntry =
4104 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4105 args->source, args->displayId, policyFlags,
4106 args->action, args->actionButton, args->flags,
4107 args->metaState, args->buttonState,
4108 args->classification, args->edgeFlags,
4109 args->xPrecision, args->yPrecision,
4110 args->xCursorPosition, args->yCursorPosition,
4111 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004112 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004114 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4115 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4116 !mInputFilterEnabled) {
4117 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4118 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4119 }
4120
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004121 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122 mLock.unlock();
4123 } // release lock
4124
4125 if (needWake) {
4126 mLooper->wake();
4127 }
4128}
4129
Chris Yef59a2f42020-10-16 12:55:26 -07004130void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004131 if (DEBUG_INBOUND_EVENT_DETAILS) {
4132 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4133 " sensorType=%s",
4134 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004135 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004136 }
Chris Yef59a2f42020-10-16 12:55:26 -07004137
Antonio Kantekf16f2832021-09-28 04:39:20 +00004138 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004139 { // acquire lock
4140 mLock.lock();
4141
4142 // Just enqueue a new sensor event.
4143 std::unique_ptr<SensorEntry> newEntry =
4144 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4145 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4146 args->sensorType, args->accuracy,
4147 args->accuracyChanged, args->values);
4148
4149 needWake = enqueueInboundEventLocked(std::move(newEntry));
4150 mLock.unlock();
4151 } // release lock
4152
4153 if (needWake) {
4154 mLooper->wake();
4155 }
4156}
4157
Chris Yefb552902021-02-03 17:18:37 -08004158void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004159 if (DEBUG_INBOUND_EVENT_DETAILS) {
4160 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4161 args->deviceId, args->isOn);
4162 }
Chris Yefb552902021-02-03 17:18:37 -08004163 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4164}
4165
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004167 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168}
4169
4170void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004171 if (DEBUG_INBOUND_EVENT_DETAILS) {
4172 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4173 "switchMask=0x%08x",
4174 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4175 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176
4177 uint32_t policyFlags = args->policyFlags;
4178 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004179 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180}
4181
4182void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004183 if (DEBUG_INBOUND_EVENT_DETAILS) {
4184 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4185 args->deviceId);
4186 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187
Antonio Kantekf16f2832021-09-28 04:39:20 +00004188 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004190 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004191
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004192 std::unique_ptr<DeviceResetEntry> newEntry =
4193 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4194 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195 } // release lock
4196
4197 if (needWake) {
4198 mLooper->wake();
4199 }
4200}
4201
Prabir Pradhan7e186182020-11-10 13:56:45 -08004202void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004203 if (DEBUG_INBOUND_EVENT_DETAILS) {
4204 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004205 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004206 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004207
Antonio Kantekf16f2832021-09-28 04:39:20 +00004208 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004209 { // acquire lock
4210 std::scoped_lock _l(mLock);
4211 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004212 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004213 needWake = enqueueInboundEventLocked(std::move(entry));
4214 } // release lock
4215
4216 if (needWake) {
4217 mLooper->wake();
4218 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004219}
4220
Prabir Pradhan5735a322022-04-11 17:23:34 +00004221InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4222 std::optional<int32_t> targetUid,
4223 InputEventInjectionSync syncMode,
4224 std::chrono::milliseconds timeout,
4225 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004226 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004227 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4228 "policyFlags=0x%08x",
4229 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4230 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004231 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004232 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233
Prabir Pradhan5735a322022-04-11 17:23:34 +00004234 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004236 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004237 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4238 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4239 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4240 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4241 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004242 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004243 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004244 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004245 }
4246
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004247 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004249 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004250 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4251 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004252 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004253 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004254 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004256 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004257 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4258 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4259 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004260 int32_t keyCode = incomingKey.getKeyCode();
4261 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004262 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004263 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004264 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004265 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004266 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4267 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4268 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004270 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4271 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004272 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004273
4274 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4275 android::base::Timer t;
4276 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4277 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4278 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4279 std::to_string(t.duration().count()).c_str());
4280 }
4281 }
4282
4283 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004284 std::unique_ptr<KeyEntry> injectedEntry =
4285 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004286 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004287 incomingKey.getDisplayId(), policyFlags, action,
4288 flags, keyCode, incomingKey.getScanCode(), metaState,
4289 incomingKey.getRepeatCount(),
4290 incomingKey.getDownTime());
4291 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004292 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293 }
4294
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004295 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004296 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004297 const int32_t action = motionEvent.getAction();
4298 const bool isPointerEvent =
4299 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4300 // If a pointer event has no displayId specified, inject it to the default display.
4301 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4302 ? ADISPLAY_ID_DEFAULT
4303 : event->getDisplayId();
4304 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004305 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004306 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004307 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004308 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004309 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004310 }
4311
4312 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004313 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004314 android::base::Timer t;
4315 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4316 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4317 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4318 std::to_string(t.duration().count()).c_str());
4319 }
4320 }
4321
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004322 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4323 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4324 }
4325
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004326 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004327 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4328 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004329 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004330 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4331 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004332 displayId, policyFlags, action, actionButton,
4333 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004334 motionEvent.getButtonState(),
4335 motionEvent.getClassification(),
4336 motionEvent.getEdgeFlags(),
4337 motionEvent.getXPrecision(),
4338 motionEvent.getYPrecision(),
4339 motionEvent.getRawXCursorPosition(),
4340 motionEvent.getRawYCursorPosition(),
4341 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004342 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004343 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004344 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004345 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004346 sampleEventTimes += 1;
4347 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004348 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004349 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4350 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004351 displayId, policyFlags, action, actionButton,
4352 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004353 motionEvent.getButtonState(),
4354 motionEvent.getClassification(),
4355 motionEvent.getEdgeFlags(),
4356 motionEvent.getXPrecision(),
4357 motionEvent.getYPrecision(),
4358 motionEvent.getRawXCursorPosition(),
4359 motionEvent.getRawYCursorPosition(),
4360 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004361 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004362 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004363 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4364 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004365 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004366 }
4367 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004370 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004371 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004372 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 }
4374
Prabir Pradhan5735a322022-04-11 17:23:34 +00004375 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004376 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377 injectionState->injectionIsAsync = true;
4378 }
4379
4380 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004381 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382
4383 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004384 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004385 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004386 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387 }
4388
4389 mLock.unlock();
4390
4391 if (needWake) {
4392 mLooper->wake();
4393 }
4394
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004395 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004397 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004398
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004399 if (syncMode == InputEventInjectionSync::NONE) {
4400 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401 } else {
4402 for (;;) {
4403 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004404 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405 break;
4406 }
4407
4408 nsecs_t remainingTimeout = endTime - now();
4409 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004410 if (DEBUG_INJECTION) {
4411 ALOGD("injectInputEvent - Timed out waiting for injection result "
4412 "to become available.");
4413 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004414 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004415 break;
4416 }
4417
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004418 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004419 }
4420
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004421 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4422 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004423 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004424 if (DEBUG_INJECTION) {
4425 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4426 injectionState->pendingForegroundDispatches);
4427 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004428 nsecs_t remainingTimeout = endTime - now();
4429 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004430 if (DEBUG_INJECTION) {
4431 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4432 "dispatches to finish.");
4433 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004434 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004435 break;
4436 }
4437
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004438 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439 }
4440 }
4441 }
4442
4443 injectionState->release();
4444 } // release lock
4445
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004446 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004447 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004448 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449
4450 return injectionResult;
4451}
4452
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004453std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004454 std::array<uint8_t, 32> calculatedHmac;
4455 std::unique_ptr<VerifiedInputEvent> result;
4456 switch (event.getType()) {
4457 case AINPUT_EVENT_TYPE_KEY: {
4458 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4459 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4460 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004461 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004462 break;
4463 }
4464 case AINPUT_EVENT_TYPE_MOTION: {
4465 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4466 VerifiedMotionEvent verifiedMotionEvent =
4467 verifiedMotionEventFromMotionEvent(motionEvent);
4468 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004469 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004470 break;
4471 }
4472 default: {
4473 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4474 return nullptr;
4475 }
4476 }
4477 if (calculatedHmac == INVALID_HMAC) {
4478 return nullptr;
4479 }
4480 if (calculatedHmac != event.getHmac()) {
4481 return nullptr;
4482 }
4483 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004484}
4485
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004486void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004487 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004488 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004489 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004490 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004491 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004492 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004494 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495 // Log the outcome since the injector did not wait for the injection result.
4496 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004497 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004498 ALOGV("Asynchronous input event injection succeeded.");
4499 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004500 case InputEventInjectionResult::TARGET_MISMATCH:
4501 ALOGV("Asynchronous input event injection target mismatch.");
4502 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004503 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004504 ALOGW("Asynchronous input event injection failed.");
4505 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004506 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004507 ALOGW("Asynchronous input event injection timed out.");
4508 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004509 case InputEventInjectionResult::PENDING:
4510 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4511 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512 }
4513 }
4514
4515 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004516 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004517 }
4518}
4519
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004520void InputDispatcher::transformMotionEntryForInjectionLocked(
4521 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004522 // Input injection works in the logical display coordinate space, but the input pipeline works
4523 // display space, so we need to transform the injected events accordingly.
4524 const auto it = mDisplayInfos.find(entry.displayId);
4525 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004526 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004527
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004528 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4529 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4530 const vec2 cursor =
4531 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4532 {entry.xCursorPosition, entry.yCursorPosition});
4533 entry.xCursorPosition = cursor.x;
4534 entry.yCursorPosition = cursor.y;
4535 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004536 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004537 entry.pointerCoords[i] =
4538 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4539 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004540 }
4541}
4542
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004543void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4544 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004545 if (injectionState) {
4546 injectionState->pendingForegroundDispatches += 1;
4547 }
4548}
4549
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004550void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4551 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004552 if (injectionState) {
4553 injectionState->pendingForegroundDispatches -= 1;
4554
4555 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004556 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557 }
4558 }
4559}
4560
chaviw98318de2021-05-19 16:45:23 -05004561const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004562 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004563 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004564 auto it = mWindowHandlesByDisplay.find(displayId);
4565 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004566}
4567
chaviw98318de2021-05-19 16:45:23 -05004568sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004569 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004570 if (windowHandleToken == nullptr) {
4571 return nullptr;
4572 }
4573
Arthur Hungb92218b2018-08-14 12:00:21 +08004574 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004575 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4576 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004577 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004578 return windowHandle;
4579 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004580 }
4581 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004582 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004583}
4584
chaviw98318de2021-05-19 16:45:23 -05004585sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4586 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004587 if (windowHandleToken == nullptr) {
4588 return nullptr;
4589 }
4590
chaviw98318de2021-05-19 16:45:23 -05004591 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004592 if (windowHandle->getToken() == windowHandleToken) {
4593 return windowHandle;
4594 }
4595 }
4596 return nullptr;
4597}
4598
chaviw98318de2021-05-19 16:45:23 -05004599sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4600 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004601 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004602 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4603 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004604 if (handle->getId() == windowHandle->getId() &&
4605 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004606 if (windowHandle->getInfo()->displayId != it.first) {
4607 ALOGE("Found window %s in display %" PRId32
4608 ", but it should belong to display %" PRId32,
4609 windowHandle->getName().c_str(), it.first,
4610 windowHandle->getInfo()->displayId);
4611 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004612 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004613 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004614 }
4615 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004616 return nullptr;
4617}
4618
chaviw98318de2021-05-19 16:45:23 -05004619sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004620 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4621 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004622}
4623
chaviw98318de2021-05-19 16:45:23 -05004624bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004625 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4626 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004627 windowHandle.getInfo()->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004628 if (connection != nullptr && noInputChannel) {
4629 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4630 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4631 return false;
4632 }
4633
4634 if (connection == nullptr) {
4635 if (!noInputChannel) {
4636 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4637 }
4638 return false;
4639 }
4640 if (!connection->responsive) {
4641 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4642 return false;
4643 }
4644 return true;
4645}
4646
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004647std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4648 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004649 auto connectionIt = mConnectionsByToken.find(token);
4650 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004651 return nullptr;
4652 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004653 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004654}
4655
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004656void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004657 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4658 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004659 // Remove all handles on a display if there are no windows left.
4660 mWindowHandlesByDisplay.erase(displayId);
4661 return;
4662 }
4663
4664 // Since we compare the pointer of input window handles across window updates, we need
4665 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004666 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4667 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4668 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004669 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004670 }
4671
chaviw98318de2021-05-19 16:45:23 -05004672 std::vector<sp<WindowInfoHandle>> newHandles;
4673 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004674 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004675 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004676 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004677 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004678 const bool canReceiveInput =
4679 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4680 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004681 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004682 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004683 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004684 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004685 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004686 }
4687
4688 if (info->displayId != displayId) {
4689 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4690 handle->getName().c_str(), displayId, info->displayId);
4691 continue;
4692 }
4693
Robert Carredd13602020-04-13 17:24:34 -07004694 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4695 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004696 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004697 oldHandle->updateFrom(handle);
4698 newHandles.push_back(oldHandle);
4699 } else {
4700 newHandles.push_back(handle);
4701 }
4702 }
4703
4704 // Insert or replace
4705 mWindowHandlesByDisplay[displayId] = newHandles;
4706}
4707
Arthur Hung72d8dc32020-03-28 00:48:39 +00004708void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004709 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004710 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004711 { // acquire lock
4712 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004713 for (const auto& [displayId, handles] : handlesPerDisplay) {
4714 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004715 }
4716 }
4717 // Wake up poll loop since it may need to make new input dispatching choices.
4718 mLooper->wake();
4719}
4720
Arthur Hungb92218b2018-08-14 12:00:21 +08004721/**
4722 * Called from InputManagerService, update window handle list by displayId that can receive input.
4723 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4724 * If set an empty list, remove all handles from the specific display.
4725 * For focused handle, check if need to change and send a cancel event to previous one.
4726 * For removed handle, check if need to send a cancel event if already in touch.
4727 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004728void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004729 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004730 if (DEBUG_FOCUS) {
4731 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004732 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004733 windowList += iwh->getName() + " ";
4734 }
4735 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004737
Prabir Pradhand65552b2021-10-07 11:23:50 -07004738 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004739 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004740 const WindowInfo& info = *window->getInfo();
4741
4742 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004743 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004744 if (noInputWindow && window->getToken() != nullptr) {
4745 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4746 window->getName().c_str());
4747 window->releaseChannel();
4748 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004749
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004750 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004751 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4752 !info.inputConfig.test(
4753 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004754 "%s has feature SPY, but is not a trusted overlay.",
4755 window->getName().c_str());
4756
Prabir Pradhand65552b2021-10-07 11:23:50 -07004757 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004758 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4759 !info.inputConfig.test(
4760 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004761 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4762 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004763 }
4764
Arthur Hung72d8dc32020-03-28 00:48:39 +00004765 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004766 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004767
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004768 // Save the old windows' orientation by ID before it gets updated.
4769 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004770 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004771 oldWindowOrientations.emplace(handle->getId(),
4772 handle->getInfo()->transform.getOrientation());
4773 }
4774
chaviw98318de2021-05-19 16:45:23 -05004775 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004776
chaviw98318de2021-05-19 16:45:23 -05004777 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004778 if (mLastHoverWindowHandle &&
4779 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4780 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004781 mLastHoverWindowHandle = nullptr;
4782 }
4783
Vishnu Nairc519ff72021-01-21 08:23:08 -08004784 std::optional<FocusResolver::FocusChanges> changes =
4785 mFocusResolver.setInputWindows(displayId, windowHandles);
4786 if (changes) {
4787 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004788 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004789
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004790 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4791 mTouchStatesByDisplay.find(displayId);
4792 if (stateIt != mTouchStatesByDisplay.end()) {
4793 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004794 for (size_t i = 0; i < state.windows.size();) {
4795 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004796 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004797 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004798 ALOGD("Touched window was removed: %s in display %" PRId32,
4799 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004800 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004801 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004802 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4803 if (touchedInputChannel != nullptr) {
4804 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4805 "touched window was removed");
4806 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004807 // Since we are about to drop the touch, cancel the events for the wallpaper as
4808 // well.
4809 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004810 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4811 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004812 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4813 if (wallpaper != nullptr) {
4814 sp<Connection> wallpaperConnection =
4815 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004816 if (wallpaperConnection != nullptr) {
4817 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4818 options);
4819 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004820 }
4821 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004822 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004823 state.windows.erase(state.windows.begin() + i);
4824 } else {
4825 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004826 }
4827 }
arthurhungb89ccb02020-12-30 16:19:01 +08004828
arthurhung6d4bed92021-03-17 11:59:33 +08004829 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004830 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004831 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004832 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004833 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004834 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4835 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004836 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004837 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004838 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004839
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004840 // Determine if the orientation of any of the input windows have changed, and cancel all
4841 // pointer events if necessary.
4842 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4843 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4844 if (newWindowHandle != nullptr &&
4845 newWindowHandle->getInfo()->transform.getOrientation() !=
4846 oldWindowOrientations[oldWindowHandle->getId()]) {
4847 std::shared_ptr<InputChannel> inputChannel =
4848 getInputChannelLocked(newWindowHandle->getToken());
4849 if (inputChannel != nullptr) {
4850 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4851 "touched window's orientation changed");
4852 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004853 }
4854 }
4855 }
4856
Arthur Hung72d8dc32020-03-28 00:48:39 +00004857 // Release information for windows that are no longer present.
4858 // This ensures that unused input channels are released promptly.
4859 // Otherwise, they might stick around until the window handle is destroyed
4860 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004861 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004862 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004863 if (DEBUG_FOCUS) {
4864 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004865 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004866 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004867 }
chaviw291d88a2019-02-14 10:33:58 -08004868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004869}
4870
4871void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004872 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004873 if (DEBUG_FOCUS) {
4874 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4875 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4876 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004877 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004878 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004879 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880 } // release lock
4881
4882 // Wake up poll loop since it may need to make new input dispatching choices.
4883 mLooper->wake();
4884}
4885
Vishnu Nair599f1412021-06-21 10:39:58 -07004886void InputDispatcher::setFocusedApplicationLocked(
4887 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4888 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4889 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4890
4891 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4892 return; // This application is already focused. No need to wake up or change anything.
4893 }
4894
4895 // Set the new application handle.
4896 if (inputApplicationHandle != nullptr) {
4897 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4898 } else {
4899 mFocusedApplicationHandlesByDisplay.erase(displayId);
4900 }
4901
4902 // No matter what the old focused application was, stop waiting on it because it is
4903 // no longer focused.
4904 resetNoFocusedWindowTimeoutLocked();
4905}
4906
Tiger Huang721e26f2018-07-24 22:26:19 +08004907/**
4908 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4909 * the display not specified.
4910 *
4911 * We track any unreleased events for each window. If a window loses the ability to receive the
4912 * released event, we will send a cancel event to it. So when the focused display is changed, we
4913 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4914 * display. The display-specified events won't be affected.
4915 */
4916void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004917 if (DEBUG_FOCUS) {
4918 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4919 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004920 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004921 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004922
4923 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004924 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004925 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004926 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004927 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004928 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004929 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004930 CancelationOptions
4931 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4932 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004933 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004934 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4935 }
4936 }
4937 mFocusedDisplayId = displayId;
4938
Chris Ye3c2d6f52020-08-09 10:39:48 -07004939 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004940 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004941 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004942
Vishnu Nairad321cd2020-08-20 16:40:21 -07004943 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004944 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004945 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004946 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004947 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004948 }
4949 }
4950 }
4951
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004952 if (DEBUG_FOCUS) {
4953 logDispatchStateLocked();
4954 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004955 } // release lock
4956
4957 // Wake up poll loop since it may need to make new input dispatching choices.
4958 mLooper->wake();
4959}
4960
Michael Wrightd02c5b62014-02-10 15:10:22 -08004961void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004962 if (DEBUG_FOCUS) {
4963 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4964 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004965
4966 bool changed;
4967 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004968 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004969
4970 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4971 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004972 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004973 }
4974
4975 if (mDispatchEnabled && !enabled) {
4976 resetAndDropEverythingLocked("dispatcher is being disabled");
4977 }
4978
4979 mDispatchEnabled = enabled;
4980 mDispatchFrozen = frozen;
4981 changed = true;
4982 } else {
4983 changed = false;
4984 }
4985
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004986 if (DEBUG_FOCUS) {
4987 logDispatchStateLocked();
4988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004989 } // release lock
4990
4991 if (changed) {
4992 // Wake up poll loop since it may need to make new input dispatching choices.
4993 mLooper->wake();
4994 }
4995}
4996
4997void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004998 if (DEBUG_FOCUS) {
4999 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005001
5002 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005003 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005004
5005 if (mInputFilterEnabled == enabled) {
5006 return;
5007 }
5008
5009 mInputFilterEnabled = enabled;
5010 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5011 } // release lock
5012
5013 // Wake up poll loop since there might be work to do to drop everything.
5014 mLooper->wake();
5015}
5016
Antonio Kanteka042c022022-07-06 16:51:07 -07005017bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5018 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005019 bool needWake = false;
5020 {
5021 std::scoped_lock lock(mLock);
5022 if (mInTouchMode == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005023 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005024 }
5025 if (DEBUG_TOUCH_MODE) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005026 ALOGD("Request to change touch mode from %s to %s (calling pid=%d, uid=%d, "
Antonio Kanteka042c022022-07-06 16:51:07 -07005027 "hasPermission=%s, target displayId=%d, perDisplayTouchModeEnabled=%s)",
5028 toString(mInTouchMode), toString(inTouchMode), pid, uid, toString(hasPermission),
5029 displayId, toString(kPerDisplayTouchModeEnabled));
Antonio Kantekea47acb2021-12-23 12:41:25 -08005030 }
5031 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005032 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5033 !recentWindowsAreOwnedByLocked(pid, uid)) {
5034 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5035 "window nor none of the previously interacted window",
5036 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005037 return false;
5038 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005039 }
5040
Antonio Kanteka042c022022-07-06 16:51:07 -07005041 // TODO(b/198499018): Store touch mode per display (kPerDisplayTouchModeEnabled)
Antonio Kantekf16f2832021-09-28 04:39:20 +00005042 mInTouchMode = inTouchMode;
5043
Antonio Kantekf16f2832021-09-28 04:39:20 +00005044 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
5045 needWake = enqueueInboundEventLocked(std::move(entry));
5046 } // release lock
5047
5048 if (needWake) {
5049 mLooper->wake();
5050 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005051 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005052}
5053
Antonio Kantek48710e42022-03-24 14:19:30 -07005054bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5055 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5056 if (focusedToken == nullptr) {
5057 return false;
5058 }
5059 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5060 return isWindowOwnedBy(windowHandle, pid, uid);
5061}
5062
5063bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5064 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5065 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5066 const sp<WindowInfoHandle> windowHandle =
5067 getWindowHandleLocked(connectionToken);
5068 return isWindowOwnedBy(windowHandle, pid, uid);
5069 }) != mInteractionConnectionTokens.end();
5070}
5071
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005072void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5073 if (opacity < 0 || opacity > 1) {
5074 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5075 return;
5076 }
5077
5078 std::scoped_lock lock(mLock);
5079 mMaximumObscuringOpacityForTouch = opacity;
5080}
5081
Arthur Hungabbb9d82021-09-01 14:52:30 +00005082std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
5083 const sp<IBinder>& token) {
5084 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5085 for (TouchedWindow& w : state.windows) {
5086 if (w.windowHandle->getToken() == token) {
5087 return std::make_pair(&state, &w);
5088 }
5089 }
5090 }
5091 return std::make_pair(nullptr, nullptr);
5092}
5093
arthurhungb89ccb02020-12-30 16:19:01 +08005094bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5095 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005096 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005097 if (DEBUG_FOCUS) {
5098 ALOGD("Trivial transfer to same window.");
5099 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005100 return true;
5101 }
5102
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005104 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005105
Arthur Hungabbb9d82021-09-01 14:52:30 +00005106 // Find the target touch state and touched window by fromToken.
5107 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5108 if (state == nullptr || touchedWindow == nullptr) {
5109 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005110 return false;
5111 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005112
5113 const int32_t displayId = state->displayId;
5114 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5115 if (toWindowHandle == nullptr) {
5116 ALOGW("Cannot transfer focus because to window not found.");
5117 return false;
5118 }
5119
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005120 if (DEBUG_FOCUS) {
5121 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005122 touchedWindow->windowHandle->getName().c_str(),
5123 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124 }
5125
Arthur Hungabbb9d82021-09-01 14:52:30 +00005126 // Erase old window.
5127 int32_t oldTargetFlags = touchedWindow->targetFlags;
5128 BitSet32 pointerIds = touchedWindow->pointerIds;
5129 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005130
Arthur Hungabbb9d82021-09-01 14:52:30 +00005131 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005132 nsecs_t downTimeInTarget = now();
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005133 int32_t newTargetFlags =
5134 oldTargetFlags & (InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
5135 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
5136 newTargetFlags |= InputTarget::FLAG_FOREGROUND;
5137 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005138 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005139
Arthur Hungabbb9d82021-09-01 14:52:30 +00005140 // Store the dragging window.
5141 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005142 if (pointerIds.count() != 1) {
5143 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5144 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005145 return false;
5146 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005147 // Track the pointer id for drag window and generate the drag state.
5148 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005149 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005150 }
5151
Arthur Hungabbb9d82021-09-01 14:52:30 +00005152 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005153 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5154 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005155 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005156 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005157 CancelationOptions
5158 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5159 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005160 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005161 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005162 }
5163
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005164 if (DEBUG_FOCUS) {
5165 logDispatchStateLocked();
5166 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005167 } // release lock
5168
5169 // Wake up poll loop since it may need to make new input dispatching choices.
5170 mLooper->wake();
5171 return true;
5172}
5173
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005174/**
5175 * Get the touched foreground window on the given display.
5176 * Return null if there are no windows touched on that display, or if more than one foreground
5177 * window is being touched.
5178 */
5179sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5180 auto stateIt = mTouchStatesByDisplay.find(displayId);
5181 if (stateIt == mTouchStatesByDisplay.end()) {
5182 ALOGI("No touch state on display %" PRId32, displayId);
5183 return nullptr;
5184 }
5185
5186 const TouchState& state = stateIt->second;
5187 sp<WindowInfoHandle> touchedForegroundWindow;
5188 // If multiple foreground windows are touched, return nullptr
5189 for (const TouchedWindow& window : state.windows) {
5190 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5191 if (touchedForegroundWindow != nullptr) {
5192 ALOGI("Two or more foreground windows: %s and %s",
5193 touchedForegroundWindow->getName().c_str(),
5194 window.windowHandle->getName().c_str());
5195 return nullptr;
5196 }
5197 touchedForegroundWindow = window.windowHandle;
5198 }
5199 }
5200 return touchedForegroundWindow;
5201}
5202
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005203// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005204bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005205 sp<IBinder> fromToken;
5206 { // acquire lock
5207 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005208 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005209 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005210 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5211 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005212 return false;
5213 }
5214
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005215 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5216 if (from == nullptr) {
5217 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5218 return false;
5219 }
5220
5221 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005222 } // release lock
5223
5224 return transferTouchFocus(fromToken, destChannelToken);
5225}
5226
Michael Wrightd02c5b62014-02-10 15:10:22 -08005227void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005228 if (DEBUG_FOCUS) {
5229 ALOGD("Resetting and dropping all events (%s).", reason);
5230 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231
5232 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5233 synthesizeCancelationEventsForAllConnectionsLocked(options);
5234
5235 resetKeyRepeatLocked();
5236 releasePendingEventLocked();
5237 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005238 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005239
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005240 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005241 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005242 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005243 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005244}
5245
5246void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005247 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005248 dumpDispatchStateLocked(dump);
5249
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005250 std::istringstream stream(dump);
5251 std::string line;
5252
5253 while (std::getline(stream, line, '\n')) {
5254 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005255 }
5256}
5257
Prabir Pradhan99987712020-11-10 18:43:05 -08005258std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5259 std::string dump;
5260
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005261 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5262 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005263
5264 std::string windowName = "None";
5265 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005266 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005267 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5268 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5269 : "token has capture without window";
5270 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005271 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005272
5273 return dump;
5274}
5275
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005276void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005277 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5278 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5279 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005280 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005281
Tiger Huang721e26f2018-07-24 22:26:19 +08005282 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5283 dump += StringPrintf(INDENT "FocusedApplications:\n");
5284 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5285 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005286 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005287 const std::chrono::duration timeout =
5288 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005289 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005290 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005291 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005292 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005293 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005294 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005295 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005296
Vishnu Nairc519ff72021-01-21 08:23:08 -08005297 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005298 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005299
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005300 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005301 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005302 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5303 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005304 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005305 state.displayId, toString(state.down), toString(state.split),
5306 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005307 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005308 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005309 for (size_t i = 0; i < state.windows.size(); i++) {
5310 const TouchedWindow& touchedWindow = state.windows[i];
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005311 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, "
5312 "targetFlags=0x%x, firstDownTimeInTarget=%" PRId64
5313 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005314 i, touchedWindow.windowHandle->getName().c_str(),
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005315 touchedWindow.pointerIds.value, touchedWindow.targetFlags,
5316 ns2ms(touchedWindow.firstDownTimeInTarget.value_or(0)));
Jeff Brownf086ddb2014-02-11 14:28:48 -08005317 }
5318 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005319 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005321 }
5322 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005323 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005324 }
5325
arthurhung6d4bed92021-03-17 11:59:33 +08005326 if (mDragState) {
5327 dump += StringPrintf(INDENT "DragState:\n");
5328 mDragState->dump(dump, INDENT2);
5329 }
5330
Arthur Hungb92218b2018-08-14 12:00:21 +08005331 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005332 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5333 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5334 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5335 const auto& displayInfo = it->second;
5336 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5337 displayInfo.logicalHeight);
5338 displayInfo.transform.dump(dump, "transform", INDENT4);
5339 } else {
5340 dump += INDENT2 "No DisplayInfo found!\n";
5341 }
5342
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005343 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005344 dump += INDENT2 "Windows:\n";
5345 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005346 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5347 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005348
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005349 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005350 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005351 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005352 "applicationInfo.name=%s, "
5353 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005354 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005355 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005356 windowInfo->displayId,
5357 windowInfo->inputConfig.string().c_str(),
5358 windowInfo->alpha, windowInfo->frameLeft,
5359 windowInfo->frameTop, windowInfo->frameRight,
5360 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005361 windowInfo->applicationInfo.name.c_str(),
5362 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005363 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005364 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005365 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005366 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005367 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005368 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005369 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005370 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005371 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005372 }
5373 } else {
5374 dump += INDENT2 "Windows: <none>\n";
5375 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005376 }
5377 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005378 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005379 }
5380
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005381 if (!mGlobalMonitorsByDisplay.empty()) {
5382 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5383 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005384 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005385 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005386 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005387 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005388 }
5389
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005390 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005391
5392 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005393 if (!mRecentQueue.empty()) {
5394 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005395 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005396 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005397 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005398 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005399 }
5400 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005401 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005402 }
5403
5404 // Dump event currently being dispatched.
5405 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005406 dump += INDENT "PendingEvent:\n";
5407 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005408 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005409 dump += StringPrintf(", age=%" PRId64 "ms\n",
5410 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005411 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005412 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005413 }
5414
5415 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005416 if (!mInboundQueue.empty()) {
5417 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005418 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005419 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005420 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005421 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005422 }
5423 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005424 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005425 }
5426
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005427 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005428 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005429 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5430 const KeyReplacement& replacement = pair.first;
5431 int32_t newKeyCode = pair.second;
5432 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005433 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005434 }
5435 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005436 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005437 }
5438
Prabir Pradhancef936d2021-07-21 16:17:52 +00005439 if (!mCommandQueue.empty()) {
5440 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5441 } else {
5442 dump += INDENT "CommandQueue: <empty>\n";
5443 }
5444
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005445 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005446 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005447 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005448 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005449 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005450 connection->inputChannel->getFd().get(),
5451 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005452 connection->getWindowName().c_str(),
5453 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005454 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005455
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005456 if (!connection->outboundQueue.empty()) {
5457 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5458 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005459 dump += dumpQueue(connection->outboundQueue, currentTime);
5460
Michael Wrightd02c5b62014-02-10 15:10:22 -08005461 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005462 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005463 }
5464
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005465 if (!connection->waitQueue.empty()) {
5466 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5467 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005468 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005469 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005470 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005471 }
5472 }
5473 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005474 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005475 }
5476
5477 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005478 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5479 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005480 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005481 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482 }
5483
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005484 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005485 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5486 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5487 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005488 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005489 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490}
5491
Michael Wright3dd60e22019-03-27 22:06:44 +00005492void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5493 const size_t numMonitors = monitors.size();
5494 for (size_t i = 0; i < numMonitors; i++) {
5495 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005496 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005497 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5498 dump += "\n";
5499 }
5500}
5501
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005502class LooperEventCallback : public LooperCallback {
5503public:
5504 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5505 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5506
5507private:
5508 std::function<int(int events)> mCallback;
5509};
5510
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005511Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005512 if (DEBUG_CHANNEL_CREATION) {
5513 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5514 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005515
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005516 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005517 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005518 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005519
5520 if (result) {
5521 return base::Error(result) << "Failed to open input channel pair with name " << name;
5522 }
5523
Michael Wrightd02c5b62014-02-10 15:10:22 -08005524 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005525 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005526 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005527 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005528 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005529 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005530
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005531 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5532 ALOGE("Created a new connection, but the token %p is already known", token.get());
5533 }
5534 mConnectionsByToken.emplace(token, connection);
5535
5536 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5537 this, std::placeholders::_1, token);
5538
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005539 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5540 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005541 } // release lock
5542
5543 // Wake the looper because some connections have changed.
5544 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005545 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005546}
5547
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005548Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005549 const std::string& name,
5550 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005551 std::shared_ptr<InputChannel> serverChannel;
5552 std::unique_ptr<InputChannel> clientChannel;
5553 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5554 if (result) {
5555 return base::Error(result) << "Failed to open input channel pair with name " << name;
5556 }
5557
Michael Wright3dd60e22019-03-27 22:06:44 +00005558 { // acquire lock
5559 std::scoped_lock _l(mLock);
5560
5561 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005562 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5563 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005564 }
5565
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005566 sp<Connection> connection =
5567 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005568 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005569 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005570
5571 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5572 ALOGE("Created a new connection, but the token %p is already known", token.get());
5573 }
5574 mConnectionsByToken.emplace(token, connection);
5575 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5576 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005577
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005578 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005579
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005580 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5581 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005582 }
Garfield Tan15601662020-09-22 15:32:38 -07005583
Michael Wright3dd60e22019-03-27 22:06:44 +00005584 // Wake the looper because some connections have changed.
5585 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005586 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005587}
5588
Garfield Tan15601662020-09-22 15:32:38 -07005589status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005590 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005591 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005592
Garfield Tan15601662020-09-22 15:32:38 -07005593 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005594 if (status) {
5595 return status;
5596 }
5597 } // release lock
5598
5599 // Wake the poll loop because removing the connection may have changed the current
5600 // synchronization state.
5601 mLooper->wake();
5602 return OK;
5603}
5604
Garfield Tan15601662020-09-22 15:32:38 -07005605status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5606 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005607 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005608 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005609 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005610 return BAD_VALUE;
5611 }
5612
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005613 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005614
Michael Wrightd02c5b62014-02-10 15:10:22 -08005615 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005616 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005617 }
5618
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005619 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005620
5621 nsecs_t currentTime = now();
5622 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5623
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005624 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005625 return OK;
5626}
5627
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005628void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005629 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5630 auto& [displayId, monitors] = *it;
5631 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5632 return monitor.inputChannel->getConnectionToken() == connectionToken;
5633 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005634
Michael Wright3dd60e22019-03-27 22:06:44 +00005635 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005636 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005637 } else {
5638 ++it;
5639 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005640 }
5641}
5642
Michael Wright3dd60e22019-03-27 22:06:44 +00005643status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005644 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005645 return pilferPointersLocked(token);
5646}
Michael Wright3dd60e22019-03-27 22:06:44 +00005647
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005648status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005649 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5650 if (!requestingChannel) {
5651 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5652 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005653 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005654
5655 auto [statePtr, windowPtr] = findTouchStateAndWindowLocked(token);
5656 if (statePtr == nullptr || windowPtr == nullptr || !statePtr->down) {
5657 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5658 " Ignoring.");
5659 return BAD_VALUE;
5660 }
5661
5662 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005663 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005664 // Send cancel events to all the input channels we're stealing from.
5665 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5666 "input channel stole pointer stream");
5667 options.deviceId = state.deviceId;
5668 options.displayId = state.displayId;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005669 if (state.split) {
5670 // If split pointers then selectively cancel pointers otherwise cancel all pointers
5671 options.pointerIds = window.pointerIds;
5672 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005673 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005674 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005675 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005676 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005677 if (channel != nullptr && channel->getConnectionToken() != token) {
5678 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5679 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5680 canceledWindows += channel->getName();
5681 }
5682 }
5683 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5684 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5685 canceledWindows.c_str());
5686
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005687 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005688 // This only blocks relevant pointers to be sent to other windows
5689 window.isPilferingPointers = true;
5690
5691 if (state.split) {
5692 state.cancelPointersForWindowsExcept(window.pointerIds, token);
5693 } else {
5694 state.filterWindowsExcept(token);
5695 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005696 return OK;
5697}
5698
Prabir Pradhan99987712020-11-10 18:43:05 -08005699void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5700 { // acquire lock
5701 std::scoped_lock _l(mLock);
5702 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005703 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005704 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5705 windowHandle != nullptr ? windowHandle->getName().c_str()
5706 : "token without window");
5707 }
5708
Vishnu Nairc519ff72021-01-21 08:23:08 -08005709 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005710 if (focusedToken != windowToken) {
5711 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5712 enabled ? "enable" : "disable");
5713 return;
5714 }
5715
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005716 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005717 ALOGW("Ignoring request to %s Pointer Capture: "
5718 "window has %s requested pointer capture.",
5719 enabled ? "enable" : "disable", enabled ? "already" : "not");
5720 return;
5721 }
5722
Christine Franksb768bb42021-11-29 12:11:31 -08005723 if (enabled) {
5724 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5725 mIneligibleDisplaysForPointerCapture.end(),
5726 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5727 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5728 return;
5729 }
5730 }
5731
Prabir Pradhan99987712020-11-10 18:43:05 -08005732 setPointerCaptureLocked(enabled);
5733 } // release lock
5734
5735 // Wake the thread to process command entries.
5736 mLooper->wake();
5737}
5738
Christine Franksb768bb42021-11-29 12:11:31 -08005739void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5740 { // acquire lock
5741 std::scoped_lock _l(mLock);
5742 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5743 if (!isEligible) {
5744 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5745 }
5746 } // release lock
5747}
5748
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005749std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5750 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005751 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005752 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005753 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005754 }
5755 }
5756 }
5757 return std::nullopt;
5758}
5759
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005760sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005761 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005762 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005763 }
5764
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005765 for (const auto& [token, connection] : mConnectionsByToken) {
5766 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005767 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005768 }
5769 }
Robert Carr4e670e52018-08-15 13:26:12 -07005770
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005771 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005772}
5773
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005774std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5775 sp<Connection> connection = getConnectionLocked(connectionToken);
5776 if (connection == nullptr) {
5777 return "<nullptr>";
5778 }
5779 return connection->getInputChannelName();
5780}
5781
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005782void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005783 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005784 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005785}
5786
Prabir Pradhancef936d2021-07-21 16:17:52 +00005787void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5788 const sp<Connection>& connection, uint32_t seq,
5789 bool handled, nsecs_t consumeTime) {
5790 // Handle post-event policy actions.
5791 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5792 if (dispatchEntryIt == connection->waitQueue.end()) {
5793 return;
5794 }
5795 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5796 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5797 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5798 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5799 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5800 }
5801 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5802 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5803 connection->inputChannel->getConnectionToken(),
5804 dispatchEntry->deliveryTime, consumeTime, finishTime);
5805 }
5806
5807 bool restartEvent;
5808 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5809 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5810 restartEvent =
5811 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5812 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5813 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5814 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5815 handled);
5816 } else {
5817 restartEvent = false;
5818 }
5819
5820 // Dequeue the event and start the next cycle.
5821 // Because the lock might have been released, it is possible that the
5822 // contents of the wait queue to have been drained, so we need to double-check
5823 // a few things.
5824 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5825 if (dispatchEntryIt != connection->waitQueue.end()) {
5826 dispatchEntry = *dispatchEntryIt;
5827 connection->waitQueue.erase(dispatchEntryIt);
5828 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5829 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5830 if (!connection->responsive) {
5831 connection->responsive = isConnectionResponsive(*connection);
5832 if (connection->responsive) {
5833 // The connection was unresponsive, and now it's responsive.
5834 processConnectionResponsiveLocked(*connection);
5835 }
5836 }
5837 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005838 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005839 connection->outboundQueue.push_front(dispatchEntry);
5840 traceOutboundQueueLength(*connection);
5841 } else {
5842 releaseDispatchEntry(dispatchEntry);
5843 }
5844 }
5845
5846 // Start the next dispatch cycle for this connection.
5847 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005848}
5849
Prabir Pradhancef936d2021-07-21 16:17:52 +00005850void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5851 const sp<IBinder>& newToken) {
5852 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5853 scoped_unlock unlock(mLock);
5854 mPolicy->notifyFocusChanged(oldToken, newToken);
5855 };
5856 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005857}
5858
Prabir Pradhancef936d2021-07-21 16:17:52 +00005859void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5860 auto command = [this, token, x, y]() REQUIRES(mLock) {
5861 scoped_unlock unlock(mLock);
5862 mPolicy->notifyDropWindow(token, x, y);
5863 };
5864 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005865}
5866
Vishnu Nair2f5bc8b2022-08-09 00:03:11 +00005867bool InputDispatcher::onAnrLocked(const android::gui::FocusRequest& pendingFocusRequest) {
5868 if (pendingFocusRequest.token == nullptr) {
5869 return false;
5870 }
5871
5872 const std::string reason = android::base::StringPrintf("%s is not focusable.",
5873 pendingFocusRequest.windowName.c_str());
5874 updateLastAnrStateLocked(pendingFocusRequest.windowName, reason);
5875 sp<Connection> connection = getConnectionLocked(pendingFocusRequest.token);
5876 if (connection != nullptr) {
5877 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5878 // Stop waking up for events on this connection, it is already unresponsive
5879 cancelEventsForAnrLocked(connection);
5880 } else {
5881 sendWindowUnresponsiveCommandLocked(pendingFocusRequest.token, std::nullopt, reason);
5882 }
5883 return true;
5884}
5885
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005886void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5887 if (connection == nullptr) {
5888 LOG_ALWAYS_FATAL("Caller must check for nullness");
5889 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005890 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5891 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005892 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005893 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005894 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005895 return;
5896 }
5897 /**
5898 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5899 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5900 * has changed. This could cause newer entries to time out before the already dispatched
5901 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5902 * processes the events linearly. So providing information about the oldest entry seems to be
5903 * most useful.
5904 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005905 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005906 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5907 std::string reason =
5908 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005909 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005910 ns2ms(currentWait),
5911 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005912 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005913 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005914
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005915 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5916
5917 // Stop waking up for events on this connection, it is already unresponsive
5918 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005919}
5920
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005921void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5922 std::string reason =
5923 StringPrintf("%s does not have a focused window", application->getName().c_str());
5924 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005925
Prabir Pradhancef936d2021-07-21 16:17:52 +00005926 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5927 scoped_unlock unlock(mLock);
5928 mPolicy->notifyNoFocusedWindowAnr(application);
5929 };
5930 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005931}
5932
chaviw98318de2021-05-19 16:45:23 -05005933void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005934 const std::string& reason) {
5935 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5936 updateLastAnrStateLocked(windowLabel, reason);
5937}
5938
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005939void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5940 const std::string& reason) {
5941 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005942 updateLastAnrStateLocked(windowLabel, reason);
5943}
5944
5945void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5946 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005947 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005948 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005949 struct tm tm;
5950 localtime_r(&t, &tm);
5951 char timestr[64];
5952 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005953 mLastAnrState.clear();
5954 mLastAnrState += INDENT "ANR:\n";
5955 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005956 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5957 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005958 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005959}
5960
Prabir Pradhancef936d2021-07-21 16:17:52 +00005961void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5962 KeyEntry& entry) {
5963 const KeyEvent event = createKeyEvent(entry);
5964 nsecs_t delay = 0;
5965 { // release lock
5966 scoped_unlock unlock(mLock);
5967 android::base::Timer t;
5968 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5969 entry.policyFlags);
5970 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5971 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5972 std::to_string(t.duration().count()).c_str());
5973 }
5974 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005975
5976 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005977 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005978 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005979 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005980 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005981 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5982 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005983 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005984}
5985
Prabir Pradhancef936d2021-07-21 16:17:52 +00005986void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005987 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005988 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005989 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005990 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005991 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005992 };
5993 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005994}
5995
Prabir Pradhanedd96402022-02-15 01:46:16 -08005996void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5997 std::optional<int32_t> pid) {
5998 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005999 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006000 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006001 };
6002 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006003}
6004
6005/**
6006 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6007 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6008 * command entry to the command queue.
6009 */
6010void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6011 std::string reason) {
6012 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006013 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006014 if (connection.monitor) {
6015 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6016 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006017 pid = findMonitorPidByTokenLocked(connectionToken);
6018 } else {
6019 // The connection is a window
6020 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6021 reason.c_str());
6022 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6023 if (handle != nullptr) {
6024 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006025 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006026 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006027 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006028}
6029
6030/**
6031 * Tell the policy that a connection has become responsive so that it can stop ANR.
6032 */
6033void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6034 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006035 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006036 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006037 pid = findMonitorPidByTokenLocked(connectionToken);
6038 } else {
6039 // The connection is a window
6040 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6041 if (handle != nullptr) {
6042 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006043 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006044 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006045 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006046}
6047
Prabir Pradhancef936d2021-07-21 16:17:52 +00006048bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006049 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006050 KeyEntry& keyEntry, bool handled) {
6051 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006052 if (!handled) {
6053 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006054 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006055 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006056 return false;
6057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006058
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006059 // Get the fallback key state.
6060 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006061 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006062 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006063 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006064 connection->inputState.removeFallbackKey(originalKeyCode);
6065 }
6066
6067 if (handled || !dispatchEntry->hasForegroundTarget()) {
6068 // If the application handles the original key for which we previously
6069 // generated a fallback or if the window is not a foreground window,
6070 // then cancel the associated fallback key, if any.
6071 if (fallbackKeyCode != -1) {
6072 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006073 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6074 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6075 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6076 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6077 keyEntry.policyFlags);
6078 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006079 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006080 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006081
6082 mLock.unlock();
6083
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006084 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006085 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006086
6087 mLock.lock();
6088
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006089 // Cancel the fallback key.
6090 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006091 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006092 "application handled the original non-fallback key "
6093 "or is no longer a foreground target, "
6094 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006095 options.keyCode = fallbackKeyCode;
6096 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006097 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006098 connection->inputState.removeFallbackKey(originalKeyCode);
6099 }
6100 } else {
6101 // If the application did not handle a non-fallback key, first check
6102 // that we are in a good state to perform unhandled key event processing
6103 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006104 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006105 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006106 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6107 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6108 "since this is not an initial down. "
6109 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6110 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6111 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006112 return false;
6113 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006114
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006115 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006116 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6117 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6118 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6119 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6120 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006121 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006122
6123 mLock.unlock();
6124
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006125 bool fallback =
6126 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006127 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006128
6129 mLock.lock();
6130
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006131 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006132 connection->inputState.removeFallbackKey(originalKeyCode);
6133 return false;
6134 }
6135
6136 // Latch the fallback keycode for this key on an initial down.
6137 // The fallback keycode cannot change at any other point in the lifecycle.
6138 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006139 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006140 fallbackKeyCode = event.getKeyCode();
6141 } else {
6142 fallbackKeyCode = AKEYCODE_UNKNOWN;
6143 }
6144 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6145 }
6146
6147 ALOG_ASSERT(fallbackKeyCode != -1);
6148
6149 // Cancel the fallback key if the policy decides not to send it anymore.
6150 // We will continue to dispatch the key to the policy but we will no
6151 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006152 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6153 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006154 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6155 if (fallback) {
6156 ALOGD("Unhandled key event: Policy requested to send key %d"
6157 "as a fallback for %d, but on the DOWN it had requested "
6158 "to send %d instead. Fallback canceled.",
6159 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6160 } else {
6161 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6162 "but on the DOWN it had requested to send %d. "
6163 "Fallback canceled.",
6164 originalKeyCode, fallbackKeyCode);
6165 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006166 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006167
6168 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6169 "canceling fallback, policy no longer desires it");
6170 options.keyCode = fallbackKeyCode;
6171 synthesizeCancelationEventsForConnectionLocked(connection, options);
6172
6173 fallback = false;
6174 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006175 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006176 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006177 }
6178 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006179
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006180 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6181 {
6182 std::string msg;
6183 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6184 connection->inputState.getFallbackKeys();
6185 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6186 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6187 }
6188 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6189 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006190 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006191 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006192
6193 if (fallback) {
6194 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006195 keyEntry.eventTime = event.getEventTime();
6196 keyEntry.deviceId = event.getDeviceId();
6197 keyEntry.source = event.getSource();
6198 keyEntry.displayId = event.getDisplayId();
6199 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6200 keyEntry.keyCode = fallbackKeyCode;
6201 keyEntry.scanCode = event.getScanCode();
6202 keyEntry.metaState = event.getMetaState();
6203 keyEntry.repeatCount = event.getRepeatCount();
6204 keyEntry.downTime = event.getDownTime();
6205 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006206
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006207 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6208 ALOGD("Unhandled key event: Dispatching fallback key. "
6209 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6210 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6211 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006212 return true; // restart the event
6213 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006214 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6215 ALOGD("Unhandled key event: No fallback key.");
6216 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006217
6218 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006219 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006220 }
6221 }
6222 return false;
6223}
6224
Prabir Pradhancef936d2021-07-21 16:17:52 +00006225bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006226 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006227 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006228 return false;
6229}
6230
Michael Wrightd02c5b62014-02-10 15:10:22 -08006231void InputDispatcher::traceInboundQueueLengthLocked() {
6232 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006233 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006234 }
6235}
6236
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006237void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006238 if (ATRACE_ENABLED()) {
6239 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006240 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6241 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006242 }
6243}
6244
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006245void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006246 if (ATRACE_ENABLED()) {
6247 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006248 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6249 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006250 }
6251}
6252
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006253void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006254 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006255
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006256 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006257 dumpDispatchStateLocked(dump);
6258
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006259 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006260 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006261 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006262 }
6263}
6264
6265void InputDispatcher::monitor() {
6266 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006267 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006268 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006269 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006270}
6271
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006272/**
6273 * Wake up the dispatcher and wait until it processes all events and commands.
6274 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6275 * this method can be safely called from any thread, as long as you've ensured that
6276 * the work you are interested in completing has already been queued.
6277 */
6278bool InputDispatcher::waitForIdle() {
6279 /**
6280 * Timeout should represent the longest possible time that a device might spend processing
6281 * events and commands.
6282 */
6283 constexpr std::chrono::duration TIMEOUT = 100ms;
6284 std::unique_lock lock(mLock);
6285 mLooper->wake();
6286 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6287 return result == std::cv_status::no_timeout;
6288}
6289
Vishnu Naire798b472020-07-23 13:52:21 -07006290/**
6291 * Sets focus to the window identified by the token. This must be called
6292 * after updating any input window handles.
6293 *
6294 * Params:
6295 * request.token - input channel token used to identify the window that should gain focus.
6296 * request.focusedToken - the token that the caller expects currently to be focused. If the
6297 * specified token does not match the currently focused window, this request will be dropped.
6298 * If the specified focused token matches the currently focused window, the call will succeed.
6299 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6300 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6301 * when requesting the focus change. This determines which request gets
6302 * precedence if there is a focus change request from another source such as pointer down.
6303 */
Vishnu Nair958da932020-08-21 17:12:37 -07006304void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6305 { // acquire lock
6306 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006307 std::optional<FocusResolver::FocusChanges> changes =
6308 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6309 if (changes) {
6310 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006311 }
6312 } // release lock
6313 // Wake up poll loop since it may need to make new input dispatching choices.
6314 mLooper->wake();
6315}
6316
Vishnu Nairc519ff72021-01-21 08:23:08 -08006317void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6318 if (changes.oldFocus) {
6319 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006320 if (focusedInputChannel) {
6321 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6322 "focus left window");
6323 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006324 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006325 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006326 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006327 if (changes.newFocus) {
6328 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006329 }
6330
Prabir Pradhan99987712020-11-10 18:43:05 -08006331 // If a window has pointer capture, then it must have focus. We need to ensure that this
6332 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6333 // If the window loses focus before it loses pointer capture, then the window can be in a state
6334 // where it has pointer capture but not focus, violating the contract. Therefore we must
6335 // dispatch the pointer capture event before the focus event. Since focus events are added to
6336 // the front of the queue (above), we add the pointer capture event to the front of the queue
6337 // after the focus events are added. This ensures the pointer capture event ends up at the
6338 // front.
6339 disablePointerCaptureForcedLocked();
6340
Vishnu Nairc519ff72021-01-21 08:23:08 -08006341 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006342 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006343 }
6344}
Vishnu Nair958da932020-08-21 17:12:37 -07006345
Prabir Pradhan99987712020-11-10 18:43:05 -08006346void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006347 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006348 return;
6349 }
6350
6351 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6352
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006353 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006354 setPointerCaptureLocked(false);
6355 }
6356
6357 if (!mWindowTokenWithPointerCapture) {
6358 // No need to send capture changes because no window has capture.
6359 return;
6360 }
6361
6362 if (mPendingEvent != nullptr) {
6363 // Move the pending event to the front of the queue. This will give the chance
6364 // for the pending event to be dropped if it is a captured event.
6365 mInboundQueue.push_front(mPendingEvent);
6366 mPendingEvent = nullptr;
6367 }
6368
6369 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006370 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006371 mInboundQueue.push_front(std::move(entry));
6372}
6373
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006374void InputDispatcher::setPointerCaptureLocked(bool enable) {
6375 mCurrentPointerCaptureRequest.enable = enable;
6376 mCurrentPointerCaptureRequest.seq++;
6377 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006378 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006379 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006380 };
6381 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006382}
6383
Vishnu Nair599f1412021-06-21 10:39:58 -07006384void InputDispatcher::displayRemoved(int32_t displayId) {
6385 { // acquire lock
6386 std::scoped_lock _l(mLock);
6387 // Set an empty list to remove all handles from the specific display.
6388 setInputWindowsLocked(/* window handles */ {}, displayId);
6389 setFocusedApplicationLocked(displayId, nullptr);
6390 // Call focus resolver to clean up stale requests. This must be called after input windows
6391 // have been removed for the removed display.
6392 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006393 // Reset pointer capture eligibility, regardless of previous state.
6394 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006395 } // release lock
6396
6397 // Wake up poll loop since it may need to make new input dispatching choices.
6398 mLooper->wake();
6399}
6400
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006401void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6402 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006403 // The listener sends the windows as a flattened array. Separate the windows by display for
6404 // more convenient parsing.
6405 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006406 for (const auto& info : windowInfos) {
6407 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006408 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006409 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006410
6411 { // acquire lock
6412 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006413
6414 // Ensure that we have an entry created for all existing displays so that if a displayId has
6415 // no windows, we can tell that the windows were removed from the display.
6416 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6417 handlesPerDisplay[displayId];
6418 }
6419
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006420 mDisplayInfos.clear();
6421 for (const auto& displayInfo : displayInfos) {
6422 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6423 }
6424
6425 for (const auto& [displayId, handles] : handlesPerDisplay) {
6426 setInputWindowsLocked(handles, displayId);
6427 }
6428 }
6429 // Wake up poll loop since it may need to make new input dispatching choices.
6430 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006431}
6432
Vishnu Nair062a8672021-09-03 16:07:44 -07006433bool InputDispatcher::shouldDropInput(
6434 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006435 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6436 (windowHandle->getInfo()->inputConfig.test(
6437 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006438 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006439 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6440 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006441 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006442 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006443 windowHandle->getInfo()->displayId);
6444 return true;
6445 }
6446 return false;
6447}
6448
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006449void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6450 const std::vector<gui::WindowInfo>& windowInfos,
6451 const std::vector<DisplayInfo>& displayInfos) {
6452 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6453}
6454
Arthur Hungdfd528e2021-12-08 13:23:04 +00006455void InputDispatcher::cancelCurrentTouch() {
6456 {
6457 std::scoped_lock _l(mLock);
6458 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6459 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6460 "cancel current touch");
6461 synthesizeCancelationEventsForAllConnectionsLocked(options);
6462
6463 mTouchStatesByDisplay.clear();
6464 mLastHoverWindowHandle.clear();
6465 }
6466 // Wake up poll loop since there might be work to do.
6467 mLooper->wake();
6468}
6469
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006470void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6471 std::scoped_lock _l(mLock);
6472 mMonitorDispatchingTimeout = timeout;
6473}
6474
Garfield Tane84e6f92019-08-29 17:28:41 -07006475} // namespace android::inputdispatcher