blob: 9265fd3c93fa865afb5f223e0a58cdefb1735a23 [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()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800558 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800559 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800560
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700561 mWindowInfoListener = new DispatcherWindowListener(*this);
562 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 }
662 onAnrLocked(mAwaitedFocusedApplication);
663}
664
665/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700666 * Check if any of the connections' wait queues have events that are too old.
667 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
668 * Return the time at which we should wake up next.
669 */
670nsecs_t InputDispatcher::processAnrsLocked() {
671 const nsecs_t currentTime = now();
672 nsecs_t nextAnrCheck = LONG_LONG_MAX;
673 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
674 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
675 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500676 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700677 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500678 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700679 return LONG_LONG_MIN;
680 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500681 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700682 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
683 }
684 }
685
686 // Check if any connection ANRs are due
687 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
688 if (currentTime < nextAnrCheck) { // most likely scenario
689 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
690 }
691
692 // If we reached here, we have an unresponsive connection.
693 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
694 if (connection == nullptr) {
695 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
696 return nextAnrCheck;
697 }
698 connection->responsive = false;
699 // Stop waking up for this unresponsive connection
700 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000701 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700702 return LONG_LONG_MIN;
703}
704
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800705std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
706 const sp<Connection>& connection) {
707 if (connection->monitor) {
708 return mMonitorDispatchingTimeout;
709 }
710 const sp<WindowInfoHandle> window =
711 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700712 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500713 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700714 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500715 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700716}
717
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
719 nsecs_t currentTime = now();
720
Jeff Browndc5992e2014-04-11 01:27:26 -0700721 // Reset the key repeat timer whenever normal dispatch is suspended while the
722 // device is in a non-interactive state. This is to ensure that we abort a key
723 // repeat if the device is just coming out of sleep.
724 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800725 resetKeyRepeatLocked();
726 }
727
728 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
729 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100730 if (DEBUG_FOCUS) {
731 ALOGD("Dispatch frozen. Waiting some more.");
732 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800733 return;
734 }
735
736 // Optimize latency of app switches.
737 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
738 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
739 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
740 if (mAppSwitchDueTime < *nextWakeupTime) {
741 *nextWakeupTime = mAppSwitchDueTime;
742 }
743
744 // Ready to start a new event.
745 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700746 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700747 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800748 if (isAppSwitchDue) {
749 // The inbound queue is empty so the app switch key we were waiting
750 // for will never arrive. Stop waiting for it.
751 resetPendingAppSwitchLocked(false);
752 isAppSwitchDue = false;
753 }
754
755 // Synthesize a key repeat if appropriate.
756 if (mKeyRepeatState.lastKeyEntry) {
757 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
758 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
759 } else {
760 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
761 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
762 }
763 }
764 }
765
766 // Nothing to do if there is no pending event.
767 if (!mPendingEvent) {
768 return;
769 }
770 } else {
771 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700772 mPendingEvent = mInboundQueue.front();
773 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774 traceInboundQueueLengthLocked();
775 }
776
777 // Poke user activity for this event.
778 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700779 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781 }
782
783 // Now we have an event to dispatch.
784 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700785 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700787 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700789 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700791 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792 }
793
794 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700795 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800796 }
797
798 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700799 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700800 const ConfigurationChangedEntry& typedEntry =
801 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700802 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700803 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700804 break;
805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700807 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700808 const DeviceResetEntry& typedEntry =
809 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700810 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700811 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700812 break;
813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100815 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700816 std::shared_ptr<FocusEntry> typedEntry =
817 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100818 dispatchFocusLocked(currentTime, typedEntry);
819 done = true;
820 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
821 break;
822 }
823
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700824 case EventEntry::Type::TOUCH_MODE_CHANGED: {
825 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
826 dispatchTouchModeChangeLocked(currentTime, typedEntry);
827 done = true;
828 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
829 break;
830 }
831
Prabir Pradhan99987712020-11-10 18:43:05 -0800832 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
833 const auto typedEntry =
834 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
835 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
836 done = true;
837 break;
838 }
839
arthurhungb89ccb02020-12-30 16:19:01 +0800840 case EventEntry::Type::DRAG: {
841 std::shared_ptr<DragEntry> typedEntry =
842 std::static_pointer_cast<DragEntry>(mPendingEvent);
843 dispatchDragLocked(currentTime, typedEntry);
844 done = true;
845 break;
846 }
847
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700848 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700849 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700850 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700851 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700852 resetPendingAppSwitchLocked(true);
853 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700854 } else if (dropReason == DropReason::NOT_DROPPED) {
855 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700856 }
857 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700858 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700859 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700860 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700861 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
862 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700863 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700864 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700865 break;
866 }
867
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700868 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700869 std::shared_ptr<MotionEntry> motionEntry =
870 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700871 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
872 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700874 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700875 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700876 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700877 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
878 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700879 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700880 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700881 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882 }
Chris Yef59a2f42020-10-16 12:55:26 -0700883
884 case EventEntry::Type::SENSOR: {
885 std::shared_ptr<SensorEntry> sensorEntry =
886 std::static_pointer_cast<SensorEntry>(mPendingEvent);
887 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
888 dropReason = DropReason::APP_SWITCH;
889 }
890 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
891 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
892 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
893 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
894 dropReason = DropReason::STALE;
895 }
896 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
897 done = true;
898 break;
899 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900 }
901
902 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700903 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700904 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 }
Michael Wright3a981722015-06-10 15:26:13 +0100906 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907
908 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700909 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800910 }
911}
912
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800913bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
914 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
915}
916
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700917/**
918 * Return true if the events preceding this incoming motion event should be dropped
919 * Return false otherwise (the default behaviour)
920 */
921bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700922 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700923 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700924
925 // Optimize case where the current application is unresponsive and the user
926 // decides to touch a window in a different application.
927 // If the application takes too long to catch up then we drop all events preceding
928 // the touch into the other window.
929 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700930 int32_t displayId = motionEntry.displayId;
931 int32_t x = static_cast<int32_t>(
932 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
933 int32_t y = static_cast<int32_t>(
934 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Prabir Pradhand65552b2021-10-07 11:23:50 -0700935
936 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -0500937 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700938 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700939 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700940 touchedWindowHandle->getApplicationToken() !=
941 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700942 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700943 ALOGI("Pruning input queue because user touched a different application while waiting "
944 "for %s",
945 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700946 return true;
947 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700948
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800949 // Alternatively, maybe there's a spy window that could handle this event.
950 const std::vector<sp<WindowInfoHandle>> touchedSpies =
951 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
952 for (const auto& windowHandle : touchedSpies) {
953 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000954 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800955 // This spy window could take more input. Drop all events preceding this
956 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700957 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800958 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700959 mAwaitedFocusedApplication->getName().c_str());
960 return true;
961 }
962 }
963 }
964
965 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
966 // yet been processed by some connections, the dispatcher will wait for these motion
967 // events to be processed before dispatching the key event. This is because these motion events
968 // may cause a new window to be launched, which the user might expect to receive focus.
969 // To prevent waiting forever for such events, just send the key to the currently focused window
970 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
971 ALOGD("Received a new pointer down event, stop waiting for events to process and "
972 "just send the pending key event to the focused window.");
973 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700974 }
975 return false;
976}
977
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700978bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700979 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700980 mInboundQueue.push_back(std::move(newEntry));
981 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982 traceInboundQueueLengthLocked();
983
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700984 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700985 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +0000986 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
987 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700988 // Optimize app switch latency.
989 // If the application takes too long to catch up then we drop all events preceding
990 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700991 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700992 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700993 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700994 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700995 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700996 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000997 if (DEBUG_APP_SWITCH) {
998 ALOGD("App switch is pending!");
999 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001000 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001001 mAppSwitchSawKeyDown = false;
1002 needWake = true;
1003 }
1004 }
1005 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001006
1007 // If a new up event comes in, and the pending event with same key code has been asked
1008 // to try again later because of the policy. We have to reset the intercept key wake up
1009 // time for it may have been handled in the policy and could be dropped.
1010 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1011 mPendingEvent->type == EventEntry::Type::KEY) {
1012 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1013 if (pendingKey.keyCode == keyEntry.keyCode &&
1014 pendingKey.interceptKeyResult ==
1015 KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1016 pendingKey.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1017 pendingKey.interceptKeyWakeupTime = 0;
1018 needWake = true;
1019 }
1020 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001021 break;
1022 }
1023
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001024 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001025 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1026 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001027 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1028 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001029 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001030 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001033 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001034 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1035 break;
1036 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001037 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001038 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001039 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001040 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001041 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1042 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001043 // nothing to do
1044 break;
1045 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046 }
1047
1048 return needWake;
1049}
1050
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001051void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001052 // Do not store sensor event in recent queue to avoid flooding the queue.
1053 if (entry->type != EventEntry::Type::SENSOR) {
1054 mRecentQueue.push_back(entry);
1055 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001056 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001057 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058 }
1059}
1060
chaviw98318de2021-05-19 16:45:23 -05001061sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1062 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001063 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001064 bool addOutsideTargets,
1065 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001066 if (addOutsideTargets && touchState == nullptr) {
1067 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001070 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001071 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001072 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001073 continue;
1074 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001076 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001077 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001078 return windowHandle;
1079 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001080
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001081 if (addOutsideTargets &&
1082 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001083 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1084 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085 }
1086 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001087 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088}
1089
Prabir Pradhand65552b2021-10-07 11:23:50 -07001090std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1091 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001092 // Traverse windows from front to back and gather the touched spy windows.
1093 std::vector<sp<WindowInfoHandle>> spyWindows;
1094 const auto& windowHandles = getWindowHandlesLocked(displayId);
1095 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1096 const WindowInfo& info = *windowHandle->getInfo();
1097
Prabir Pradhand65552b2021-10-07 11:23:50 -07001098 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001099 continue;
1100 }
1101 if (!info.isSpy()) {
1102 // The first touched non-spy window was found, so return the spy windows touched so far.
1103 return spyWindows;
1104 }
1105 spyWindows.push_back(windowHandle);
1106 }
1107 return spyWindows;
1108}
1109
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001110void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001111 const char* reason;
1112 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001113 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001114 if (DEBUG_INBOUND_EVENT_DETAILS) {
1115 ALOGD("Dropped event because policy consumed it.");
1116 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001117 reason = "inbound event was dropped because the policy consumed it";
1118 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001119 case DropReason::DISABLED:
1120 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001121 ALOGI("Dropped event because input dispatch is disabled.");
1122 }
1123 reason = "inbound event was dropped because input dispatch is disabled";
1124 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001125 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001126 ALOGI("Dropped event because of pending overdue app switch.");
1127 reason = "inbound event was dropped because of pending overdue app switch";
1128 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001129 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001130 ALOGI("Dropped event because the current application is not responding and the user "
1131 "has started interacting with a different application.");
1132 reason = "inbound event was dropped because the current application is not responding "
1133 "and the user has started interacting with a different application";
1134 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001135 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001136 ALOGI("Dropped event because it is stale.");
1137 reason = "inbound event was dropped because it is stale";
1138 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001139 case DropReason::NO_POINTER_CAPTURE:
1140 ALOGI("Dropped event because there is no window with Pointer Capture.");
1141 reason = "inbound event was dropped because there is no window with Pointer Capture";
1142 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001143 case DropReason::NOT_DROPPED: {
1144 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001145 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 }
1148
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001149 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001150 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1152 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001153 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001155 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001156 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1157 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001158 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1159 synthesizeCancelationEventsForAllConnectionsLocked(options);
1160 } else {
1161 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1162 synthesizeCancelationEventsForAllConnectionsLocked(options);
1163 }
1164 break;
1165 }
Chris Yef59a2f42020-10-16 12:55:26 -07001166 case EventEntry::Type::SENSOR: {
1167 break;
1168 }
arthurhungb89ccb02020-12-30 16:19:01 +08001169 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1170 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001171 break;
1172 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001173 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001174 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001175 case EventEntry::Type::CONFIGURATION_CHANGED:
1176 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001177 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001178 break;
1179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180 }
1181}
1182
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001183static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001184 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1185 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186}
1187
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001188bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1189 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1190 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1191 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192}
1193
1194bool InputDispatcher::isAppSwitchPendingLocked() {
1195 return mAppSwitchDueTime != LONG_LONG_MAX;
1196}
1197
1198void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1199 mAppSwitchDueTime = LONG_LONG_MAX;
1200
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001201 if (DEBUG_APP_SWITCH) {
1202 if (handled) {
1203 ALOGD("App switch has arrived.");
1204 } else {
1205 ALOGD("App switch was abandoned.");
1206 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208}
1209
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001211 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212}
1213
Prabir Pradhancef936d2021-07-21 16:17:52 +00001214bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001215 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216 return false;
1217 }
1218
1219 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001220 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001221 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001222 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1223 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001224 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225 return true;
1226}
1227
Prabir Pradhancef936d2021-07-21 16:17:52 +00001228void InputDispatcher::postCommandLocked(Command&& command) {
1229 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230}
1231
1232void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001233 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001234 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001235 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236 releaseInboundEventLocked(entry);
1237 }
1238 traceInboundQueueLengthLocked();
1239}
1240
1241void InputDispatcher::releasePendingEventLocked() {
1242 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001244 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 }
1246}
1247
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001248void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001250 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001251 if (DEBUG_DISPATCH_CYCLE) {
1252 ALOGD("Injected inbound event was dropped.");
1253 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001254 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 }
1256 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001257 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258 }
1259 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260}
1261
1262void InputDispatcher::resetKeyRepeatLocked() {
1263 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001264 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 }
1266}
1267
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001268std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1269 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270
Michael Wright2e732952014-09-24 13:26:59 -07001271 uint32_t policyFlags = entry->policyFlags &
1272 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001274 std::shared_ptr<KeyEntry> newEntry =
1275 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1276 entry->source, entry->displayId, policyFlags, entry->action,
1277 entry->flags, entry->keyCode, entry->scanCode,
1278 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001280 newEntry->syntheticRepeat = true;
1281 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001283 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284}
1285
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001286bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001287 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001288 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1289 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1290 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291
1292 // Reset key repeating in case a keyboard device was added or removed or something.
1293 resetKeyRepeatLocked();
1294
1295 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001296 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1297 scoped_unlock unlock(mLock);
1298 mPolicy->notifyConfigurationChanged(eventTime);
1299 };
1300 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001301 return true;
1302}
1303
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001304bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1305 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001306 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1307 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1308 entry.deviceId);
1309 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310
liushenxiang42232912021-05-21 20:24:09 +08001311 // Reset key repeating in case a keyboard device was disabled or enabled.
1312 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1313 resetKeyRepeatLocked();
1314 }
1315
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001316 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001317 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 synthesizeCancelationEventsForAllConnectionsLocked(options);
1319 return true;
1320}
1321
Vishnu Nairad321cd2020-08-20 16:40:21 -07001322void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001323 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001324 if (mPendingEvent != nullptr) {
1325 // Move the pending event to the front of the queue. This will give the chance
1326 // for the pending event to get dispatched to the newly focused window
1327 mInboundQueue.push_front(mPendingEvent);
1328 mPendingEvent = nullptr;
1329 }
1330
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001331 std::unique_ptr<FocusEntry> focusEntry =
1332 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1333 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001334
1335 // This event should go to the front of the queue, but behind all other focus events
1336 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001337 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001338 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001339 [](const std::shared_ptr<EventEntry>& event) {
1340 return event->type == EventEntry::Type::FOCUS;
1341 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001342
1343 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001344 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001345}
1346
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001347void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001348 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001349 if (channel == nullptr) {
1350 return; // Window has gone away
1351 }
1352 InputTarget target;
1353 target.inputChannel = channel;
1354 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1355 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001356 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1357 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001358 std::string reason = std::string("reason=").append(entry->reason);
1359 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001360 dispatchEventLocked(currentTime, entry, {target});
1361}
1362
Prabir Pradhan99987712020-11-10 18:43:05 -08001363void InputDispatcher::dispatchPointerCaptureChangedLocked(
1364 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1365 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001366 dropReason = DropReason::NOT_DROPPED;
1367
Prabir Pradhan99987712020-11-10 18:43:05 -08001368 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001369 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001370
1371 if (entry->pointerCaptureRequest.enable) {
1372 // Enable Pointer Capture.
1373 if (haveWindowWithPointerCapture &&
1374 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001375 // This can happen if pointer capture is disabled and re-enabled before we notify the
1376 // app of the state change, so there is no need to notify the app.
1377 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1378 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001379 }
1380 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001381 // This can happen if a window requests capture and immediately releases capture.
1382 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001383 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001384 return;
1385 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001386 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1387 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1388 return;
1389 }
1390
Vishnu Nairc519ff72021-01-21 08:23:08 -08001391 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001392 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1393 mWindowTokenWithPointerCapture = token;
1394 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001395 // Disable Pointer Capture.
1396 // We do not check if the sequence number matches for requests to disable Pointer Capture
1397 // for two reasons:
1398 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1399 // to disable capture with the same sequence number: one generated by
1400 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1401 // Capture being disabled in InputReader.
1402 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1403 // actual Pointer Capture state that affects events being generated by input devices is
1404 // in InputReader.
1405 if (!haveWindowWithPointerCapture) {
1406 // Pointer capture was already forcefully disabled because of focus change.
1407 dropReason = DropReason::NOT_DROPPED;
1408 return;
1409 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001410 token = mWindowTokenWithPointerCapture;
1411 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001412 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001413 setPointerCaptureLocked(false);
1414 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001415 }
1416
1417 auto channel = getInputChannelLocked(token);
1418 if (channel == nullptr) {
1419 // Window has gone away, clean up Pointer Capture state.
1420 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001421 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001422 setPointerCaptureLocked(false);
1423 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001424 return;
1425 }
1426 InputTarget target;
1427 target.inputChannel = channel;
1428 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1429 entry->dispatchInProgress = true;
1430 dispatchEventLocked(currentTime, entry, {target});
1431
1432 dropReason = DropReason::NOT_DROPPED;
1433}
1434
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001435void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1436 const std::shared_ptr<TouchModeEntry>& entry) {
1437 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1438 getWindowHandlesLocked(mFocusedDisplayId);
1439 if (windowHandles.empty()) {
1440 return;
1441 }
1442 const std::vector<InputTarget> inputTargets =
1443 getInputTargetsFromWindowHandlesLocked(windowHandles);
1444 if (inputTargets.empty()) {
1445 return;
1446 }
1447 entry->dispatchInProgress = true;
1448 dispatchEventLocked(currentTime, entry, inputTargets);
1449}
1450
1451std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1452 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1453 std::vector<InputTarget> inputTargets;
1454 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1455 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1456 const sp<IBinder>& token = handle->getToken();
1457 if (token == nullptr) {
1458 continue;
1459 }
1460 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1461 if (channel == nullptr) {
1462 continue; // Window has gone away
1463 }
1464 InputTarget target;
1465 target.inputChannel = channel;
1466 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1467 inputTargets.push_back(target);
1468 }
1469 return inputTargets;
1470}
1471
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001472bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001473 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001475 if (!entry->dispatchInProgress) {
1476 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1477 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1478 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1479 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001480 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481 // We have seen two identical key downs in a row which indicates that the device
1482 // driver is automatically generating key repeats itself. We take note of the
1483 // repeat here, but we disable our own next key repeat timer since it is clear that
1484 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001485 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1486 // Make sure we don't get key down from a different device. If a different
1487 // device Id has same key pressed down, the new device Id will replace the
1488 // current one to hold the key repeat with repeat count reset.
1489 // In the future when got a KEY_UP on the device id, drop it and do not
1490 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1492 resetKeyRepeatLocked();
1493 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1494 } else {
1495 // Not a repeat. Save key down state in case we do see a repeat later.
1496 resetKeyRepeatLocked();
1497 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1498 }
1499 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001500 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1501 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001502 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001503 if (DEBUG_INBOUND_EVENT_DETAILS) {
1504 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1505 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001506 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 resetKeyRepeatLocked();
1508 }
1509
1510 if (entry->repeatCount == 1) {
1511 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1512 } else {
1513 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1514 }
1515
1516 entry->dispatchInProgress = true;
1517
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001518 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519 }
1520
1521 // Handle case where the policy asked us to try again later last time.
1522 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1523 if (currentTime < entry->interceptKeyWakeupTime) {
1524 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1525 *nextWakeupTime = entry->interceptKeyWakeupTime;
1526 }
1527 return false; // wait until next wakeup
1528 }
1529 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1530 entry->interceptKeyWakeupTime = 0;
1531 }
1532
1533 // Give the policy a chance to intercept the key.
1534 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1535 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001536 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001537 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001538
1539 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1540 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1541 };
1542 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543 return false; // wait for the command to run
1544 } else {
1545 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1546 }
1547 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001548 if (*dropReason == DropReason::NOT_DROPPED) {
1549 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 }
1551 }
1552
1553 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001554 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001555 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001556 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1557 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001558 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559 return true;
1560 }
1561
1562 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001563 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001564 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001565 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001566 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 return false;
1568 }
1569
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001570 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001571 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 return true;
1573 }
1574
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001575 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001576 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577
1578 // Dispatch the key.
1579 dispatchEventLocked(currentTime, entry, inputTargets);
1580 return true;
1581}
1582
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001583void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001584 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1585 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1586 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1587 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1588 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1589 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1590 entry.metaState, entry.repeatCount, entry.downTime);
1591 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592}
1593
Prabir Pradhancef936d2021-07-21 16:17:52 +00001594void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1595 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001596 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001597 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1598 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1599 "source=0x%x, sensorType=%s",
1600 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001601 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001602 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001603 auto command = [this, entry]() REQUIRES(mLock) {
1604 scoped_unlock unlock(mLock);
1605
1606 if (entry->accuracyChanged) {
1607 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1608 }
1609 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1610 entry->hwTimestamp, entry->values);
1611 };
1612 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001613}
1614
1615bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001616 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1617 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001618 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001619 }
Chris Yef59a2f42020-10-16 12:55:26 -07001620 { // acquire lock
1621 std::scoped_lock _l(mLock);
1622
1623 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1624 std::shared_ptr<EventEntry> entry = *it;
1625 if (entry->type == EventEntry::Type::SENSOR) {
1626 it = mInboundQueue.erase(it);
1627 releaseInboundEventLocked(entry);
1628 }
1629 }
1630 }
1631 return true;
1632}
1633
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001634bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001635 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001636 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001638 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001639 entry->dispatchInProgress = true;
1640
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001641 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642 }
1643
1644 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001645 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001646 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001647 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1648 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 return true;
1650 }
1651
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001652 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001653
1654 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001655 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656
1657 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001658 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001659 if (isPointerEvent) {
1660 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001661
1662 if (mDragState &&
1663 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1664 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1665 pilferPointersLocked(mDragState->dragWindow->getToken());
1666 }
1667
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001668 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001669 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001670 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001671 } else {
1672 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001673 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001674 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001676 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001677 return false;
1678 }
1679
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001680 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001681 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001682 return true;
1683 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001684 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001685 CancelationOptions::Mode mode(isPointerEvent
1686 ? CancelationOptions::CANCEL_POINTER_EVENTS
1687 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1688 CancelationOptions options(mode, "input event injection failed");
1689 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690 return true;
1691 }
1692
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001693 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001694 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001695
1696 // Dispatch the motion.
1697 if (conflictingPointerActions) {
1698 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001699 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001700 synthesizeCancelationEventsForAllConnectionsLocked(options);
1701 }
1702 dispatchEventLocked(currentTime, entry, inputTargets);
1703 return true;
1704}
1705
chaviw98318de2021-05-19 16:45:23 -05001706void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001707 bool isExiting, const int32_t rawX,
1708 const int32_t rawY) {
1709 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001710 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001711 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1712 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001713
1714 enqueueInboundEventLocked(std::move(dragEntry));
1715}
1716
1717void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1718 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1719 if (channel == nullptr) {
1720 return; // Window has gone away
1721 }
1722 InputTarget target;
1723 target.inputChannel = channel;
1724 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1725 entry->dispatchInProgress = true;
1726 dispatchEventLocked(currentTime, entry, {target});
1727}
1728
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001729void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001730 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1731 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1732 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001733 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001734 "metaState=0x%x, buttonState=0x%x,"
1735 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1736 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001737 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1738 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1739 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001741 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1742 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1743 "x=%f, y=%f, pressure=%f, size=%f, "
1744 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1745 "orientation=%f",
1746 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1747 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1748 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1749 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1750 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1751 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1752 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1753 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1754 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1755 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1756 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758}
1759
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001760void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1761 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001762 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001763 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001764 if (DEBUG_DISPATCH_CYCLE) {
1765 ALOGD("dispatchEventToCurrentInputTargets");
1766 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001768 updateInteractionTokensLocked(*eventEntry, inputTargets);
1769
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1771
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001772 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001774 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001775 sp<Connection> connection =
1776 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001777 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001778 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001779 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001780 if (DEBUG_FOCUS) {
1781 ALOGD("Dropping event delivery to target with channel '%s' because it "
1782 "is no longer registered with the input dispatcher.",
1783 inputTarget.inputChannel->getName().c_str());
1784 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785 }
1786 }
1787}
1788
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001789void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1790 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1791 // If the policy decides to close the app, we will get a channel removal event via
1792 // unregisterInputChannel, and will clean up the connection that way. We are already not
1793 // sending new pointers to the connection when it blocked, but focused events will continue to
1794 // pile up.
1795 ALOGW("Canceling events for %s because it is unresponsive",
1796 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001797 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001798 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1799 "application not responding");
1800 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001801 }
1802}
1803
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001804void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001805 if (DEBUG_FOCUS) {
1806 ALOGD("Resetting ANR timeouts.");
1807 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808
1809 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001810 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001811 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812}
1813
Tiger Huang721e26f2018-07-24 22:26:19 +08001814/**
1815 * Get the display id that the given event should go to. If this event specifies a valid display id,
1816 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1817 * Focused display is the display that the user most recently interacted with.
1818 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001819int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001820 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001821 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001822 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001823 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1824 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001825 break;
1826 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001827 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001828 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1829 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001830 break;
1831 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001832 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001833 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001834 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001835 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001836 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001837 case EventEntry::Type::SENSOR:
1838 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001839 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001840 return ADISPLAY_ID_NONE;
1841 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001842 }
1843 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1844}
1845
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001846bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1847 const char* focusedWindowName) {
1848 if (mAnrTracker.empty()) {
1849 // already processed all events that we waited for
1850 mKeyIsWaitingForEventsTimeout = std::nullopt;
1851 return false;
1852 }
1853
1854 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1855 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001856 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001857 mKeyIsWaitingForEventsTimeout = currentTime +
1858 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1859 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001860 return true;
1861 }
1862
1863 // We still have pending events, and already started the timer
1864 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1865 return true; // Still waiting
1866 }
1867
1868 // Waited too long, and some connection still hasn't processed all motions
1869 // Just send the key to the focused window
1870 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1871 focusedWindowName);
1872 mKeyIsWaitingForEventsTimeout = std::nullopt;
1873 return false;
1874}
1875
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001876static std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
1877 if (eventEntry.type == EventEntry::Type::KEY) {
1878 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
1879 return keyEntry.downTime;
1880 } else if (eventEntry.type == EventEntry::Type::MOTION) {
1881 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
1882 return motionEntry.downTime;
1883 }
1884 return std::nullopt;
1885}
1886
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001887InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1888 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1889 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001890 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001891
Tiger Huang721e26f2018-07-24 22:26:19 +08001892 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001893 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001894 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001895 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1896
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897 // If there is no currently focused window and no focused application
1898 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001899 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1900 ALOGI("Dropping %s event because there is no focused window or focused application in "
1901 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001902 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001903 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 }
1905
Vishnu Nair062a8672021-09-03 16:07:44 -07001906 // Drop key events if requested by input feature
1907 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1908 return InputEventInjectionResult::FAILED;
1909 }
1910
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001911 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1912 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1913 // start interacting with another application via touch (app switch). This code can be removed
1914 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1915 // an app is expected to have a focused window.
1916 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1917 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1918 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001919 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1920 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1921 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001922 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001923 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001924 ALOGW("Waiting because no window has focus but %s may eventually add a "
1925 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001926 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001927 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001928 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001929 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1930 // Already raised ANR. Drop the event
1931 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001932 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001933 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001934 } else {
1935 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001936 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001937 }
1938 }
1939
1940 // we have a valid, non-null focused window
1941 resetNoFocusedWindowTimeoutLocked();
1942
Prabir Pradhan5735a322022-04-11 17:23:34 +00001943 // Verify targeted injection.
1944 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
1945 ALOGW("Dropping injected event: %s", (*err).c_str());
1946 return InputEventInjectionResult::TARGET_MISMATCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001947 }
1948
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001949 if (focusedWindowHandle->getInfo()->inputConfig.test(
1950 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001951 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001952 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001953 }
1954
1955 // If the event is a key event, then we must wait for all previous events to
1956 // complete before delivering it because previous events may have the
1957 // side-effect of transferring focus to a different window and we want to
1958 // ensure that the following keys are sent to the new window.
1959 //
1960 // Suppose the user touches a button in a window then immediately presses "A".
1961 // If the button causes a pop-up window to appear then we want to ensure that
1962 // the "A" key is delivered to the new pop-up window. This is because users
1963 // often anticipate pending UI changes when typing on a keyboard.
1964 // To obtain this behavior, we must serialize key events with respect to all
1965 // prior input events.
1966 if (entry.type == EventEntry::Type::KEY) {
1967 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1968 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001969 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001970 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 }
1972
1973 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001974 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001975 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001976 BitSet32(0), getDownTime(entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977
1978 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001979 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980}
1981
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001982/**
1983 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1984 * that are currently unresponsive.
1985 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001986std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1987 const std::vector<Monitor>& monitors) const {
1988 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001989 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001990 [this](const Monitor& monitor) REQUIRES(mLock) {
1991 sp<Connection> connection =
1992 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001993 if (connection == nullptr) {
1994 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001995 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001996 return false;
1997 }
1998 if (!connection->responsive) {
1999 ALOGW("Unresponsive monitor %s will not get the new gesture",
2000 connection->inputChannel->getName().c_str());
2001 return false;
2002 }
2003 return true;
2004 });
2005 return responsiveMonitors;
2006}
2007
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002008InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
2009 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
2010 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002011 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013 // For security reasons, we defer updating the touch state until we are sure that
2014 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002015 const int32_t displayId = entry.displayId;
2016 const int32_t action = entry.action;
2017 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018
2019 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002020 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
chaviw98318de2021-05-19 16:45:23 -05002021 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2022 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002024 // Copy current touch state into tempTouchState.
2025 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2026 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002027 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002028 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002029 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2030 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002031 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002032 }
2033
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002034 bool isSplit = tempTouchState.split;
2035 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2036 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2037 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002038
2039 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2040 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2041 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2042 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2043 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002044 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002045 bool wrongDevice = false;
2046 if (newGesture) {
2047 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002048 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002049 ALOGI("Dropping event because a pointer for a different device is already down "
2050 "in display %" PRId32,
2051 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002052 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002053 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054 switchedDevice = false;
2055 wrongDevice = true;
2056 goto Failed;
2057 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002058 tempTouchState.reset();
2059 tempTouchState.down = down;
2060 tempTouchState.deviceId = entry.deviceId;
2061 tempTouchState.source = entry.source;
2062 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002064 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002065 ALOGI("Dropping move event because a pointer for a different device is already active "
2066 "in display %" PRId32,
2067 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002068 // TODO: test multiple simultaneous input streams.
Prabir Pradhan5735a322022-04-11 17:23:34 +00002069 injectionResult = InputEventInjectionResult::FAILED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002070 switchedDevice = false;
2071 wrongDevice = true;
2072 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073 }
2074
2075 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2076 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2077
Garfield Tan00f511d2019-06-12 16:55:40 -07002078 int32_t x;
2079 int32_t y;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002080 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002081 // Always dispatch mouse events to cursor position.
2082 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002083 x = int32_t(entry.xCursorPosition);
2084 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002085 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002086 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2087 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002088 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002089 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002090 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002091 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002092 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002093
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002095 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002096 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2097 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002099 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002100 }
2101
Prabir Pradhan5735a322022-04-11 17:23:34 +00002102 // Verify targeted injection.
2103 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2104 ALOGW("Dropping injected touch event: %s", (*err).c_str());
2105 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2106 newTouchedWindowHandle = nullptr;
2107 goto Failed;
2108 }
2109
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002110 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002111 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002112 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2113 // New window supports splitting, but we should never split mouse events.
2114 isSplit = !isFromMouse;
2115 } else if (isSplit) {
2116 // New window does not support splitting but we have already split events.
2117 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002118 newTouchedWindowHandle = nullptr;
2119 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002120 } else {
2121 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002122 // be delivered to a new window which supports split touch. Pointers from a mouse device
2123 // should never be split.
2124 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002125 }
2126
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002127 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002128 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002129 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2130 newHoverWindowHandle = nullptr;
2131 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002132 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002133 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002134 }
2135
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002136 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002137 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002138 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002139 // Process the foreground window first so that it is the first to receive the event.
2140 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002141 }
2142
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002143 if (newTouchedWindows.empty()) {
2144 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2145 x, y, displayId);
2146 injectionResult = InputEventInjectionResult::FAILED;
2147 goto Failed;
2148 }
2149
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002150 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2151 const WindowInfo& info = *windowHandle->getInfo();
2152
Prabir Pradhan5735a322022-04-11 17:23:34 +00002153 // Skip spy window targets that are not valid for targeted injection.
2154 if (const auto err = verifyTargetedInjection(windowHandle, entry); err) {
2155 continue;
2156 }
2157
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002158 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002159 ALOGI("Not sending touch event to %s because it is paused",
2160 windowHandle->getName().c_str());
2161 continue;
2162 }
2163
2164 // Ensure the window has a connection and the connection is responsive
2165 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2166 if (!isResponsive) {
2167 ALOGW("Not sending touch gesture to %s because it is not responsive",
2168 windowHandle->getName().c_str());
2169 continue;
2170 }
2171
2172 // Drop events that can't be trusted due to occlusion
Hani Kazmi3ce9c3a2022-04-25 09:40:23 +00002173 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(windowHandle, x, y);
2174 if (!isTouchTrustedLocked(occlusionInfo)) {
2175 if (DEBUG_TOUCH_OCCLUSION) {
2176 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2177 for (const auto& log : occlusionInfo.debugInfo) {
2178 ALOGD("%s", log.c_str());
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002179 }
2180 }
Hani Kazmi3ce9c3a2022-04-25 09:40:23 +00002181 ALOGW("Dropping untrusted touch event due to %s/%d",
2182 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2183 continue;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002184 }
2185
2186 // Drop touch events if requested by input feature
2187 if (shouldDropInput(entry, windowHandle)) {
2188 continue;
2189 }
2190
2191 // Set target flags.
2192 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2193
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002194 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2195 // There should only be one touched window that can be "foreground" for the pointer.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002196 targetFlags |= InputTarget::FLAG_FOREGROUND;
2197 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002198
2199 if (isSplit) {
2200 targetFlags |= InputTarget::FLAG_SPLIT;
2201 }
2202 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2203 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2204 } else if (isWindowObscuredLocked(windowHandle)) {
2205 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2206 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002207
2208 // Update the temporary touch state.
2209 BitSet32 pointerIds;
2210 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002211 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002212 pointerIds.markBit(pointerId);
2213 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002214
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002215 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
2216 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002217 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002218
2219 // If any existing window is pilfering pointers from newly added window, remove it
2220 BitSet32 canceledPointers = BitSet32(0);
2221 for (const TouchedWindow& window : tempTouchState.windows) {
2222 if (window.isPilferingPointers) {
2223 canceledPointers |= window.pointerIds;
2224 }
2225 }
2226 tempTouchState.cancelPointersForNonPilferingWindows(canceledPointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227 } else {
2228 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2229
2230 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002231 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002232 if (DEBUG_FOCUS) {
2233 ALOGD("Dropping event because the pointer is not down or we previously "
2234 "dropped the pointer down event in display %" PRId32,
2235 displayId);
2236 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002237 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238 goto Failed;
2239 }
2240
arthurhung6d4bed92021-03-17 11:59:33 +08002241 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002242
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002244 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002245 tempTouchState.isSlippery()) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002246 const int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2247 const int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248
Prabir Pradhand65552b2021-10-07 11:23:50 -07002249 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002250 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002251 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002252 newTouchedWindowHandle =
2253 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002254
Prabir Pradhan5735a322022-04-11 17:23:34 +00002255 // Verify targeted injection.
2256 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2257 ALOGW("Dropping injected event: %s", (*err).c_str());
2258 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2259 newTouchedWindowHandle = nullptr;
2260 goto Failed;
2261 }
2262
Vishnu Nair062a8672021-09-03 16:07:44 -07002263 // Drop touch events if requested by input feature
2264 if (newTouchedWindowHandle != nullptr &&
2265 shouldDropInput(entry, newTouchedWindowHandle)) {
2266 newTouchedWindowHandle = nullptr;
2267 }
2268
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002269 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2270 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002271 if (DEBUG_FOCUS) {
2272 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2273 oldTouchedWindowHandle->getName().c_str(),
2274 newTouchedWindowHandle->getName().c_str(), displayId);
2275 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002277 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2278 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2279 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280
2281 // Make a slippery entrance into the new window.
2282 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002283 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284 }
2285
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002286 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
2287 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
2288 targetFlags |= InputTarget::FLAG_FOREGROUND;
2289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290 if (isSplit) {
2291 targetFlags |= InputTarget::FLAG_SPLIT;
2292 }
2293 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2294 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002295 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2296 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297 }
2298
2299 BitSet32 pointerIds;
2300 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002301 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002302 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002303 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2304 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 }
2306 }
2307 }
2308
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002309 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002311 // Let the previous window know that the hover sequence is over, unless we already did
2312 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002313 if (mLastHoverWindowHandle != nullptr &&
2314 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2315 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002316 if (DEBUG_HOVER) {
2317 ALOGD("Sending hover exit event to window %s.",
2318 mLastHoverWindowHandle->getName().c_str());
2319 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002320 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2321 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322 }
2323
Garfield Tandf26e862020-07-01 20:18:19 -07002324 // Let the new window know that the hover sequence is starting, unless we already did it
2325 // when dispatching it as is to newTouchedWindowHandle.
2326 if (newHoverWindowHandle != nullptr &&
2327 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2328 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002329 if (DEBUG_HOVER) {
2330 ALOGD("Sending hover enter event to window %s.",
2331 newHoverWindowHandle->getName().c_str());
2332 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002333 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2334 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2335 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336 }
2337 }
2338
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002339 // Ensure that we have at least one foreground window or at least one window that cannot be a
2340 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2341 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2342 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002343 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2344 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002345 return !canReceiveForegroundTouches(
2346 *touchedWindow.windowHandle->getInfo()) ||
2347 (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002348 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002349 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2350 displayId, entry.getDescription().c_str());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002351 injectionResult = InputEventInjectionResult::FAILED;
2352 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353 }
2354
Prabir Pradhan5735a322022-04-11 17:23:34 +00002355 // Ensure that all touched windows are valid for injection.
2356 if (entry.injectionState != nullptr) {
2357 std::string errs;
2358 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
2359 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2360 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2361 // dispatched to any uid, since the coords will be zeroed out later.
2362 continue;
2363 }
2364 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2365 if (err) errs += "\n - " + *err;
2366 }
2367 if (!errs.empty()) {
2368 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2369 "%d:%s",
2370 *entry.injectionState->targetUid, errs.c_str());
2371 injectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2372 goto Failed;
2373 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002374 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002375
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376 // Check whether windows listening for outside touches are owned by the same UID. If it is
2377 // set the policy flag that we will not reveal coordinate information to this window.
2378 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002379 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002380 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002381 if (foregroundWindowHandle) {
2382 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002383 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002384 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002385 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2386 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2387 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002388 InputTarget::FLAG_ZERO_COORDS,
2389 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002391 }
2392 }
2393 }
2394 }
2395
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396 // If this is the first pointer going down and the touched window has a wallpaper
2397 // then also add the touched wallpaper windows so they are locked in for the duration
2398 // of the touch gesture.
2399 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2400 // engine only supports touch events. We would need to add a mechanism similar
2401 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2402 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002403 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002404 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002405 if (foregroundWindowHandle &&
2406 foregroundWindowHandle->getInfo()->inputConfig.test(
2407 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002408 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002409 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002410 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2411 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002412 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002413 windowHandle->getInfo()->inputConfig.test(
2414 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002415 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002416 .addOrUpdateWindow(windowHandle,
2417 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2418 InputTarget::
2419 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2420 InputTarget::FLAG_DISPATCH_AS_IS,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002421 BitSet32(0), entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422 }
2423 }
2424 }
2425 }
2426
2427 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002428 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002429
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002430 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002431 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002432 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2433 inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002434 }
2435
2436 // Drop the outside or hover touch windows since we will not care about them
2437 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002438 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002439
2440Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002442 if (!wrongDevice) {
2443 if (switchedDevice) {
2444 if (DEBUG_FOCUS) {
2445 ALOGD("Conflicting pointer actions: Switched to a different device.");
2446 }
2447 *outConflictingPointerActions = true;
2448 }
2449
2450 if (isHoverAction) {
2451 // Started hovering, therefore no longer down.
2452 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002453 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002454 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2455 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002456 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457 *outConflictingPointerActions = true;
2458 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002459 tempTouchState.reset();
2460 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2461 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2462 tempTouchState.deviceId = entry.deviceId;
2463 tempTouchState.source = entry.source;
2464 tempTouchState.displayId = displayId;
2465 }
2466 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2467 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2468 // All pointers up or canceled.
2469 tempTouchState.reset();
2470 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2471 // First pointer went down.
2472 if (oldState && oldState->down) {
2473 if (DEBUG_FOCUS) {
2474 ALOGD("Conflicting pointer actions: Down received while already down.");
2475 }
2476 *outConflictingPointerActions = true;
2477 }
2478 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2479 // One pointer went up.
2480 if (isSplit) {
2481 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2482 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002484 for (size_t i = 0; i < tempTouchState.windows.size();) {
2485 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2486 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
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 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002492 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002493 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002495 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002496 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002497
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002498 // Save changes unless the action was scroll in which case the temporary touch
2499 // state was only valid for this one action.
2500 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2501 if (tempTouchState.displayId >= 0) {
2502 mTouchStatesByDisplay[displayId] = tempTouchState;
2503 } else {
2504 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002506 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002507
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002508 // Update hover state.
2509 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510 }
2511
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 return injectionResult;
2513}
2514
arthurhung6d4bed92021-03-17 11:59:33 +08002515void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002516 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2517 // have an explicit reason to support it.
2518 constexpr bool isStylus = false;
2519
chaviw98318de2021-05-19 16:45:23 -05002520 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002521 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002522 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002523 if (dropWindow) {
2524 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002525 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002526 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002527 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002528 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002529 }
2530 mDragState.reset();
2531}
2532
2533void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002534 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002535 return;
2536 }
2537
arthurhung6d4bed92021-03-17 11:59:33 +08002538 if (!mDragState->isStartDrag) {
2539 mDragState->isStartDrag = true;
2540 mDragState->isStylusButtonDownAtStart =
2541 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2542 }
2543
Arthur Hung54745652022-04-20 07:17:41 +00002544 // Find the pointer index by id.
2545 int32_t pointerIndex = 0;
2546 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2547 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2548 if (pointerProperties.id == mDragState->pointerId) {
2549 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002550 }
Arthur Hung54745652022-04-20 07:17:41 +00002551 }
arthurhung6d4bed92021-03-17 11:59:33 +08002552
Arthur Hung54745652022-04-20 07:17:41 +00002553 if (uint32_t(pointerIndex) == entry.pointerCount) {
2554 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002555 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002556 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002557 return;
2558 }
2559
2560 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2561 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2562 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2563
2564 switch (maskedAction) {
2565 case AMOTION_EVENT_ACTION_MOVE: {
2566 // Handle the special case : stylus button no longer pressed.
2567 bool isStylusButtonDown =
2568 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2569 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2570 finishDragAndDrop(entry.displayId, x, y);
2571 return;
2572 }
2573
2574 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2575 // until we have an explicit reason to support it.
2576 constexpr bool isStylus = false;
2577
2578 const sp<WindowInfoHandle> hoverWindowHandle =
2579 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2580 isStylus, false /*addOutsideTargets*/,
2581 true /*ignoreDragWindow*/);
2582 // enqueue drag exit if needed.
2583 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2584 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2585 if (mDragState->dragHoverWindowHandle != nullptr) {
2586 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2587 y);
2588 }
2589 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2590 }
2591 // enqueue drag location if needed.
2592 if (hoverWindowHandle != nullptr) {
2593 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2594 }
2595 break;
2596 }
2597
2598 case AMOTION_EVENT_ACTION_POINTER_UP:
2599 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2600 break;
2601 }
2602 // The drag pointer is up.
2603 [[fallthrough]];
2604 case AMOTION_EVENT_ACTION_UP:
2605 finishDragAndDrop(entry.displayId, x, y);
2606 break;
2607 case AMOTION_EVENT_ACTION_CANCEL: {
2608 ALOGD("Receiving cancel when drag and drop.");
2609 sendDropWindowCommandLocked(nullptr, 0, 0);
2610 mDragState.reset();
2611 break;
2612 }
arthurhungb89ccb02020-12-30 16:19:01 +08002613 }
2614}
2615
chaviw98318de2021-05-19 16:45:23 -05002616void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002617 int32_t targetFlags, BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002618 std::optional<nsecs_t> firstDownTimeInTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002619 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002620 std::vector<InputTarget>::iterator it =
2621 std::find_if(inputTargets.begin(), inputTargets.end(),
2622 [&windowHandle](const InputTarget& inputTarget) {
2623 return inputTarget.inputChannel->getConnectionToken() ==
2624 windowHandle->getToken();
2625 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002626
chaviw98318de2021-05-19 16:45:23 -05002627 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002628
2629 if (it == inputTargets.end()) {
2630 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002631 std::shared_ptr<InputChannel> inputChannel =
2632 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002633 if (inputChannel == nullptr) {
2634 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2635 return;
2636 }
2637 inputTarget.inputChannel = inputChannel;
2638 inputTarget.flags = targetFlags;
2639 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002640 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002641 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2642 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002643 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002644 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002645 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002646 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002647 inputTargets.push_back(inputTarget);
2648 it = inputTargets.end() - 1;
2649 }
2650
2651 ALOG_ASSERT(it->flags == targetFlags);
2652 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2653
chaviw1ff3d1e2020-07-01 15:53:47 -07002654 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002655}
2656
Michael Wright3dd60e22019-03-27 22:06:44 +00002657void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002658 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002659 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2660 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002661
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002662 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2663 InputTarget target;
2664 target.inputChannel = monitor.inputChannel;
2665 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002666 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2667 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002668 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2669 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002670 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002671 target.setDefaultPointerTransform(target.displayTransform);
2672 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002673 }
2674}
2675
Robert Carrc9bf1d32020-04-13 17:21:08 -07002676/**
2677 * Indicate whether one window handle should be considered as obscuring
2678 * another window handle. We only check a few preconditions. Actually
2679 * checking the bounds is left to the caller.
2680 */
chaviw98318de2021-05-19 16:45:23 -05002681static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2682 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002683 // Compare by token so cloned layers aren't counted
2684 if (haveSameToken(windowHandle, otherHandle)) {
2685 return false;
2686 }
2687 auto info = windowHandle->getInfo();
2688 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002689 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002690 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002691 } else if (otherInfo->alpha == 0 &&
2692 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002693 // Those act as if they were invisible, so we don't need to flag them.
2694 // We do want to potentially flag touchable windows even if they have 0
2695 // opacity, since they can consume touches and alter the effects of the
2696 // user interaction (eg. apps that rely on
2697 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2698 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2699 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002700 } else if (info->ownerUid == otherInfo->ownerUid) {
2701 // If ownerUid is the same we don't generate occlusion events as there
2702 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002703 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002704 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002705 return false;
2706 } else if (otherInfo->displayId != info->displayId) {
2707 return false;
2708 }
2709 return true;
2710}
2711
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002712/**
2713 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2714 * untrusted, one should check:
2715 *
2716 * 1. If result.hasBlockingOcclusion is true.
2717 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2718 * BLOCK_UNTRUSTED.
2719 *
2720 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2721 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2722 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2723 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2724 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2725 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2726 *
2727 * If neither of those is true, then it means the touch can be allowed.
2728 */
2729InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002730 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2731 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002732 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002733 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002734 TouchOcclusionInfo info;
2735 info.hasBlockingOcclusion = false;
2736 info.obscuringOpacity = 0;
2737 info.obscuringUid = -1;
2738 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002739 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002740 if (windowHandle == otherHandle) {
2741 break; // All future windows are below us. Exit early.
2742 }
chaviw98318de2021-05-19 16:45:23 -05002743 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002744 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2745 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002746 if (DEBUG_TOUCH_OCCLUSION) {
2747 info.debugInfo.push_back(
2748 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2749 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002750 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2751 // we perform the checks below to see if the touch can be propagated or not based on the
2752 // window's touch occlusion mode
2753 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2754 info.hasBlockingOcclusion = true;
2755 info.obscuringUid = otherInfo->ownerUid;
2756 info.obscuringPackage = otherInfo->packageName;
2757 break;
2758 }
2759 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2760 uint32_t uid = otherInfo->ownerUid;
2761 float opacity =
2762 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2763 // Given windows A and B:
2764 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2765 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2766 opacityByUid[uid] = opacity;
2767 if (opacity > info.obscuringOpacity) {
2768 info.obscuringOpacity = opacity;
2769 info.obscuringUid = uid;
2770 info.obscuringPackage = otherInfo->packageName;
2771 }
2772 }
2773 }
2774 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002775 if (DEBUG_TOUCH_OCCLUSION) {
2776 info.debugInfo.push_back(
2777 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2778 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002779 return info;
2780}
2781
chaviw98318de2021-05-19 16:45:23 -05002782std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002783 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002784 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2785 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2786 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2787 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002788 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2789 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2790 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2791 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2792 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002793 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002794 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002795}
2796
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002797bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2798 if (occlusionInfo.hasBlockingOcclusion) {
2799 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2800 occlusionInfo.obscuringUid);
2801 return false;
2802 }
2803 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2804 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2805 "%.2f, maximum allowed = %.2f)",
2806 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2807 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2808 return false;
2809 }
2810 return true;
2811}
2812
chaviw98318de2021-05-19 16:45:23 -05002813bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002814 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002815 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002816 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2817 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002818 if (windowHandle == otherHandle) {
2819 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820 }
chaviw98318de2021-05-19 16:45:23 -05002821 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002822 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002823 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824 return true;
2825 }
2826 }
2827 return false;
2828}
2829
chaviw98318de2021-05-19 16:45:23 -05002830bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002831 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002832 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2833 const WindowInfo* windowInfo = windowHandle->getInfo();
2834 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002835 if (windowHandle == otherHandle) {
2836 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002837 }
chaviw98318de2021-05-19 16:45:23 -05002838 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002839 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002840 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002841 return true;
2842 }
2843 }
2844 return false;
2845}
2846
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002847std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002848 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002849 if (applicationHandle != nullptr) {
2850 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002851 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852 } else {
2853 return applicationHandle->getName();
2854 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002855 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002856 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002857 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002858 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002859 }
2860}
2861
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002862void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002863 if (!isUserActivityEvent(eventEntry)) {
2864 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002865 return;
2866 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002867 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002868 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002869 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002870 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002871 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002872 if (DEBUG_DISPATCH_CYCLE) {
2873 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2874 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002875 return;
2876 }
2877 }
2878
2879 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002880 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002881 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002882 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2883 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002884 return;
2885 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002887 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002888 eventType = USER_ACTIVITY_EVENT_TOUCH;
2889 }
2890 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002892 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002893 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2894 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002895 return;
2896 }
2897 eventType = USER_ACTIVITY_EVENT_BUTTON;
2898 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002899 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002900 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002901 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002902 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002903 break;
2904 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002905 }
2906
Prabir Pradhancef936d2021-07-21 16:17:52 +00002907 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2908 REQUIRES(mLock) {
2909 scoped_unlock unlock(mLock);
2910 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2911 };
2912 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002913}
2914
2915void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002916 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002917 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002918 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002919 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002920 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002921 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002922 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002923 ATRACE_NAME(message.c_str());
2924 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002925 if (DEBUG_DISPATCH_CYCLE) {
2926 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2927 "globalScaleFactor=%f, pointerIds=0x%x %s",
2928 connection->getInputChannelName().c_str(), inputTarget.flags,
2929 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2930 inputTarget.getPointerInfoString().c_str());
2931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002932
2933 // Skip this event if the connection status is not normal.
2934 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002935 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002936 if (DEBUG_DISPATCH_CYCLE) {
2937 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002938 connection->getInputChannelName().c_str(),
2939 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002940 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002941 return;
2942 }
2943
2944 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002945 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2946 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2947 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002948 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002949
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002950 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002951 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002952 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
2953 "Splitting motion events requires a down time to be set for the "
2954 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002955 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002956 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
2957 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002958 if (!splitMotionEntry) {
2959 return; // split event was dropped
2960 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002961 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2962 std::string reason = std::string("reason=pointer cancel on split window");
2963 android_log_event_list(LOGTAG_INPUT_CANCEL)
2964 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2965 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002966 if (DEBUG_FOCUS) {
2967 ALOGD("channel '%s' ~ Split motion event.",
2968 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002969 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002970 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002971 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2972 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973 return;
2974 }
2975 }
2976
2977 // Not splitting. Enqueue dispatch entries for the event as is.
2978 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2979}
2980
2981void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002982 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002983 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002984 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002985 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002986 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002987 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002988 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002989 ATRACE_NAME(message.c_str());
2990 }
2991
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002992 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002993
2994 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002995 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002996 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002997 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002998 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002999 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003000 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003001 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003002 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003003 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003004 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003005 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003006 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003007
3008 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003009 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003010 startDispatchCycleLocked(currentTime, connection);
3011 }
3012}
3013
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003014void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003015 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003016 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003017 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003018 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003019 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3020 connection->getInputChannelName().c_str(),
3021 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003022 ATRACE_NAME(message.c_str());
3023 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003024 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003025 if (!(inputTargetFlags & dispatchMode)) {
3026 return;
3027 }
3028 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
3029
3030 // This is a new event.
3031 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003032 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003033 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003034
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003035 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3036 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003037 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003039 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003040 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003041 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003042 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003043 dispatchEntry->resolvedAction = keyEntry.action;
3044 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003045
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003046 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3047 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003048 if (DEBUG_DISPATCH_CYCLE) {
3049 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3050 "event",
3051 connection->getInputChannelName().c_str());
3052 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003053 return; // skip the inconsistent event
3054 }
3055 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003057
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003058 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003059 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003060 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3061 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3062 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3063 static_cast<int32_t>(IdGenerator::Source::OTHER);
3064 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003065 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3066 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3067 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3068 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3069 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3070 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3071 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3072 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3073 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3074 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3075 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003076 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003077 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003078 }
3079 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003080 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3081 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003082 if (DEBUG_DISPATCH_CYCLE) {
3083 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3084 "enter event",
3085 connection->getInputChannelName().c_str());
3086 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003087 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3088 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003089 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3090 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003091
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003092 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003093 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3094 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3095 }
3096 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3097 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3098 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003099
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003100 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3101 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003102 if (DEBUG_DISPATCH_CYCLE) {
3103 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3104 "event",
3105 connection->getInputChannelName().c_str());
3106 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003107 return; // skip the inconsistent event
3108 }
3109
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003110 dispatchEntry->resolvedEventId =
3111 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3112 ? mIdGenerator.nextId()
3113 : motionEntry.id;
3114 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3115 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3116 ") to MotionEvent(id=0x%" PRIx32 ").",
3117 motionEntry.id, dispatchEntry->resolvedEventId);
3118 ATRACE_NAME(message.c_str());
3119 }
3120
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003121 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3122 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3123 // Skip reporting pointer down outside focus to the policy.
3124 break;
3125 }
3126
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003127 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003128 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003129
3130 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003131 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003132 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003133 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003134 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3135 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003136 break;
3137 }
Chris Yef59a2f42020-10-16 12:55:26 -07003138 case EventEntry::Type::SENSOR: {
3139 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3140 break;
3141 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003142 case EventEntry::Type::CONFIGURATION_CHANGED:
3143 case EventEntry::Type::DEVICE_RESET: {
3144 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003145 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003146 break;
3147 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148 }
3149
3150 // Remember that we are waiting for this dispatch to complete.
3151 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003152 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 }
3154
3155 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003156 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003157 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003158}
3159
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003160/**
3161 * This function is purely for debugging. It helps us understand where the user interaction
3162 * was taking place. For example, if user is touching launcher, we will see a log that user
3163 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3164 * We will see both launcher and wallpaper in that list.
3165 * Once the interaction with a particular set of connections starts, no new logs will be printed
3166 * until the set of interacted connections changes.
3167 *
3168 * The following items are skipped, to reduce the logspam:
3169 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3170 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3171 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3172 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3173 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003174 */
3175void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3176 const std::vector<InputTarget>& targets) {
3177 // Skip ACTION_UP events, and all events other than keys and motions
3178 if (entry.type == EventEntry::Type::KEY) {
3179 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3180 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3181 return;
3182 }
3183 } else if (entry.type == EventEntry::Type::MOTION) {
3184 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3185 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3186 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3187 return;
3188 }
3189 } else {
3190 return; // Not a key or a motion
3191 }
3192
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003193 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003194 std::vector<sp<Connection>> newConnections;
3195 for (const InputTarget& target : targets) {
3196 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3197 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3198 continue; // Skip windows that receive ACTION_OUTSIDE
3199 }
3200
3201 sp<IBinder> token = target.inputChannel->getConnectionToken();
3202 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003203 if (connection == nullptr) {
3204 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003205 }
3206 newConnectionTokens.insert(std::move(token));
3207 newConnections.emplace_back(connection);
3208 }
3209 if (newConnectionTokens == mInteractionConnectionTokens) {
3210 return; // no change
3211 }
3212 mInteractionConnectionTokens = newConnectionTokens;
3213
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003214 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003215 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003216 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003217 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003218 std::string message = "Interaction with: " + targetList;
3219 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003220 message += "<none>";
3221 }
3222 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3223}
3224
chaviwfd6d3512019-03-25 13:23:49 -07003225void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003226 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003227 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003228 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3229 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003230 return;
3231 }
3232
Vishnu Nairc519ff72021-01-21 08:23:08 -08003233 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003234 if (focusedToken == token) {
3235 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003236 return;
3237 }
3238
Prabir Pradhancef936d2021-07-21 16:17:52 +00003239 auto command = [this, token]() REQUIRES(mLock) {
3240 scoped_unlock unlock(mLock);
3241 mPolicy->onPointerDownOutsideFocus(token);
3242 };
3243 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244}
3245
3246void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003247 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003248 if (ATRACE_ENABLED()) {
3249 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003250 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003251 ATRACE_NAME(message.c_str());
3252 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003253 if (DEBUG_DISPATCH_CYCLE) {
3254 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003257 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003258 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003259 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003260 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003261 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003262
3263 // Publish the event.
3264 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003265 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3266 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003267 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003268 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3269 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003270
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003271 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003272 status = connection->inputPublisher
3273 .publishKeyEvent(dispatchEntry->seq,
3274 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3275 keyEntry.source, keyEntry.displayId,
3276 std::move(hmac), dispatchEntry->resolvedAction,
3277 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3278 keyEntry.scanCode, keyEntry.metaState,
3279 keyEntry.repeatCount, keyEntry.downTime,
3280 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003281 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003282 }
3283
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003284 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003285 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003287 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003288 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003289
chaviw82357092020-01-28 13:13:06 -08003290 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003291 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003292 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3293 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003294 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003295 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3296 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003297 // Don't apply window scale here since we don't want scale to affect raw
3298 // coordinates. The scale will be sent back to the client and applied
3299 // later when requesting relative coordinates.
3300 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3301 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003302 }
3303 usingCoords = scaledCoords;
3304 }
3305 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003306 // We don't want the dispatch target to know.
3307 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003308 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003309 scaledCoords[i].clear();
3310 }
3311 usingCoords = scaledCoords;
3312 }
3313 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003314
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003315 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003316
3317 // Publish the motion event.
3318 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003319 .publishMotionEvent(dispatchEntry->seq,
3320 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003321 motionEntry.deviceId, motionEntry.source,
3322 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003323 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003324 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003325 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003326 motionEntry.edgeFlags, motionEntry.metaState,
3327 motionEntry.buttonState,
3328 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003329 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003330 motionEntry.xPrecision, motionEntry.yPrecision,
3331 motionEntry.xCursorPosition,
3332 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003333 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003334 motionEntry.downTime, motionEntry.eventTime,
3335 motionEntry.pointerCount,
3336 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003337 break;
3338 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003339
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003340 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003341 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003342 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003343 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003344 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003345 break;
3346 }
3347
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003348 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3349 const TouchModeEntry& touchModeEntry =
3350 static_cast<const TouchModeEntry&>(eventEntry);
3351 status = connection->inputPublisher
3352 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3353 touchModeEntry.inTouchMode);
3354
3355 break;
3356 }
3357
Prabir Pradhan99987712020-11-10 18:43:05 -08003358 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3359 const auto& captureEntry =
3360 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3361 status = connection->inputPublisher
3362 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003363 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003364 break;
3365 }
3366
arthurhungb89ccb02020-12-30 16:19:01 +08003367 case EventEntry::Type::DRAG: {
3368 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3369 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3370 dragEntry.id, dragEntry.x,
3371 dragEntry.y,
3372 dragEntry.isExiting);
3373 break;
3374 }
3375
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003376 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003377 case EventEntry::Type::DEVICE_RESET:
3378 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003379 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003380 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003381 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003382 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383 }
3384
3385 // Check the result.
3386 if (status) {
3387 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003388 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003389 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003390 "This is unexpected because the wait queue is empty, so the pipe "
3391 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003392 "event to it, status=%s(%d)",
3393 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3394 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003395 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3396 } else {
3397 // Pipe is full and we are waiting for the app to finish process some events
3398 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003399 if (DEBUG_DISPATCH_CYCLE) {
3400 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3401 "waiting for the application to catch up",
3402 connection->getInputChannelName().c_str());
3403 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404 }
3405 } else {
3406 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003407 "status=%s(%d)",
3408 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3409 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3411 }
3412 return;
3413 }
3414
3415 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003416 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3417 connection->outboundQueue.end(),
3418 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003419 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003420 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003421 if (connection->responsive) {
3422 mAnrTracker.insert(dispatchEntry->timeoutTime,
3423 connection->inputChannel->getConnectionToken());
3424 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003425 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426 }
3427}
3428
chaviw09c8d2d2020-08-24 15:48:26 -07003429std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3430 size_t size;
3431 switch (event.type) {
3432 case VerifiedInputEvent::Type::KEY: {
3433 size = sizeof(VerifiedKeyEvent);
3434 break;
3435 }
3436 case VerifiedInputEvent::Type::MOTION: {
3437 size = sizeof(VerifiedMotionEvent);
3438 break;
3439 }
3440 }
3441 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3442 return mHmacKeyManager.sign(start, size);
3443}
3444
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003445const std::array<uint8_t, 32> InputDispatcher::getSignature(
3446 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003447 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3448 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003449 // Only sign events up and down events as the purely move events
3450 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003451 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003452 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003453
3454 VerifiedMotionEvent verifiedEvent =
3455 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3456 verifiedEvent.actionMasked = actionMasked;
3457 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3458 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003459}
3460
3461const std::array<uint8_t, 32> InputDispatcher::getSignature(
3462 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3463 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3464 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3465 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003466 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003467}
3468
Michael Wrightd02c5b62014-02-10 15:10:22 -08003469void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003470 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003471 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003472 if (DEBUG_DISPATCH_CYCLE) {
3473 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3474 connection->getInputChannelName().c_str(), seq, toString(handled));
3475 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003476
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003477 if (connection->status == Connection::Status::BROKEN ||
3478 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479 return;
3480 }
3481
3482 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003483 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3484 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3485 };
3486 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003487}
3488
3489void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003490 const sp<Connection>& connection,
3491 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003492 if (DEBUG_DISPATCH_CYCLE) {
3493 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3494 connection->getInputChannelName().c_str(), toString(notify));
3495 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496
3497 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003498 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003499 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003500 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003501 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502
3503 // The connection appears to be unrecoverably broken.
3504 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003505 if (connection->status == Connection::Status::NORMAL) {
3506 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003507
3508 if (notify) {
3509 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003510 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3511 connection->getInputChannelName().c_str());
3512
3513 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003514 scoped_unlock unlock(mLock);
3515 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3516 };
3517 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003518 }
3519 }
3520}
3521
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003522void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3523 while (!queue.empty()) {
3524 DispatchEntry* dispatchEntry = queue.front();
3525 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003526 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 }
3528}
3529
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003530void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003532 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533 }
3534 delete dispatchEntry;
3535}
3536
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003537int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3538 std::scoped_lock _l(mLock);
3539 sp<Connection> connection = getConnectionLocked(connectionToken);
3540 if (connection == nullptr) {
3541 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3542 connectionToken.get(), events);
3543 return 0; // remove the callback
3544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003546 bool notify;
3547 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3548 if (!(events & ALOOPER_EVENT_INPUT)) {
3549 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3550 "events=0x%x",
3551 connection->getInputChannelName().c_str(), events);
3552 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003553 }
3554
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003555 nsecs_t currentTime = now();
3556 bool gotOne = false;
3557 status_t status = OK;
3558 for (;;) {
3559 Result<InputPublisher::ConsumerResponse> result =
3560 connection->inputPublisher.receiveConsumerResponse();
3561 if (!result.ok()) {
3562 status = result.error().code();
3563 break;
3564 }
3565
3566 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3567 const InputPublisher::Finished& finish =
3568 std::get<InputPublisher::Finished>(*result);
3569 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3570 finish.consumeTime);
3571 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003572 if (shouldReportMetricsForConnection(*connection)) {
3573 const InputPublisher::Timeline& timeline =
3574 std::get<InputPublisher::Timeline>(*result);
3575 mLatencyTracker
3576 .trackGraphicsLatency(timeline.inputEventId,
3577 connection->inputChannel->getConnectionToken(),
3578 std::move(timeline.graphicsTimeline));
3579 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003580 }
3581 gotOne = true;
3582 }
3583 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003584 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003585 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586 return 1;
3587 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588 }
3589
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003590 notify = status != DEAD_OBJECT || !connection->monitor;
3591 if (notify) {
3592 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3593 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3594 status);
3595 }
3596 } else {
3597 // Monitor channels are never explicitly unregistered.
3598 // We do it automatically when the remote endpoint is closed so don't warn about them.
3599 const bool stillHaveWindowHandle =
3600 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3601 notify = !connection->monitor && stillHaveWindowHandle;
3602 if (notify) {
3603 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3604 connection->getInputChannelName().c_str(), events);
3605 }
3606 }
3607
3608 // Remove the channel.
3609 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3610 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611}
3612
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003613void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003614 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003615 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003616 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 }
3618}
3619
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003620void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003621 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003622 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003623 for (const Monitor& monitor : monitors) {
3624 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003625 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003626 }
3627}
3628
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003630 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003631 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003632 if (connection == nullptr) {
3633 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003635
3636 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637}
3638
3639void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3640 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003641 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 return;
3643 }
3644
3645 nsecs_t currentTime = now();
3646
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003647 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003648 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003650 if (cancelationEvents.empty()) {
3651 return;
3652 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003653 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3654 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3655 "with reality: %s, mode=%d.",
3656 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3657 options.mode);
3658 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003659
Arthur Hungb3307ee2021-10-14 10:57:37 +00003660 std::string reason = std::string("reason=").append(options.reason);
3661 android_log_event_list(LOGTAG_INPUT_CANCEL)
3662 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3663
Svet Ganov5d3bc372020-01-26 23:11:07 -08003664 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003665 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003666 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3667 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003668 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003669 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003670 target.globalScaleFactor = windowInfo->globalScaleFactor;
3671 }
3672 target.inputChannel = connection->inputChannel;
3673 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3674
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003675 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003676 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003677 switch (cancelationEventEntry->type) {
3678 case EventEntry::Type::KEY: {
3679 logOutboundKeyDetails("cancel - ",
3680 static_cast<const KeyEntry&>(*cancelationEventEntry));
3681 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003682 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003683 case EventEntry::Type::MOTION: {
3684 logOutboundMotionDetails("cancel - ",
3685 static_cast<const MotionEntry&>(*cancelationEventEntry));
3686 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003688 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003689 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003690 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3691 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003692 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003693 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003694 break;
3695 }
3696 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003697 case EventEntry::Type::DEVICE_RESET:
3698 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003699 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003700 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003701 break;
3702 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003703 }
3704
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003705 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3706 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003707 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003708
3709 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710}
3711
Svet Ganov5d3bc372020-01-26 23:11:07 -08003712void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003713 const nsecs_t downTime, const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003714 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003715 return;
3716 }
3717
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003718 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003719 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003720
3721 if (downEvents.empty()) {
3722 return;
3723 }
3724
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003725 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003726 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3727 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003728 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003729
3730 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003731 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003732 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3733 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003734 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003735 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003736 target.globalScaleFactor = windowInfo->globalScaleFactor;
3737 }
3738 target.inputChannel = connection->inputChannel;
3739 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3740
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003741 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003742 switch (downEventEntry->type) {
3743 case EventEntry::Type::MOTION: {
3744 logOutboundMotionDetails("down - ",
3745 static_cast<const MotionEntry&>(*downEventEntry));
3746 break;
3747 }
3748
3749 case EventEntry::Type::KEY:
3750 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003751 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003752 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003753 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003754 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003755 case EventEntry::Type::SENSOR:
3756 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003757 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003758 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003759 break;
3760 }
3761 }
3762
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003763 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3764 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003765 }
3766
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003767 startDispatchCycleLocked(downTime, connection);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003768}
3769
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003770std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003771 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772 ALOG_ASSERT(pointerIds.value != 0);
3773
3774 uint32_t splitPointerIndexMap[MAX_POINTERS];
3775 PointerProperties splitPointerProperties[MAX_POINTERS];
3776 PointerCoords splitPointerCoords[MAX_POINTERS];
3777
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003778 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779 uint32_t splitPointerCount = 0;
3780
3781 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003782 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003784 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785 uint32_t pointerId = uint32_t(pointerProperties.id);
3786 if (pointerIds.hasBit(pointerId)) {
3787 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3788 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3789 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003790 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791 splitPointerCount += 1;
3792 }
3793 }
3794
3795 if (splitPointerCount != pointerIds.count()) {
3796 // This is bad. We are missing some of the pointers that we expected to deliver.
3797 // Most likely this indicates that we received an ACTION_MOVE events that has
3798 // different pointer ids than we expected based on the previous ACTION_DOWN
3799 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3800 // in this way.
3801 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003802 "we expected there to be %d pointers. This probably means we received "
3803 "a broken sequence of pointer ids from the input device.",
3804 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003805 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806 }
3807
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003808 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003809 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003810 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3811 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003812 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3813 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003814 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 uint32_t pointerId = uint32_t(pointerProperties.id);
3816 if (pointerIds.hasBit(pointerId)) {
3817 if (pointerIds.count() == 1) {
3818 // The first/last pointer went down/up.
3819 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003820 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003821 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3822 ? AMOTION_EVENT_ACTION_CANCEL
3823 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824 } else {
3825 // A secondary pointer went down/up.
3826 uint32_t splitPointerIndex = 0;
3827 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3828 splitPointerIndex += 1;
3829 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003830 action = maskedAction |
3831 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003832 }
3833 } else {
3834 // An unrelated pointer changed.
3835 action = AMOTION_EVENT_ACTION_MOVE;
3836 }
3837 }
3838
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003839 if (action == AMOTION_EVENT_ACTION_DOWN) {
3840 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3841 "Split motion event has mismatching downTime and eventTime for "
3842 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3843 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3844 }
3845
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003846 int32_t newId = mIdGenerator.nextId();
3847 if (ATRACE_ENABLED()) {
3848 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3849 ") to MotionEvent(id=0x%" PRIx32 ").",
3850 originalMotionEntry.id, newId);
3851 ATRACE_NAME(message.c_str());
3852 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003853 std::unique_ptr<MotionEntry> splitMotionEntry =
3854 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3855 originalMotionEntry.deviceId, originalMotionEntry.source,
3856 originalMotionEntry.displayId,
3857 originalMotionEntry.policyFlags, action,
3858 originalMotionEntry.actionButton,
3859 originalMotionEntry.flags, originalMotionEntry.metaState,
3860 originalMotionEntry.buttonState,
3861 originalMotionEntry.classification,
3862 originalMotionEntry.edgeFlags,
3863 originalMotionEntry.xPrecision,
3864 originalMotionEntry.yPrecision,
3865 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003866 originalMotionEntry.yCursorPosition, splitDownTime,
3867 splitPointerCount, splitPointerProperties,
3868 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003870 if (originalMotionEntry.injectionState) {
3871 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872 splitMotionEntry->injectionState->refCount += 1;
3873 }
3874
3875 return splitMotionEntry;
3876}
3877
3878void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003879 if (DEBUG_INBOUND_EVENT_DETAILS) {
3880 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003882
Antonio Kantekf16f2832021-09-28 04:39:20 +00003883 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003885 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003886
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003887 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3888 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3889 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003890 } // release lock
3891
3892 if (needWake) {
3893 mLooper->wake();
3894 }
3895}
3896
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003897/**
3898 * If one of the meta shortcuts is detected, process them here:
3899 * Meta + Backspace -> generate BACK
3900 * Meta + Enter -> generate HOME
3901 * This will potentially overwrite keyCode and metaState.
3902 */
3903void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003904 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003905 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3906 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3907 if (keyCode == AKEYCODE_DEL) {
3908 newKeyCode = AKEYCODE_BACK;
3909 } else if (keyCode == AKEYCODE_ENTER) {
3910 newKeyCode = AKEYCODE_HOME;
3911 }
3912 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003913 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003914 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003915 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003916 keyCode = newKeyCode;
3917 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3918 }
3919 } else if (action == AKEY_EVENT_ACTION_UP) {
3920 // In order to maintain a consistent stream of up and down events, check to see if the key
3921 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3922 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003923 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003924 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003925 auto replacementIt = mReplacedKeys.find(replacement);
3926 if (replacementIt != mReplacedKeys.end()) {
3927 keyCode = replacementIt->second;
3928 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003929 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3930 }
3931 }
3932}
3933
Michael Wrightd02c5b62014-02-10 15:10:22 -08003934void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003935 if (DEBUG_INBOUND_EVENT_DETAILS) {
3936 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3937 "policyFlags=0x%x, action=0x%x, "
3938 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3939 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3940 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3941 args->downTime);
3942 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943 if (!validateKeyEvent(args->action)) {
3944 return;
3945 }
3946
3947 uint32_t policyFlags = args->policyFlags;
3948 int32_t flags = args->flags;
3949 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003950 // InputDispatcher tracks and generates key repeats on behalf of
3951 // whatever notifies it, so repeatCount should always be set to 0
3952 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3954 policyFlags |= POLICY_FLAG_VIRTUAL;
3955 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3956 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 if (policyFlags & POLICY_FLAG_FUNCTION) {
3958 metaState |= AMETA_FUNCTION_ON;
3959 }
3960
3961 policyFlags |= POLICY_FLAG_TRUSTED;
3962
Michael Wright78f24442014-08-06 15:55:28 -07003963 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003964 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003965
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003967 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003968 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3969 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970
Michael Wright2b3c3302018-03-02 17:19:13 +00003971 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003973 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3974 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003975 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003976 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977
Antonio Kantekf16f2832021-09-28 04:39:20 +00003978 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003979 { // acquire lock
3980 mLock.lock();
3981
3982 if (shouldSendKeyToInputFilterLocked(args)) {
3983 mLock.unlock();
3984
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003985 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3987 return; // event was consumed by the filter
3988 }
3989
3990 mLock.lock();
3991 }
3992
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003993 std::unique_ptr<KeyEntry> newEntry =
3994 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3995 args->displayId, policyFlags, args->action, flags,
3996 keyCode, args->scanCode, metaState, repeatCount,
3997 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003999 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000 mLock.unlock();
4001 } // release lock
4002
4003 if (needWake) {
4004 mLooper->wake();
4005 }
4006}
4007
4008bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4009 return mInputFilterEnabled;
4010}
4011
4012void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004013 if (DEBUG_INBOUND_EVENT_DETAILS) {
4014 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4015 "displayId=%" PRId32 ", policyFlags=0x%x, "
4016 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
4017 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4018 "yCursorPosition=%f, downTime=%" PRId64,
4019 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
4020 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
4021 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
4022 args->xCursorPosition, args->yCursorPosition, args->downTime);
4023 for (uint32_t i = 0; i < args->pointerCount; i++) {
4024 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4025 "x=%f, y=%f, pressure=%f, size=%f, "
4026 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4027 "orientation=%f",
4028 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4029 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4030 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4031 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4032 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4033 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4034 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4035 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4036 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4037 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4038 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004039 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004040 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4041 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004042 return;
4043 }
4044
4045 uint32_t policyFlags = args->policyFlags;
4046 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004047
4048 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004049 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004050 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4051 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004052 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004053 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004054
Antonio Kantekf16f2832021-09-28 04:39:20 +00004055 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056 { // acquire lock
4057 mLock.lock();
4058
4059 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004060 ui::Transform displayTransform;
4061 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4062 displayTransform = it->second.transform;
4063 }
4064
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065 mLock.unlock();
4066
4067 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004068 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4069 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004070 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004071 displayTransform, args->xPrecision, args->yPrecision,
4072 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004073 args->downTime, args->eventTime, args->pointerCount,
4074 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075
4076 policyFlags |= POLICY_FLAG_FILTERED;
4077 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4078 return; // event was consumed by the filter
4079 }
4080
4081 mLock.lock();
4082 }
4083
4084 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004085 std::unique_ptr<MotionEntry> newEntry =
4086 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4087 args->source, args->displayId, policyFlags,
4088 args->action, args->actionButton, args->flags,
4089 args->metaState, args->buttonState,
4090 args->classification, args->edgeFlags,
4091 args->xPrecision, args->yPrecision,
4092 args->xCursorPosition, args->yCursorPosition,
4093 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004094 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004095
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004096 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4097 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4098 !mInputFilterEnabled) {
4099 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4100 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4101 }
4102
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004103 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004104 mLock.unlock();
4105 } // release lock
4106
4107 if (needWake) {
4108 mLooper->wake();
4109 }
4110}
4111
Chris Yef59a2f42020-10-16 12:55:26 -07004112void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004113 if (DEBUG_INBOUND_EVENT_DETAILS) {
4114 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4115 " sensorType=%s",
4116 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004117 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004118 }
Chris Yef59a2f42020-10-16 12:55:26 -07004119
Antonio Kantekf16f2832021-09-28 04:39:20 +00004120 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004121 { // acquire lock
4122 mLock.lock();
4123
4124 // Just enqueue a new sensor event.
4125 std::unique_ptr<SensorEntry> newEntry =
4126 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4127 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4128 args->sensorType, args->accuracy,
4129 args->accuracyChanged, args->values);
4130
4131 needWake = enqueueInboundEventLocked(std::move(newEntry));
4132 mLock.unlock();
4133 } // release lock
4134
4135 if (needWake) {
4136 mLooper->wake();
4137 }
4138}
4139
Chris Yefb552902021-02-03 17:18:37 -08004140void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004141 if (DEBUG_INBOUND_EVENT_DETAILS) {
4142 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4143 args->deviceId, args->isOn);
4144 }
Chris Yefb552902021-02-03 17:18:37 -08004145 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4146}
4147
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004149 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004150}
4151
4152void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004153 if (DEBUG_INBOUND_EVENT_DETAILS) {
4154 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4155 "switchMask=0x%08x",
4156 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158
4159 uint32_t policyFlags = args->policyFlags;
4160 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004161 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162}
4163
4164void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004165 if (DEBUG_INBOUND_EVENT_DETAILS) {
4166 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4167 args->deviceId);
4168 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169
Antonio Kantekf16f2832021-09-28 04:39:20 +00004170 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004172 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004174 std::unique_ptr<DeviceResetEntry> newEntry =
4175 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4176 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004177 } // release lock
4178
4179 if (needWake) {
4180 mLooper->wake();
4181 }
4182}
4183
Prabir Pradhan7e186182020-11-10 13:56:45 -08004184void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004185 if (DEBUG_INBOUND_EVENT_DETAILS) {
4186 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004187 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004188 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004189
Antonio Kantekf16f2832021-09-28 04:39:20 +00004190 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004191 { // acquire lock
4192 std::scoped_lock _l(mLock);
4193 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004194 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004195 needWake = enqueueInboundEventLocked(std::move(entry));
4196 } // release lock
4197
4198 if (needWake) {
4199 mLooper->wake();
4200 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004201}
4202
Prabir Pradhan5735a322022-04-11 17:23:34 +00004203InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4204 std::optional<int32_t> targetUid,
4205 InputEventInjectionSync syncMode,
4206 std::chrono::milliseconds timeout,
4207 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004208 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004209 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4210 "policyFlags=0x%08x",
4211 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4212 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004213 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004214 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004215
Prabir Pradhan5735a322022-04-11 17:23:34 +00004216 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004218 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004219 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4220 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4221 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4222 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4223 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004224 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004225 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004226 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004227 }
4228
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004229 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004230 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004231 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004232 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4233 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004234 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004235 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004236 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004237
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004238 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004239 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4240 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4241 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004242 int32_t keyCode = incomingKey.getKeyCode();
4243 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004244 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004245 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004246 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004247 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004248 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4249 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4250 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004252 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4253 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004254 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004255
4256 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4257 android::base::Timer t;
4258 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4259 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4260 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4261 std::to_string(t.duration().count()).c_str());
4262 }
4263 }
4264
4265 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004266 std::unique_ptr<KeyEntry> injectedEntry =
4267 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004268 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004269 incomingKey.getDisplayId(), policyFlags, action,
4270 flags, keyCode, incomingKey.getScanCode(), metaState,
4271 incomingKey.getRepeatCount(),
4272 incomingKey.getDownTime());
4273 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004274 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 }
4276
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004277 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004278 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004279 const int32_t action = motionEvent.getAction();
4280 const bool isPointerEvent =
4281 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4282 // If a pointer event has no displayId specified, inject it to the default display.
4283 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4284 ? ADISPLAY_ID_DEFAULT
4285 : event->getDisplayId();
4286 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004287 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004288 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004289 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004290 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004291 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004292 }
4293
4294 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004295 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004296 android::base::Timer t;
4297 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4298 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4299 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4300 std::to_string(t.duration().count()).c_str());
4301 }
4302 }
4303
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004304 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4305 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4306 }
4307
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004308 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004309 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4310 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004311 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004312 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4313 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004314 displayId, policyFlags, action, actionButton,
4315 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004316 motionEvent.getButtonState(),
4317 motionEvent.getClassification(),
4318 motionEvent.getEdgeFlags(),
4319 motionEvent.getXPrecision(),
4320 motionEvent.getYPrecision(),
4321 motionEvent.getRawXCursorPosition(),
4322 motionEvent.getRawYCursorPosition(),
4323 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004324 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004325 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004326 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004327 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004328 sampleEventTimes += 1;
4329 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004330 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004331 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4332 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004333 displayId, policyFlags, action, actionButton,
4334 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004335 motionEvent.getButtonState(),
4336 motionEvent.getClassification(),
4337 motionEvent.getEdgeFlags(),
4338 motionEvent.getXPrecision(),
4339 motionEvent.getYPrecision(),
4340 motionEvent.getRawXCursorPosition(),
4341 motionEvent.getRawYCursorPosition(),
4342 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004343 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004344 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004345 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4346 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004347 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004348 }
4349 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004352 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004353 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004354 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355 }
4356
Prabir Pradhan5735a322022-04-11 17:23:34 +00004357 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004358 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359 injectionState->injectionIsAsync = true;
4360 }
4361
4362 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004363 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364
4365 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004366 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004367 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004368 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 }
4370
4371 mLock.unlock();
4372
4373 if (needWake) {
4374 mLooper->wake();
4375 }
4376
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004377 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004379 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004381 if (syncMode == InputEventInjectionSync::NONE) {
4382 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 } else {
4384 for (;;) {
4385 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004386 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387 break;
4388 }
4389
4390 nsecs_t remainingTimeout = endTime - now();
4391 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004392 if (DEBUG_INJECTION) {
4393 ALOGD("injectInputEvent - Timed out waiting for injection result "
4394 "to become available.");
4395 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004396 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004397 break;
4398 }
4399
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004400 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401 }
4402
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004403 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4404 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004406 if (DEBUG_INJECTION) {
4407 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4408 injectionState->pendingForegroundDispatches);
4409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004410 nsecs_t remainingTimeout = endTime - now();
4411 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004412 if (DEBUG_INJECTION) {
4413 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4414 "dispatches to finish.");
4415 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004416 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417 break;
4418 }
4419
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004420 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421 }
4422 }
4423 }
4424
4425 injectionState->release();
4426 } // release lock
4427
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004428 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004429 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004430 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004431
4432 return injectionResult;
4433}
4434
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004435std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004436 std::array<uint8_t, 32> calculatedHmac;
4437 std::unique_ptr<VerifiedInputEvent> result;
4438 switch (event.getType()) {
4439 case AINPUT_EVENT_TYPE_KEY: {
4440 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4441 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4442 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004443 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004444 break;
4445 }
4446 case AINPUT_EVENT_TYPE_MOTION: {
4447 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4448 VerifiedMotionEvent verifiedMotionEvent =
4449 verifiedMotionEventFromMotionEvent(motionEvent);
4450 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004451 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004452 break;
4453 }
4454 default: {
4455 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4456 return nullptr;
4457 }
4458 }
4459 if (calculatedHmac == INVALID_HMAC) {
4460 return nullptr;
4461 }
4462 if (calculatedHmac != event.getHmac()) {
4463 return nullptr;
4464 }
4465 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004466}
4467
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004468void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004469 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004470 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004472 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004473 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004474 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004475
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004476 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004477 // Log the outcome since the injector did not wait for the injection result.
4478 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004479 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004480 ALOGV("Asynchronous input event injection succeeded.");
4481 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004482 case InputEventInjectionResult::TARGET_MISMATCH:
4483 ALOGV("Asynchronous input event injection target mismatch.");
4484 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004485 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004486 ALOGW("Asynchronous input event injection failed.");
4487 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004488 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004489 ALOGW("Asynchronous input event injection timed out.");
4490 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004491 case InputEventInjectionResult::PENDING:
4492 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4493 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004494 }
4495 }
4496
4497 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004498 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499 }
4500}
4501
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004502void InputDispatcher::transformMotionEntryForInjectionLocked(
4503 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004504 // Input injection works in the logical display coordinate space, but the input pipeline works
4505 // display space, so we need to transform the injected events accordingly.
4506 const auto it = mDisplayInfos.find(entry.displayId);
4507 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004508 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004509
4510 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004511 entry.pointerCoords[i] =
4512 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4513 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004514 }
4515}
4516
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004517void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4518 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519 if (injectionState) {
4520 injectionState->pendingForegroundDispatches += 1;
4521 }
4522}
4523
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004524void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4525 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526 if (injectionState) {
4527 injectionState->pendingForegroundDispatches -= 1;
4528
4529 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004530 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004531 }
4532 }
4533}
4534
chaviw98318de2021-05-19 16:45:23 -05004535const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004536 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004537 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004538 auto it = mWindowHandlesByDisplay.find(displayId);
4539 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004540}
4541
chaviw98318de2021-05-19 16:45:23 -05004542sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004543 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004544 if (windowHandleToken == nullptr) {
4545 return nullptr;
4546 }
4547
Arthur Hungb92218b2018-08-14 12:00:21 +08004548 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004549 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4550 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004551 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004552 return windowHandle;
4553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554 }
4555 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004556 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557}
4558
chaviw98318de2021-05-19 16:45:23 -05004559sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4560 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004561 if (windowHandleToken == nullptr) {
4562 return nullptr;
4563 }
4564
chaviw98318de2021-05-19 16:45:23 -05004565 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004566 if (windowHandle->getToken() == windowHandleToken) {
4567 return windowHandle;
4568 }
4569 }
4570 return nullptr;
4571}
4572
chaviw98318de2021-05-19 16:45:23 -05004573sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4574 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004575 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004576 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4577 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004578 if (handle->getId() == windowHandle->getId() &&
4579 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004580 if (windowHandle->getInfo()->displayId != it.first) {
4581 ALOGE("Found window %s in display %" PRId32
4582 ", but it should belong to display %" PRId32,
4583 windowHandle->getName().c_str(), it.first,
4584 windowHandle->getInfo()->displayId);
4585 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004586 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004587 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588 }
4589 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004590 return nullptr;
4591}
4592
chaviw98318de2021-05-19 16:45:23 -05004593sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004594 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4595 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004596}
4597
chaviw98318de2021-05-19 16:45:23 -05004598bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004599 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4600 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004601 windowHandle.getInfo()->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004602 if (connection != nullptr && noInputChannel) {
4603 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4604 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4605 return false;
4606 }
4607
4608 if (connection == nullptr) {
4609 if (!noInputChannel) {
4610 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4611 }
4612 return false;
4613 }
4614 if (!connection->responsive) {
4615 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4616 return false;
4617 }
4618 return true;
4619}
4620
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004621std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4622 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004623 auto connectionIt = mConnectionsByToken.find(token);
4624 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004625 return nullptr;
4626 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004627 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004628}
4629
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004630void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004631 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4632 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004633 // Remove all handles on a display if there are no windows left.
4634 mWindowHandlesByDisplay.erase(displayId);
4635 return;
4636 }
4637
4638 // Since we compare the pointer of input window handles across window updates, we need
4639 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004640 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4641 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4642 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004643 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004644 }
4645
chaviw98318de2021-05-19 16:45:23 -05004646 std::vector<sp<WindowInfoHandle>> newHandles;
4647 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004648 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004649 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004650 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004651 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004652 const bool canReceiveInput =
4653 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4654 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004655 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004656 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004657 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004658 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004659 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004660 }
4661
4662 if (info->displayId != displayId) {
4663 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4664 handle->getName().c_str(), displayId, info->displayId);
4665 continue;
4666 }
4667
Robert Carredd13602020-04-13 17:24:34 -07004668 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4669 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004670 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004671 oldHandle->updateFrom(handle);
4672 newHandles.push_back(oldHandle);
4673 } else {
4674 newHandles.push_back(handle);
4675 }
4676 }
4677
4678 // Insert or replace
4679 mWindowHandlesByDisplay[displayId] = newHandles;
4680}
4681
Arthur Hung72d8dc32020-03-28 00:48:39 +00004682void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004683 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004684 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004685 { // acquire lock
4686 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004687 for (const auto& [displayId, handles] : handlesPerDisplay) {
4688 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004689 }
4690 }
4691 // Wake up poll loop since it may need to make new input dispatching choices.
4692 mLooper->wake();
4693}
4694
Arthur Hungb92218b2018-08-14 12:00:21 +08004695/**
4696 * Called from InputManagerService, update window handle list by displayId that can receive input.
4697 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4698 * If set an empty list, remove all handles from the specific display.
4699 * For focused handle, check if need to change and send a cancel event to previous one.
4700 * For removed handle, check if need to send a cancel event if already in touch.
4701 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004702void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004703 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004704 if (DEBUG_FOCUS) {
4705 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004706 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004707 windowList += iwh->getName() + " ";
4708 }
4709 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4710 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711
Prabir Pradhand65552b2021-10-07 11:23:50 -07004712 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004713 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004714 const WindowInfo& info = *window->getInfo();
4715
4716 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004717 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004718 if (noInputWindow && window->getToken() != nullptr) {
4719 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4720 window->getName().c_str());
4721 window->releaseChannel();
4722 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004723
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004724 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004725 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4726 !info.inputConfig.test(
4727 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004728 "%s has feature SPY, but is not a trusted overlay.",
4729 window->getName().c_str());
4730
Prabir Pradhand65552b2021-10-07 11:23:50 -07004731 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004732 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4733 !info.inputConfig.test(
4734 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004735 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4736 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004737 }
4738
Arthur Hung72d8dc32020-03-28 00:48:39 +00004739 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004740 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004742 // Save the old windows' orientation by ID before it gets updated.
4743 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004744 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004745 oldWindowOrientations.emplace(handle->getId(),
4746 handle->getInfo()->transform.getOrientation());
4747 }
4748
chaviw98318de2021-05-19 16:45:23 -05004749 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004750
chaviw98318de2021-05-19 16:45:23 -05004751 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004752 if (mLastHoverWindowHandle &&
4753 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4754 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004755 mLastHoverWindowHandle = nullptr;
4756 }
4757
Vishnu Nairc519ff72021-01-21 08:23:08 -08004758 std::optional<FocusResolver::FocusChanges> changes =
4759 mFocusResolver.setInputWindows(displayId, windowHandles);
4760 if (changes) {
4761 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004762 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004763
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004764 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4765 mTouchStatesByDisplay.find(displayId);
4766 if (stateIt != mTouchStatesByDisplay.end()) {
4767 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004768 for (size_t i = 0; i < state.windows.size();) {
4769 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004770 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004771 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004772 ALOGD("Touched window was removed: %s in display %" PRId32,
4773 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004774 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004775 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004776 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4777 if (touchedInputChannel != nullptr) {
4778 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4779 "touched window was removed");
4780 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004781 // Since we are about to drop the touch, cancel the events for the wallpaper as
4782 // well.
4783 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004784 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4785 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004786 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4787 if (wallpaper != nullptr) {
4788 sp<Connection> wallpaperConnection =
4789 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004790 if (wallpaperConnection != nullptr) {
4791 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4792 options);
4793 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004794 }
4795 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004796 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004797 state.windows.erase(state.windows.begin() + i);
4798 } else {
4799 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004800 }
4801 }
arthurhungb89ccb02020-12-30 16:19:01 +08004802
arthurhung6d4bed92021-03-17 11:59:33 +08004803 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004804 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004805 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004806 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004807 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004808 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4809 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004810 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004811 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004812 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004813
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004814 // Determine if the orientation of any of the input windows have changed, and cancel all
4815 // pointer events if necessary.
4816 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4817 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4818 if (newWindowHandle != nullptr &&
4819 newWindowHandle->getInfo()->transform.getOrientation() !=
4820 oldWindowOrientations[oldWindowHandle->getId()]) {
4821 std::shared_ptr<InputChannel> inputChannel =
4822 getInputChannelLocked(newWindowHandle->getToken());
4823 if (inputChannel != nullptr) {
4824 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4825 "touched window's orientation changed");
4826 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004827 }
4828 }
4829 }
4830
Arthur Hung72d8dc32020-03-28 00:48:39 +00004831 // Release information for windows that are no longer present.
4832 // This ensures that unused input channels are released promptly.
4833 // Otherwise, they might stick around until the window handle is destroyed
4834 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004835 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004836 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004837 if (DEBUG_FOCUS) {
4838 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004839 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004840 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004841 }
chaviw291d88a2019-02-14 10:33:58 -08004842 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004843}
4844
4845void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004846 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004847 if (DEBUG_FOCUS) {
4848 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4849 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4850 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004851 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004852 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004853 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004854 } // release lock
4855
4856 // Wake up poll loop since it may need to make new input dispatching choices.
4857 mLooper->wake();
4858}
4859
Vishnu Nair599f1412021-06-21 10:39:58 -07004860void InputDispatcher::setFocusedApplicationLocked(
4861 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4862 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4863 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4864
4865 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4866 return; // This application is already focused. No need to wake up or change anything.
4867 }
4868
4869 // Set the new application handle.
4870 if (inputApplicationHandle != nullptr) {
4871 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4872 } else {
4873 mFocusedApplicationHandlesByDisplay.erase(displayId);
4874 }
4875
4876 // No matter what the old focused application was, stop waiting on it because it is
4877 // no longer focused.
4878 resetNoFocusedWindowTimeoutLocked();
4879}
4880
Tiger Huang721e26f2018-07-24 22:26:19 +08004881/**
4882 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4883 * the display not specified.
4884 *
4885 * We track any unreleased events for each window. If a window loses the ability to receive the
4886 * released event, we will send a cancel event to it. So when the focused display is changed, we
4887 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4888 * display. The display-specified events won't be affected.
4889 */
4890void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004891 if (DEBUG_FOCUS) {
4892 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4893 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004894 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004895 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004896
4897 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004898 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004899 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004900 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004901 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004902 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004903 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004904 CancelationOptions
4905 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4906 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004907 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004908 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4909 }
4910 }
4911 mFocusedDisplayId = displayId;
4912
Chris Ye3c2d6f52020-08-09 10:39:48 -07004913 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004914 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004915 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004916
Vishnu Nairad321cd2020-08-20 16:40:21 -07004917 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004918 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004919 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004920 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004921 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004922 }
4923 }
4924 }
4925
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004926 if (DEBUG_FOCUS) {
4927 logDispatchStateLocked();
4928 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004929 } // release lock
4930
4931 // Wake up poll loop since it may need to make new input dispatching choices.
4932 mLooper->wake();
4933}
4934
Michael Wrightd02c5b62014-02-10 15:10:22 -08004935void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004936 if (DEBUG_FOCUS) {
4937 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4938 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004939
4940 bool changed;
4941 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004942 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004943
4944 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4945 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004946 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004947 }
4948
4949 if (mDispatchEnabled && !enabled) {
4950 resetAndDropEverythingLocked("dispatcher is being disabled");
4951 }
4952
4953 mDispatchEnabled = enabled;
4954 mDispatchFrozen = frozen;
4955 changed = true;
4956 } else {
4957 changed = false;
4958 }
4959
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004960 if (DEBUG_FOCUS) {
4961 logDispatchStateLocked();
4962 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004963 } // release lock
4964
4965 if (changed) {
4966 // Wake up poll loop since it may need to make new input dispatching choices.
4967 mLooper->wake();
4968 }
4969}
4970
4971void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004972 if (DEBUG_FOCUS) {
4973 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004975
4976 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004977 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004978
4979 if (mInputFilterEnabled == enabled) {
4980 return;
4981 }
4982
4983 mInputFilterEnabled = enabled;
4984 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4985 } // release lock
4986
4987 // Wake up poll loop since there might be work to do to drop everything.
4988 mLooper->wake();
4989}
4990
Antonio Kanteka042c022022-07-06 16:51:07 -07004991bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
4992 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00004993 bool needWake = false;
4994 {
4995 std::scoped_lock lock(mLock);
4996 if (mInTouchMode == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004997 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00004998 }
4999 if (DEBUG_TOUCH_MODE) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005000 ALOGD("Request to change touch mode from %s to %s (calling pid=%d, uid=%d, "
Antonio Kanteka042c022022-07-06 16:51:07 -07005001 "hasPermission=%s, target displayId=%d, perDisplayTouchModeEnabled=%s)",
5002 toString(mInTouchMode), toString(inTouchMode), pid, uid, toString(hasPermission),
5003 displayId, toString(kPerDisplayTouchModeEnabled));
Antonio Kantekea47acb2021-12-23 12:41:25 -08005004 }
5005 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005006 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5007 !recentWindowsAreOwnedByLocked(pid, uid)) {
5008 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5009 "window nor none of the previously interacted window",
5010 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005011 return false;
5012 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005013 }
5014
Antonio Kanteka042c022022-07-06 16:51:07 -07005015 // TODO(b/198499018): Store touch mode per display (kPerDisplayTouchModeEnabled)
Antonio Kantekf16f2832021-09-28 04:39:20 +00005016 mInTouchMode = inTouchMode;
5017
Antonio Kantekf16f2832021-09-28 04:39:20 +00005018 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
5019 needWake = enqueueInboundEventLocked(std::move(entry));
5020 } // release lock
5021
5022 if (needWake) {
5023 mLooper->wake();
5024 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005025 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005026}
5027
Antonio Kantek48710e42022-03-24 14:19:30 -07005028bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5029 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5030 if (focusedToken == nullptr) {
5031 return false;
5032 }
5033 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5034 return isWindowOwnedBy(windowHandle, pid, uid);
5035}
5036
5037bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5038 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5039 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5040 const sp<WindowInfoHandle> windowHandle =
5041 getWindowHandleLocked(connectionToken);
5042 return isWindowOwnedBy(windowHandle, pid, uid);
5043 }) != mInteractionConnectionTokens.end();
5044}
5045
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005046void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5047 if (opacity < 0 || opacity > 1) {
5048 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5049 return;
5050 }
5051
5052 std::scoped_lock lock(mLock);
5053 mMaximumObscuringOpacityForTouch = opacity;
5054}
5055
Arthur Hungabbb9d82021-09-01 14:52:30 +00005056std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
5057 const sp<IBinder>& token) {
5058 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5059 for (TouchedWindow& w : state.windows) {
5060 if (w.windowHandle->getToken() == token) {
5061 return std::make_pair(&state, &w);
5062 }
5063 }
5064 }
5065 return std::make_pair(nullptr, nullptr);
5066}
5067
arthurhungb89ccb02020-12-30 16:19:01 +08005068bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5069 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005070 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005071 if (DEBUG_FOCUS) {
5072 ALOGD("Trivial transfer to same window.");
5073 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005074 return true;
5075 }
5076
Michael Wrightd02c5b62014-02-10 15:10:22 -08005077 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005078 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005079
Arthur Hungabbb9d82021-09-01 14:52:30 +00005080 // Find the target touch state and touched window by fromToken.
5081 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5082 if (state == nullptr || touchedWindow == nullptr) {
5083 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005084 return false;
5085 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005086
5087 const int32_t displayId = state->displayId;
5088 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5089 if (toWindowHandle == nullptr) {
5090 ALOGW("Cannot transfer focus because to window not found.");
5091 return false;
5092 }
5093
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005094 if (DEBUG_FOCUS) {
5095 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005096 touchedWindow->windowHandle->getName().c_str(),
5097 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005098 }
5099
Arthur Hungabbb9d82021-09-01 14:52:30 +00005100 // Erase old window.
5101 int32_t oldTargetFlags = touchedWindow->targetFlags;
5102 BitSet32 pointerIds = touchedWindow->pointerIds;
5103 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005104
Arthur Hungabbb9d82021-09-01 14:52:30 +00005105 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005106 nsecs_t downTimeInTarget = now();
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005107 int32_t newTargetFlags =
5108 oldTargetFlags & (InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
5109 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
5110 newTargetFlags |= InputTarget::FLAG_FOREGROUND;
5111 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005112 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005113
Arthur Hungabbb9d82021-09-01 14:52:30 +00005114 // Store the dragging window.
5115 if (isDragDrop) {
Arthur Hung54745652022-04-20 07:17:41 +00005116 if (pointerIds.count() > 1) {
5117 ALOGW("The drag and drop cannot be started when there is more than 1 pointer on the"
5118 " window.");
5119 return false;
5120 }
5121 // If the window didn't not support split or the source is mouse, the pointerIds count
5122 // would be 0, so we have to track the pointer 0.
5123 const int32_t id = pointerIds.count() == 0 ? 0 : pointerIds.firstMarkedBit();
5124 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005125 }
5126
Arthur Hungabbb9d82021-09-01 14:52:30 +00005127 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005128 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5129 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005130 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005131 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005132 CancelationOptions
5133 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5134 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005135 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005136 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005137 }
5138
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005139 if (DEBUG_FOCUS) {
5140 logDispatchStateLocked();
5141 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005142 } // release lock
5143
5144 // Wake up poll loop since it may need to make new input dispatching choices.
5145 mLooper->wake();
5146 return true;
5147}
5148
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005149/**
5150 * Get the touched foreground window on the given display.
5151 * Return null if there are no windows touched on that display, or if more than one foreground
5152 * window is being touched.
5153 */
5154sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5155 auto stateIt = mTouchStatesByDisplay.find(displayId);
5156 if (stateIt == mTouchStatesByDisplay.end()) {
5157 ALOGI("No touch state on display %" PRId32, displayId);
5158 return nullptr;
5159 }
5160
5161 const TouchState& state = stateIt->second;
5162 sp<WindowInfoHandle> touchedForegroundWindow;
5163 // If multiple foreground windows are touched, return nullptr
5164 for (const TouchedWindow& window : state.windows) {
5165 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5166 if (touchedForegroundWindow != nullptr) {
5167 ALOGI("Two or more foreground windows: %s and %s",
5168 touchedForegroundWindow->getName().c_str(),
5169 window.windowHandle->getName().c_str());
5170 return nullptr;
5171 }
5172 touchedForegroundWindow = window.windowHandle;
5173 }
5174 }
5175 return touchedForegroundWindow;
5176}
5177
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005178// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005179bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005180 sp<IBinder> fromToken;
5181 { // acquire lock
5182 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005183 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005184 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005185 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5186 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005187 return false;
5188 }
5189
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005190 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5191 if (from == nullptr) {
5192 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5193 return false;
5194 }
5195
5196 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005197 } // release lock
5198
5199 return transferTouchFocus(fromToken, destChannelToken);
5200}
5201
Michael Wrightd02c5b62014-02-10 15:10:22 -08005202void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005203 if (DEBUG_FOCUS) {
5204 ALOGD("Resetting and dropping all events (%s).", reason);
5205 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005206
5207 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5208 synthesizeCancelationEventsForAllConnectionsLocked(options);
5209
5210 resetKeyRepeatLocked();
5211 releasePendingEventLocked();
5212 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005213 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005214
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005215 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005216 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005217 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005218 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005219}
5220
5221void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005222 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005223 dumpDispatchStateLocked(dump);
5224
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005225 std::istringstream stream(dump);
5226 std::string line;
5227
5228 while (std::getline(stream, line, '\n')) {
5229 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005230 }
5231}
5232
Prabir Pradhan99987712020-11-10 18:43:05 -08005233std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5234 std::string dump;
5235
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005236 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5237 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005238
5239 std::string windowName = "None";
5240 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005241 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005242 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5243 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5244 : "token has capture without window";
5245 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005246 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005247
5248 return dump;
5249}
5250
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005251void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005252 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5253 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5254 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005255 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005256
Tiger Huang721e26f2018-07-24 22:26:19 +08005257 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5258 dump += StringPrintf(INDENT "FocusedApplications:\n");
5259 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5260 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005261 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005262 const std::chrono::duration timeout =
5263 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005264 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005265 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005266 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005267 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005268 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005269 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005270 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005271
Vishnu Nairc519ff72021-01-21 08:23:08 -08005272 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005273 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005274
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005275 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005276 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005277 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5278 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005279 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005280 state.displayId, toString(state.down), toString(state.split),
5281 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005282 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005283 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005284 for (size_t i = 0; i < state.windows.size(); i++) {
5285 const TouchedWindow& touchedWindow = state.windows[i];
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005286 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, "
5287 "targetFlags=0x%x, firstDownTimeInTarget=%" PRId64
5288 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005289 i, touchedWindow.windowHandle->getName().c_str(),
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005290 touchedWindow.pointerIds.value, touchedWindow.targetFlags,
5291 ns2ms(touchedWindow.firstDownTimeInTarget.value_or(0)));
Jeff Brownf086ddb2014-02-11 14:28:48 -08005292 }
5293 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005294 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005295 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005296 }
5297 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005298 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005299 }
5300
arthurhung6d4bed92021-03-17 11:59:33 +08005301 if (mDragState) {
5302 dump += StringPrintf(INDENT "DragState:\n");
5303 mDragState->dump(dump, INDENT2);
5304 }
5305
Arthur Hungb92218b2018-08-14 12:00:21 +08005306 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005307 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5308 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5309 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5310 const auto& displayInfo = it->second;
5311 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5312 displayInfo.logicalHeight);
5313 displayInfo.transform.dump(dump, "transform", INDENT4);
5314 } else {
5315 dump += INDENT2 "No DisplayInfo found!\n";
5316 }
5317
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005318 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005319 dump += INDENT2 "Windows:\n";
5320 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005321 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5322 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005324 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005325 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005326 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005327 "applicationInfo.name=%s, "
5328 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005329 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005330 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005331 windowInfo->displayId,
5332 windowInfo->inputConfig.string().c_str(),
5333 windowInfo->alpha, windowInfo->frameLeft,
5334 windowInfo->frameTop, windowInfo->frameRight,
5335 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005336 windowInfo->applicationInfo.name.c_str(),
5337 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005338 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005339 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005340 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005341 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005342 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005343 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005344 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005345 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005346 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005347 }
5348 } else {
5349 dump += INDENT2 "Windows: <none>\n";
5350 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351 }
5352 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005353 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005354 }
5355
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005356 if (!mGlobalMonitorsByDisplay.empty()) {
5357 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5358 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005359 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005361 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005362 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005363 }
5364
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005365 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005366
5367 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005368 if (!mRecentQueue.empty()) {
5369 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005370 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005371 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005372 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005373 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005374 }
5375 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005376 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005377 }
5378
5379 // Dump event currently being dispatched.
5380 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005381 dump += INDENT "PendingEvent:\n";
5382 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005383 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005384 dump += StringPrintf(", age=%" PRId64 "ms\n",
5385 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005386 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005387 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005388 }
5389
5390 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005391 if (!mInboundQueue.empty()) {
5392 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005393 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005394 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005395 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005396 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005397 }
5398 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005399 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005400 }
5401
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005402 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005403 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005404 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5405 const KeyReplacement& replacement = pair.first;
5406 int32_t newKeyCode = pair.second;
5407 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005408 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005409 }
5410 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005411 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005412 }
5413
Prabir Pradhancef936d2021-07-21 16:17:52 +00005414 if (!mCommandQueue.empty()) {
5415 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5416 } else {
5417 dump += INDENT "CommandQueue: <empty>\n";
5418 }
5419
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005420 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005421 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005422 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005423 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005424 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005425 connection->inputChannel->getFd().get(),
5426 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005427 connection->getWindowName().c_str(),
5428 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005429 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005430
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005431 if (!connection->outboundQueue.empty()) {
5432 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5433 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005434 dump += dumpQueue(connection->outboundQueue, currentTime);
5435
Michael Wrightd02c5b62014-02-10 15:10:22 -08005436 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005437 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005438 }
5439
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005440 if (!connection->waitQueue.empty()) {
5441 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5442 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005443 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005444 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005445 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005446 }
5447 }
5448 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005449 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005450 }
5451
5452 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005453 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5454 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005455 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005456 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005457 }
5458
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005459 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005460 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5461 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5462 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005463 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005464 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005465}
5466
Michael Wright3dd60e22019-03-27 22:06:44 +00005467void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5468 const size_t numMonitors = monitors.size();
5469 for (size_t i = 0; i < numMonitors; i++) {
5470 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005471 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005472 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5473 dump += "\n";
5474 }
5475}
5476
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005477class LooperEventCallback : public LooperCallback {
5478public:
5479 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5480 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5481
5482private:
5483 std::function<int(int events)> mCallback;
5484};
5485
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005486Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005487 if (DEBUG_CHANNEL_CREATION) {
5488 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5489 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005491 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005492 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005493 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005494
5495 if (result) {
5496 return base::Error(result) << "Failed to open input channel pair with name " << name;
5497 }
5498
Michael Wrightd02c5b62014-02-10 15:10:22 -08005499 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005500 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005501 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005502 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005503 sp<Connection> connection =
5504 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005505
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005506 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5507 ALOGE("Created a new connection, but the token %p is already known", token.get());
5508 }
5509 mConnectionsByToken.emplace(token, connection);
5510
5511 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5512 this, std::placeholders::_1, token);
5513
5514 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005515 } // release lock
5516
5517 // Wake the looper because some connections have changed.
5518 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005519 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005520}
5521
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005522Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005523 const std::string& name,
5524 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005525 std::shared_ptr<InputChannel> serverChannel;
5526 std::unique_ptr<InputChannel> clientChannel;
5527 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5528 if (result) {
5529 return base::Error(result) << "Failed to open input channel pair with name " << name;
5530 }
5531
Michael Wright3dd60e22019-03-27 22:06:44 +00005532 { // acquire lock
5533 std::scoped_lock _l(mLock);
5534
5535 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005536 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5537 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005538 }
5539
Garfield Tan15601662020-09-22 15:32:38 -07005540 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005541 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005542 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005543
5544 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5545 ALOGE("Created a new connection, but the token %p is already known", token.get());
5546 }
5547 mConnectionsByToken.emplace(token, connection);
5548 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5549 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005550
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005551 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005552
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005553 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005554 }
Garfield Tan15601662020-09-22 15:32:38 -07005555
Michael Wright3dd60e22019-03-27 22:06:44 +00005556 // Wake the looper because some connections have changed.
5557 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005558 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005559}
5560
Garfield Tan15601662020-09-22 15:32:38 -07005561status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005563 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005564
Garfield Tan15601662020-09-22 15:32:38 -07005565 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005566 if (status) {
5567 return status;
5568 }
5569 } // release lock
5570
5571 // Wake the poll loop because removing the connection may have changed the current
5572 // synchronization state.
5573 mLooper->wake();
5574 return OK;
5575}
5576
Garfield Tan15601662020-09-22 15:32:38 -07005577status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5578 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005579 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005580 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005581 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005582 return BAD_VALUE;
5583 }
5584
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005585 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005586
Michael Wrightd02c5b62014-02-10 15:10:22 -08005587 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005588 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005589 }
5590
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005591 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005592
5593 nsecs_t currentTime = now();
5594 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5595
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005596 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005597 return OK;
5598}
5599
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005600void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005601 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5602 auto& [displayId, monitors] = *it;
5603 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5604 return monitor.inputChannel->getConnectionToken() == connectionToken;
5605 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005606
Michael Wright3dd60e22019-03-27 22:06:44 +00005607 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005608 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005609 } else {
5610 ++it;
5611 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005612 }
5613}
5614
Michael Wright3dd60e22019-03-27 22:06:44 +00005615status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005616 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005617 return pilferPointersLocked(token);
5618}
Michael Wright3dd60e22019-03-27 22:06:44 +00005619
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005620status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005621 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5622 if (!requestingChannel) {
5623 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5624 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005625 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005626
5627 auto [statePtr, windowPtr] = findTouchStateAndWindowLocked(token);
5628 if (statePtr == nullptr || windowPtr == nullptr || !statePtr->down) {
5629 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5630 " Ignoring.");
5631 return BAD_VALUE;
5632 }
5633
5634 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005635 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005636 // Send cancel events to all the input channels we're stealing from.
5637 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5638 "input channel stole pointer stream");
5639 options.deviceId = state.deviceId;
5640 options.displayId = state.displayId;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005641 if (state.split) {
5642 // If split pointers then selectively cancel pointers otherwise cancel all pointers
5643 options.pointerIds = window.pointerIds;
5644 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005645 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005646 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005647 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005648 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005649 if (channel != nullptr && channel->getConnectionToken() != token) {
5650 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5651 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5652 canceledWindows += channel->getName();
5653 }
5654 }
5655 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5656 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5657 canceledWindows.c_str());
5658
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005659 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005660 // This only blocks relevant pointers to be sent to other windows
5661 window.isPilferingPointers = true;
5662
5663 if (state.split) {
5664 state.cancelPointersForWindowsExcept(window.pointerIds, token);
5665 } else {
5666 state.filterWindowsExcept(token);
5667 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005668 return OK;
5669}
5670
Prabir Pradhan99987712020-11-10 18:43:05 -08005671void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5672 { // acquire lock
5673 std::scoped_lock _l(mLock);
5674 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005675 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005676 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5677 windowHandle != nullptr ? windowHandle->getName().c_str()
5678 : "token without window");
5679 }
5680
Vishnu Nairc519ff72021-01-21 08:23:08 -08005681 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005682 if (focusedToken != windowToken) {
5683 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5684 enabled ? "enable" : "disable");
5685 return;
5686 }
5687
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005688 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005689 ALOGW("Ignoring request to %s Pointer Capture: "
5690 "window has %s requested pointer capture.",
5691 enabled ? "enable" : "disable", enabled ? "already" : "not");
5692 return;
5693 }
5694
Christine Franksb768bb42021-11-29 12:11:31 -08005695 if (enabled) {
5696 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5697 mIneligibleDisplaysForPointerCapture.end(),
5698 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5699 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5700 return;
5701 }
5702 }
5703
Prabir Pradhan99987712020-11-10 18:43:05 -08005704 setPointerCaptureLocked(enabled);
5705 } // release lock
5706
5707 // Wake the thread to process command entries.
5708 mLooper->wake();
5709}
5710
Christine Franksb768bb42021-11-29 12:11:31 -08005711void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5712 { // acquire lock
5713 std::scoped_lock _l(mLock);
5714 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5715 if (!isEligible) {
5716 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5717 }
5718 } // release lock
5719}
5720
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005721std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5722 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005723 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005724 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005725 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005726 }
5727 }
5728 }
5729 return std::nullopt;
5730}
5731
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005732sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005733 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005734 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005735 }
5736
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005737 for (const auto& [token, connection] : mConnectionsByToken) {
5738 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005739 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005740 }
5741 }
Robert Carr4e670e52018-08-15 13:26:12 -07005742
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005743 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005744}
5745
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005746std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5747 sp<Connection> connection = getConnectionLocked(connectionToken);
5748 if (connection == nullptr) {
5749 return "<nullptr>";
5750 }
5751 return connection->getInputChannelName();
5752}
5753
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005754void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005755 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005756 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005757}
5758
Prabir Pradhancef936d2021-07-21 16:17:52 +00005759void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5760 const sp<Connection>& connection, uint32_t seq,
5761 bool handled, nsecs_t consumeTime) {
5762 // Handle post-event policy actions.
5763 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5764 if (dispatchEntryIt == connection->waitQueue.end()) {
5765 return;
5766 }
5767 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5768 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5769 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5770 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5771 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5772 }
5773 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5774 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5775 connection->inputChannel->getConnectionToken(),
5776 dispatchEntry->deliveryTime, consumeTime, finishTime);
5777 }
5778
5779 bool restartEvent;
5780 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5781 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5782 restartEvent =
5783 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5784 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5785 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5786 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5787 handled);
5788 } else {
5789 restartEvent = false;
5790 }
5791
5792 // Dequeue the event and start the next cycle.
5793 // Because the lock might have been released, it is possible that the
5794 // contents of the wait queue to have been drained, so we need to double-check
5795 // a few things.
5796 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5797 if (dispatchEntryIt != connection->waitQueue.end()) {
5798 dispatchEntry = *dispatchEntryIt;
5799 connection->waitQueue.erase(dispatchEntryIt);
5800 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5801 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5802 if (!connection->responsive) {
5803 connection->responsive = isConnectionResponsive(*connection);
5804 if (connection->responsive) {
5805 // The connection was unresponsive, and now it's responsive.
5806 processConnectionResponsiveLocked(*connection);
5807 }
5808 }
5809 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005810 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005811 connection->outboundQueue.push_front(dispatchEntry);
5812 traceOutboundQueueLength(*connection);
5813 } else {
5814 releaseDispatchEntry(dispatchEntry);
5815 }
5816 }
5817
5818 // Start the next dispatch cycle for this connection.
5819 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005820}
5821
Prabir Pradhancef936d2021-07-21 16:17:52 +00005822void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5823 const sp<IBinder>& newToken) {
5824 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5825 scoped_unlock unlock(mLock);
5826 mPolicy->notifyFocusChanged(oldToken, newToken);
5827 };
5828 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005829}
5830
Prabir Pradhancef936d2021-07-21 16:17:52 +00005831void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5832 auto command = [this, token, x, y]() REQUIRES(mLock) {
5833 scoped_unlock unlock(mLock);
5834 mPolicy->notifyDropWindow(token, x, y);
5835 };
5836 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005837}
5838
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005839void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5840 if (connection == nullptr) {
5841 LOG_ALWAYS_FATAL("Caller must check for nullness");
5842 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005843 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5844 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005845 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005846 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005847 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005848 return;
5849 }
5850 /**
5851 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5852 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5853 * has changed. This could cause newer entries to time out before the already dispatched
5854 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5855 * processes the events linearly. So providing information about the oldest entry seems to be
5856 * most useful.
5857 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005858 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005859 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5860 std::string reason =
5861 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005862 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005863 ns2ms(currentWait),
5864 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005865 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005866 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005867
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005868 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5869
5870 // Stop waking up for events on this connection, it is already unresponsive
5871 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005872}
5873
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005874void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5875 std::string reason =
5876 StringPrintf("%s does not have a focused window", application->getName().c_str());
5877 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005878
Prabir Pradhancef936d2021-07-21 16:17:52 +00005879 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5880 scoped_unlock unlock(mLock);
5881 mPolicy->notifyNoFocusedWindowAnr(application);
5882 };
5883 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005884}
5885
chaviw98318de2021-05-19 16:45:23 -05005886void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005887 const std::string& reason) {
5888 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5889 updateLastAnrStateLocked(windowLabel, reason);
5890}
5891
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005892void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5893 const std::string& reason) {
5894 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005895 updateLastAnrStateLocked(windowLabel, reason);
5896}
5897
5898void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5899 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005900 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005901 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005902 struct tm tm;
5903 localtime_r(&t, &tm);
5904 char timestr[64];
5905 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005906 mLastAnrState.clear();
5907 mLastAnrState += INDENT "ANR:\n";
5908 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005909 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5910 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005911 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005912}
5913
Prabir Pradhancef936d2021-07-21 16:17:52 +00005914void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5915 KeyEntry& entry) {
5916 const KeyEvent event = createKeyEvent(entry);
5917 nsecs_t delay = 0;
5918 { // release lock
5919 scoped_unlock unlock(mLock);
5920 android::base::Timer t;
5921 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5922 entry.policyFlags);
5923 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5924 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5925 std::to_string(t.duration().count()).c_str());
5926 }
5927 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005928
5929 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005930 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005931 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005932 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005933 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005934 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5935 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005936 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005937}
5938
Prabir Pradhancef936d2021-07-21 16:17:52 +00005939void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005940 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005941 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005942 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005943 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005944 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005945 };
5946 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005947}
5948
Prabir Pradhanedd96402022-02-15 01:46:16 -08005949void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5950 std::optional<int32_t> pid) {
5951 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005952 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005953 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005954 };
5955 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005956}
5957
5958/**
5959 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5960 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5961 * command entry to the command queue.
5962 */
5963void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5964 std::string reason) {
5965 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005966 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005967 if (connection.monitor) {
5968 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5969 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005970 pid = findMonitorPidByTokenLocked(connectionToken);
5971 } else {
5972 // The connection is a window
5973 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5974 reason.c_str());
5975 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
5976 if (handle != nullptr) {
5977 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005978 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005979 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08005980 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005981}
5982
5983/**
5984 * Tell the policy that a connection has become responsive so that it can stop ANR.
5985 */
5986void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5987 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005988 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005989 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005990 pid = findMonitorPidByTokenLocked(connectionToken);
5991 } else {
5992 // The connection is a window
5993 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
5994 if (handle != nullptr) {
5995 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005996 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005997 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08005998 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005999}
6000
Prabir Pradhancef936d2021-07-21 16:17:52 +00006001bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006002 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006003 KeyEntry& keyEntry, bool handled) {
6004 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006005 if (!handled) {
6006 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006007 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006008 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006009 return false;
6010 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006011
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006012 // Get the fallback key state.
6013 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006014 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006015 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006016 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006017 connection->inputState.removeFallbackKey(originalKeyCode);
6018 }
6019
6020 if (handled || !dispatchEntry->hasForegroundTarget()) {
6021 // If the application handles the original key for which we previously
6022 // generated a fallback or if the window is not a foreground window,
6023 // then cancel the associated fallback key, if any.
6024 if (fallbackKeyCode != -1) {
6025 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006026 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6027 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6028 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6029 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6030 keyEntry.policyFlags);
6031 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006032 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006033 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006034
6035 mLock.unlock();
6036
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006037 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006038 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006039
6040 mLock.lock();
6041
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006042 // Cancel the fallback key.
6043 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006044 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006045 "application handled the original non-fallback key "
6046 "or is no longer a foreground target, "
6047 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006048 options.keyCode = fallbackKeyCode;
6049 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006050 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006051 connection->inputState.removeFallbackKey(originalKeyCode);
6052 }
6053 } else {
6054 // If the application did not handle a non-fallback key, first check
6055 // that we are in a good state to perform unhandled key event processing
6056 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006057 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006058 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006059 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6060 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6061 "since this is not an initial down. "
6062 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6063 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6064 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006065 return false;
6066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006067
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006068 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006069 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6070 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6071 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6072 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6073 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006074 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006075
6076 mLock.unlock();
6077
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006078 bool fallback =
6079 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006080 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006081
6082 mLock.lock();
6083
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006084 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006085 connection->inputState.removeFallbackKey(originalKeyCode);
6086 return false;
6087 }
6088
6089 // Latch the fallback keycode for this key on an initial down.
6090 // The fallback keycode cannot change at any other point in the lifecycle.
6091 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006092 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006093 fallbackKeyCode = event.getKeyCode();
6094 } else {
6095 fallbackKeyCode = AKEYCODE_UNKNOWN;
6096 }
6097 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6098 }
6099
6100 ALOG_ASSERT(fallbackKeyCode != -1);
6101
6102 // Cancel the fallback key if the policy decides not to send it anymore.
6103 // We will continue to dispatch the key to the policy but we will no
6104 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006105 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6106 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006107 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6108 if (fallback) {
6109 ALOGD("Unhandled key event: Policy requested to send key %d"
6110 "as a fallback for %d, but on the DOWN it had requested "
6111 "to send %d instead. Fallback canceled.",
6112 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6113 } else {
6114 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6115 "but on the DOWN it had requested to send %d. "
6116 "Fallback canceled.",
6117 originalKeyCode, fallbackKeyCode);
6118 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006119 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006120
6121 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6122 "canceling fallback, policy no longer desires it");
6123 options.keyCode = fallbackKeyCode;
6124 synthesizeCancelationEventsForConnectionLocked(connection, options);
6125
6126 fallback = false;
6127 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006128 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006129 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006130 }
6131 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006132
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006133 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6134 {
6135 std::string msg;
6136 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6137 connection->inputState.getFallbackKeys();
6138 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6139 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6140 }
6141 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6142 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006143 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006144 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006145
6146 if (fallback) {
6147 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006148 keyEntry.eventTime = event.getEventTime();
6149 keyEntry.deviceId = event.getDeviceId();
6150 keyEntry.source = event.getSource();
6151 keyEntry.displayId = event.getDisplayId();
6152 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6153 keyEntry.keyCode = fallbackKeyCode;
6154 keyEntry.scanCode = event.getScanCode();
6155 keyEntry.metaState = event.getMetaState();
6156 keyEntry.repeatCount = event.getRepeatCount();
6157 keyEntry.downTime = event.getDownTime();
6158 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006159
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006160 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6161 ALOGD("Unhandled key event: Dispatching fallback key. "
6162 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6163 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6164 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006165 return true; // restart the event
6166 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006167 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6168 ALOGD("Unhandled key event: No fallback key.");
6169 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006170
6171 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006172 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006173 }
6174 }
6175 return false;
6176}
6177
Prabir Pradhancef936d2021-07-21 16:17:52 +00006178bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006179 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006180 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006181 return false;
6182}
6183
Michael Wrightd02c5b62014-02-10 15:10:22 -08006184void InputDispatcher::traceInboundQueueLengthLocked() {
6185 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006186 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006187 }
6188}
6189
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006190void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006191 if (ATRACE_ENABLED()) {
6192 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006193 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6194 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006195 }
6196}
6197
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006198void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006199 if (ATRACE_ENABLED()) {
6200 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006201 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6202 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006203 }
6204}
6205
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006206void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006207 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006208
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006209 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006210 dumpDispatchStateLocked(dump);
6211
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006212 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006213 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006214 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006215 }
6216}
6217
6218void InputDispatcher::monitor() {
6219 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006220 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006221 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006222 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006223}
6224
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006225/**
6226 * Wake up the dispatcher and wait until it processes all events and commands.
6227 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6228 * this method can be safely called from any thread, as long as you've ensured that
6229 * the work you are interested in completing has already been queued.
6230 */
6231bool InputDispatcher::waitForIdle() {
6232 /**
6233 * Timeout should represent the longest possible time that a device might spend processing
6234 * events and commands.
6235 */
6236 constexpr std::chrono::duration TIMEOUT = 100ms;
6237 std::unique_lock lock(mLock);
6238 mLooper->wake();
6239 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6240 return result == std::cv_status::no_timeout;
6241}
6242
Vishnu Naire798b472020-07-23 13:52:21 -07006243/**
6244 * Sets focus to the window identified by the token. This must be called
6245 * after updating any input window handles.
6246 *
6247 * Params:
6248 * request.token - input channel token used to identify the window that should gain focus.
6249 * request.focusedToken - the token that the caller expects currently to be focused. If the
6250 * specified token does not match the currently focused window, this request will be dropped.
6251 * If the specified focused token matches the currently focused window, the call will succeed.
6252 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6253 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6254 * when requesting the focus change. This determines which request gets
6255 * precedence if there is a focus change request from another source such as pointer down.
6256 */
Vishnu Nair958da932020-08-21 17:12:37 -07006257void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6258 { // acquire lock
6259 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006260 std::optional<FocusResolver::FocusChanges> changes =
6261 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6262 if (changes) {
6263 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006264 }
6265 } // release lock
6266 // Wake up poll loop since it may need to make new input dispatching choices.
6267 mLooper->wake();
6268}
6269
Vishnu Nairc519ff72021-01-21 08:23:08 -08006270void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6271 if (changes.oldFocus) {
6272 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006273 if (focusedInputChannel) {
6274 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6275 "focus left window");
6276 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006277 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006278 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006279 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006280 if (changes.newFocus) {
6281 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006282 }
6283
Prabir Pradhan99987712020-11-10 18:43:05 -08006284 // If a window has pointer capture, then it must have focus. We need to ensure that this
6285 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6286 // If the window loses focus before it loses pointer capture, then the window can be in a state
6287 // where it has pointer capture but not focus, violating the contract. Therefore we must
6288 // dispatch the pointer capture event before the focus event. Since focus events are added to
6289 // the front of the queue (above), we add the pointer capture event to the front of the queue
6290 // after the focus events are added. This ensures the pointer capture event ends up at the
6291 // front.
6292 disablePointerCaptureForcedLocked();
6293
Vishnu Nairc519ff72021-01-21 08:23:08 -08006294 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006295 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006296 }
6297}
Vishnu Nair958da932020-08-21 17:12:37 -07006298
Prabir Pradhan99987712020-11-10 18:43:05 -08006299void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006300 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006301 return;
6302 }
6303
6304 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6305
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006306 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006307 setPointerCaptureLocked(false);
6308 }
6309
6310 if (!mWindowTokenWithPointerCapture) {
6311 // No need to send capture changes because no window has capture.
6312 return;
6313 }
6314
6315 if (mPendingEvent != nullptr) {
6316 // Move the pending event to the front of the queue. This will give the chance
6317 // for the pending event to be dropped if it is a captured event.
6318 mInboundQueue.push_front(mPendingEvent);
6319 mPendingEvent = nullptr;
6320 }
6321
6322 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006323 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006324 mInboundQueue.push_front(std::move(entry));
6325}
6326
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006327void InputDispatcher::setPointerCaptureLocked(bool enable) {
6328 mCurrentPointerCaptureRequest.enable = enable;
6329 mCurrentPointerCaptureRequest.seq++;
6330 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006331 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006332 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006333 };
6334 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006335}
6336
Vishnu Nair599f1412021-06-21 10:39:58 -07006337void InputDispatcher::displayRemoved(int32_t displayId) {
6338 { // acquire lock
6339 std::scoped_lock _l(mLock);
6340 // Set an empty list to remove all handles from the specific display.
6341 setInputWindowsLocked(/* window handles */ {}, displayId);
6342 setFocusedApplicationLocked(displayId, nullptr);
6343 // Call focus resolver to clean up stale requests. This must be called after input windows
6344 // have been removed for the removed display.
6345 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006346 // Reset pointer capture eligibility, regardless of previous state.
6347 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006348 } // release lock
6349
6350 // Wake up poll loop since it may need to make new input dispatching choices.
6351 mLooper->wake();
6352}
6353
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006354void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6355 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006356 // The listener sends the windows as a flattened array. Separate the windows by display for
6357 // more convenient parsing.
6358 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006359 for (const auto& info : windowInfos) {
6360 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6361 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6362 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006363
6364 { // acquire lock
6365 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006366
6367 // Ensure that we have an entry created for all existing displays so that if a displayId has
6368 // no windows, we can tell that the windows were removed from the display.
6369 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6370 handlesPerDisplay[displayId];
6371 }
6372
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006373 mDisplayInfos.clear();
6374 for (const auto& displayInfo : displayInfos) {
6375 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6376 }
6377
6378 for (const auto& [displayId, handles] : handlesPerDisplay) {
6379 setInputWindowsLocked(handles, displayId);
6380 }
6381 }
6382 // Wake up poll loop since it may need to make new input dispatching choices.
6383 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006384}
6385
Vishnu Nair062a8672021-09-03 16:07:44 -07006386bool InputDispatcher::shouldDropInput(
6387 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006388 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6389 (windowHandle->getInfo()->inputConfig.test(
6390 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006391 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006392 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6393 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006394 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006395 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006396 windowHandle->getInfo()->displayId);
6397 return true;
6398 }
6399 return false;
6400}
6401
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006402void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6403 const std::vector<gui::WindowInfo>& windowInfos,
6404 const std::vector<DisplayInfo>& displayInfos) {
6405 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6406}
6407
Arthur Hungdfd528e2021-12-08 13:23:04 +00006408void InputDispatcher::cancelCurrentTouch() {
6409 {
6410 std::scoped_lock _l(mLock);
6411 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6412 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6413 "cancel current touch");
6414 synthesizeCancelationEventsForAllConnectionsLocked(options);
6415
6416 mTouchStatesByDisplay.clear();
6417 mLastHoverWindowHandle.clear();
6418 }
6419 // Wake up poll loop since there might be work to do.
6420 mLooper->wake();
6421}
6422
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006423void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6424 std::scoped_lock _l(mLock);
6425 mMonitorDispatchingTimeout = timeout;
6426}
6427
Garfield Tane84e6f92019-08-29 17:28:41 -07006428} // namespace android::inputdispatcher