blob: 625c36733834b61ed02ba8fb301ca29e0e2f192a [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(),
Siarhei Vishniakoubd252722022-01-06 03:49:35 -0800556 mLatencyTracker(&mLatencyAggregator) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800557 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800558 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800559
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700560 mWindowInfoListener = new DispatcherWindowListener(*this);
561 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
562
Yi Kong9b14ac62018-07-17 13:48:38 -0700563 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800564
565 policy->getDispatcherConfiguration(&mConfig);
566}
567
568InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000569 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800570
Prabir Pradhancef936d2021-07-21 16:17:52 +0000571 resetKeyRepeatLocked();
572 releasePendingEventLocked();
573 drainInboundQueueLocked();
574 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800575
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000576 while (!mConnectionsByToken.empty()) {
577 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000578 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
579 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800580 }
581}
582
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700583status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700584 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700585 return ALREADY_EXISTS;
586 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700587 mThread = std::make_unique<InputThread>(
588 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
589 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700590}
591
592status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700593 if (mThread && mThread->isCallingThread()) {
594 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700595 return INVALID_OPERATION;
596 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700597 mThread.reset();
598 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700599}
600
Michael Wrightd02c5b62014-02-10 15:10:22 -0800601void InputDispatcher::dispatchOnce() {
602 nsecs_t nextWakeupTime = LONG_LONG_MAX;
603 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800604 std::scoped_lock _l(mLock);
605 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800606
607 // Run a dispatch loop if there are no pending commands.
608 // The dispatch loop might enqueue commands to run afterwards.
609 if (!haveCommandsLocked()) {
610 dispatchOnceInnerLocked(&nextWakeupTime);
611 }
612
613 // Run all pending commands if there are any.
614 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000615 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800616 nextWakeupTime = LONG_LONG_MIN;
617 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800618
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700619 // If we are still waiting for ack on some events,
620 // we might have to wake up earlier to check if an app is anr'ing.
621 const nsecs_t nextAnrCheck = processAnrsLocked();
622 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
623
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800624 // We are about to enter an infinitely long sleep, because we have no commands or
625 // pending or queued events
626 if (nextWakeupTime == LONG_LONG_MAX) {
627 mDispatcherEnteredIdle.notify_all();
628 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629 } // release lock
630
631 // Wait for callback or timeout or wake. (make sure we round up, not down)
632 nsecs_t currentTime = now();
633 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
634 mLooper->pollOnce(timeoutMillis);
635}
636
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700637/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500638 * Raise ANR if there is no focused window.
639 * Before the ANR is raised, do a final state check:
640 * 1. The currently focused application must be the same one we are waiting for.
641 * 2. Ensure we still don't have a focused window.
642 */
643void InputDispatcher::processNoFocusedWindowAnrLocked() {
644 // Check if the application that we are waiting for is still focused.
645 std::shared_ptr<InputApplicationHandle> focusedApplication =
646 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
647 if (focusedApplication == nullptr ||
648 focusedApplication->getApplicationToken() !=
649 mAwaitedFocusedApplication->getApplicationToken()) {
650 // Unexpected because we should have reset the ANR timer when focused application changed
651 ALOGE("Waited for a focused window, but focused application has already changed to %s",
652 focusedApplication->getName().c_str());
653 return; // The focused application has changed.
654 }
655
chaviw98318de2021-05-19 16:45:23 -0500656 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500657 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
658 if (focusedWindowHandle != nullptr) {
659 return; // We now have a focused window. No need for ANR.
660 }
661 onAnrLocked(mAwaitedFocusedApplication);
662}
663
664/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700665 * Check if any of the connections' wait queues have events that are too old.
666 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
667 * Return the time at which we should wake up next.
668 */
669nsecs_t InputDispatcher::processAnrsLocked() {
670 const nsecs_t currentTime = now();
671 nsecs_t nextAnrCheck = LONG_LONG_MAX;
672 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
673 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
674 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500675 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700676 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500677 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700678 return LONG_LONG_MIN;
679 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500680 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700681 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
682 }
683 }
684
685 // Check if any connection ANRs are due
686 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
687 if (currentTime < nextAnrCheck) { // most likely scenario
688 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
689 }
690
691 // If we reached here, we have an unresponsive connection.
692 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
693 if (connection == nullptr) {
694 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
695 return nextAnrCheck;
696 }
697 connection->responsive = false;
698 // Stop waking up for this unresponsive connection
699 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000700 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700701 return LONG_LONG_MIN;
702}
703
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800704std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
705 const sp<Connection>& connection) {
706 if (connection->monitor) {
707 return mMonitorDispatchingTimeout;
708 }
709 const sp<WindowInfoHandle> window =
710 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700711 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500712 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700713 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500714 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700715}
716
Michael Wrightd02c5b62014-02-10 15:10:22 -0800717void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
718 nsecs_t currentTime = now();
719
Jeff Browndc5992e2014-04-11 01:27:26 -0700720 // Reset the key repeat timer whenever normal dispatch is suspended while the
721 // device is in a non-interactive state. This is to ensure that we abort a key
722 // repeat if the device is just coming out of sleep.
723 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800724 resetKeyRepeatLocked();
725 }
726
727 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
728 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100729 if (DEBUG_FOCUS) {
730 ALOGD("Dispatch frozen. Waiting some more.");
731 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800732 return;
733 }
734
735 // Optimize latency of app switches.
736 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
737 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
738 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
739 if (mAppSwitchDueTime < *nextWakeupTime) {
740 *nextWakeupTime = mAppSwitchDueTime;
741 }
742
743 // Ready to start a new event.
744 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700745 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700746 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747 if (isAppSwitchDue) {
748 // The inbound queue is empty so the app switch key we were waiting
749 // for will never arrive. Stop waiting for it.
750 resetPendingAppSwitchLocked(false);
751 isAppSwitchDue = false;
752 }
753
754 // Synthesize a key repeat if appropriate.
755 if (mKeyRepeatState.lastKeyEntry) {
756 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
757 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
758 } else {
759 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
760 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
761 }
762 }
763 }
764
765 // Nothing to do if there is no pending event.
766 if (!mPendingEvent) {
767 return;
768 }
769 } else {
770 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700771 mPendingEvent = mInboundQueue.front();
772 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773 traceInboundQueueLengthLocked();
774 }
775
776 // Poke user activity for this event.
777 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700778 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 }
781
782 // Now we have an event to dispatch.
783 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700784 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800785 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700786 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700788 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800789 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700790 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800791 }
792
793 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700794 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800795 }
796
797 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700798 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700799 const ConfigurationChangedEntry& typedEntry =
800 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700801 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700802 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700803 break;
804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700806 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700807 const DeviceResetEntry& typedEntry =
808 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700809 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700810 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700811 break;
812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100814 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700815 std::shared_ptr<FocusEntry> typedEntry =
816 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100817 dispatchFocusLocked(currentTime, typedEntry);
818 done = true;
819 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
820 break;
821 }
822
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700823 case EventEntry::Type::TOUCH_MODE_CHANGED: {
824 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
825 dispatchTouchModeChangeLocked(currentTime, typedEntry);
826 done = true;
827 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
828 break;
829 }
830
Prabir Pradhan99987712020-11-10 18:43:05 -0800831 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
832 const auto typedEntry =
833 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
834 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
835 done = true;
836 break;
837 }
838
arthurhungb89ccb02020-12-30 16:19:01 +0800839 case EventEntry::Type::DRAG: {
840 std::shared_ptr<DragEntry> typedEntry =
841 std::static_pointer_cast<DragEntry>(mPendingEvent);
842 dispatchDragLocked(currentTime, typedEntry);
843 done = true;
844 break;
845 }
846
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700847 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700848 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700849 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700850 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700851 resetPendingAppSwitchLocked(true);
852 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700853 } else if (dropReason == DropReason::NOT_DROPPED) {
854 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700855 }
856 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700857 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700858 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700859 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700860 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
861 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700862 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700863 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700864 break;
865 }
866
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700867 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700868 std::shared_ptr<MotionEntry> motionEntry =
869 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700870 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
871 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700873 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700874 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700875 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700876 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
877 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700878 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700879 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700880 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881 }
Chris Yef59a2f42020-10-16 12:55:26 -0700882
883 case EventEntry::Type::SENSOR: {
884 std::shared_ptr<SensorEntry> sensorEntry =
885 std::static_pointer_cast<SensorEntry>(mPendingEvent);
886 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
887 dropReason = DropReason::APP_SWITCH;
888 }
889 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
890 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
891 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
892 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
893 dropReason = DropReason::STALE;
894 }
895 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
896 done = true;
897 break;
898 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 }
900
901 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700902 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700903 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 }
Michael Wright3a981722015-06-10 15:26:13 +0100905 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906
907 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700908 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909 }
910}
911
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800912bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
913 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
914}
915
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700916/**
917 * Return true if the events preceding this incoming motion event should be dropped
918 * Return false otherwise (the default behaviour)
919 */
920bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700921 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700922 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700923
924 // Optimize case where the current application is unresponsive and the user
925 // decides to touch a window in a different application.
926 // If the application takes too long to catch up then we drop all events preceding
927 // the touch into the other window.
928 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700929 int32_t displayId = motionEntry.displayId;
930 int32_t x = static_cast<int32_t>(
931 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
932 int32_t y = static_cast<int32_t>(
933 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Prabir Pradhand65552b2021-10-07 11:23:50 -0700934
935 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -0500936 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700937 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700938 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700939 touchedWindowHandle->getApplicationToken() !=
940 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700941 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700942 ALOGI("Pruning input queue because user touched a different application while waiting "
943 "for %s",
944 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700945 return true;
946 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700947
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800948 // Alternatively, maybe there's a spy window that could handle this event.
949 const std::vector<sp<WindowInfoHandle>> touchedSpies =
950 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
951 for (const auto& windowHandle : touchedSpies) {
952 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000953 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800954 // This spy window could take more input. Drop all events preceding this
955 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700956 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800957 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700958 mAwaitedFocusedApplication->getName().c_str());
959 return true;
960 }
961 }
962 }
963
964 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
965 // yet been processed by some connections, the dispatcher will wait for these motion
966 // events to be processed before dispatching the key event. This is because these motion events
967 // may cause a new window to be launched, which the user might expect to receive focus.
968 // To prevent waiting forever for such events, just send the key to the currently focused window
969 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
970 ALOGD("Received a new pointer down event, stop waiting for events to process and "
971 "just send the pending key event to the focused window.");
972 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700973 }
974 return false;
975}
976
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700977bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700978 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700979 mInboundQueue.push_back(std::move(newEntry));
980 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981 traceInboundQueueLengthLocked();
982
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700983 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700984 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +0000985 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
986 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700987 // Optimize app switch latency.
988 // If the application takes too long to catch up then we drop all events preceding
989 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700990 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700991 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700992 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700993 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700994 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700995 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000996 if (DEBUG_APP_SWITCH) {
997 ALOGD("App switch is pending!");
998 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700999 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001000 mAppSwitchSawKeyDown = false;
1001 needWake = true;
1002 }
1003 }
1004 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001005
1006 // If a new up event comes in, and the pending event with same key code has been asked
1007 // to try again later because of the policy. We have to reset the intercept key wake up
1008 // time for it may have been handled in the policy and could be dropped.
1009 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1010 mPendingEvent->type == EventEntry::Type::KEY) {
1011 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1012 if (pendingKey.keyCode == keyEntry.keyCode &&
1013 pendingKey.interceptKeyResult ==
1014 KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1015 pendingKey.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1016 pendingKey.interceptKeyWakeupTime = 0;
1017 needWake = true;
1018 }
1019 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001020 break;
1021 }
1022
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001023 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001024 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1025 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001026 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1027 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001028 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001031 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001032 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001033 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1034 break;
1035 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001036 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001037 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001038 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001039 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001040 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1041 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001042 // nothing to do
1043 break;
1044 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045 }
1046
1047 return needWake;
1048}
1049
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001050void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001051 // Do not store sensor event in recent queue to avoid flooding the queue.
1052 if (entry->type != EventEntry::Type::SENSOR) {
1053 mRecentQueue.push_back(entry);
1054 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001055 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001056 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057 }
1058}
1059
chaviw98318de2021-05-19 16:45:23 -05001060sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1061 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001062 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001063 bool addOutsideTargets,
1064 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001065 if (addOutsideTargets && touchState == nullptr) {
1066 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001069 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001070 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001071 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001072 continue;
1073 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001074
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001075 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001076 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001077 return windowHandle;
1078 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001079
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001080 if (addOutsideTargets &&
1081 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001082 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1083 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084 }
1085 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001086 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001087}
1088
Prabir Pradhand65552b2021-10-07 11:23:50 -07001089std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1090 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001091 // Traverse windows from front to back and gather the touched spy windows.
1092 std::vector<sp<WindowInfoHandle>> spyWindows;
1093 const auto& windowHandles = getWindowHandlesLocked(displayId);
1094 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1095 const WindowInfo& info = *windowHandle->getInfo();
1096
Prabir Pradhand65552b2021-10-07 11:23:50 -07001097 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001098 continue;
1099 }
1100 if (!info.isSpy()) {
1101 // The first touched non-spy window was found, so return the spy windows touched so far.
1102 return spyWindows;
1103 }
1104 spyWindows.push_back(windowHandle);
1105 }
1106 return spyWindows;
1107}
1108
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001109void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001110 const char* reason;
1111 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001112 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001113 if (DEBUG_INBOUND_EVENT_DETAILS) {
1114 ALOGD("Dropped event because policy consumed it.");
1115 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001116 reason = "inbound event was dropped because the policy consumed it";
1117 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001118 case DropReason::DISABLED:
1119 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001120 ALOGI("Dropped event because input dispatch is disabled.");
1121 }
1122 reason = "inbound event was dropped because input dispatch is disabled";
1123 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001124 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001125 ALOGI("Dropped event because of pending overdue app switch.");
1126 reason = "inbound event was dropped because of pending overdue app switch";
1127 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001128 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001129 ALOGI("Dropped event because the current application is not responding and the user "
1130 "has started interacting with a different application.");
1131 reason = "inbound event was dropped because the current application is not responding "
1132 "and the user has started interacting with a different application";
1133 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001134 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001135 ALOGI("Dropped event because it is stale.");
1136 reason = "inbound event was dropped because it is stale";
1137 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001138 case DropReason::NO_POINTER_CAPTURE:
1139 ALOGI("Dropped event because there is no window with Pointer Capture.");
1140 reason = "inbound event was dropped because there is no window with Pointer Capture";
1141 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001142 case DropReason::NOT_DROPPED: {
1143 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001144 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001145 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146 }
1147
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001148 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001149 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001150 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1151 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001152 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001154 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001155 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1156 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001157 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1158 synthesizeCancelationEventsForAllConnectionsLocked(options);
1159 } else {
1160 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1161 synthesizeCancelationEventsForAllConnectionsLocked(options);
1162 }
1163 break;
1164 }
Chris Yef59a2f42020-10-16 12:55:26 -07001165 case EventEntry::Type::SENSOR: {
1166 break;
1167 }
arthurhungb89ccb02020-12-30 16:19:01 +08001168 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1169 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001170 break;
1171 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001172 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001173 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001174 case EventEntry::Type::CONFIGURATION_CHANGED:
1175 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001176 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001177 break;
1178 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179 }
1180}
1181
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001182static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001183 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1184 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185}
1186
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001187bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1188 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1189 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1190 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191}
1192
1193bool InputDispatcher::isAppSwitchPendingLocked() {
1194 return mAppSwitchDueTime != LONG_LONG_MAX;
1195}
1196
1197void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1198 mAppSwitchDueTime = LONG_LONG_MAX;
1199
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001200 if (DEBUG_APP_SWITCH) {
1201 if (handled) {
1202 ALOGD("App switch has arrived.");
1203 } else {
1204 ALOGD("App switch was abandoned.");
1205 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207}
1208
Michael Wrightd02c5b62014-02-10 15:10:22 -08001209bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001210 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211}
1212
Prabir Pradhancef936d2021-07-21 16:17:52 +00001213bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001214 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215 return false;
1216 }
1217
1218 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001219 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001220 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001221 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1222 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001223 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224 return true;
1225}
1226
Prabir Pradhancef936d2021-07-21 16:17:52 +00001227void InputDispatcher::postCommandLocked(Command&& command) {
1228 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229}
1230
1231void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001232 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001233 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001234 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 releaseInboundEventLocked(entry);
1236 }
1237 traceInboundQueueLengthLocked();
1238}
1239
1240void InputDispatcher::releasePendingEventLocked() {
1241 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001243 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 }
1245}
1246
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001247void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001249 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001250 if (DEBUG_DISPATCH_CYCLE) {
1251 ALOGD("Injected inbound event was dropped.");
1252 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001253 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254 }
1255 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001256 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257 }
1258 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259}
1260
1261void InputDispatcher::resetKeyRepeatLocked() {
1262 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001263 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 }
1265}
1266
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001267std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1268 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001269
Michael Wright2e732952014-09-24 13:26:59 -07001270 uint32_t policyFlags = entry->policyFlags &
1271 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001273 std::shared_ptr<KeyEntry> newEntry =
1274 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1275 entry->source, entry->displayId, policyFlags, entry->action,
1276 entry->flags, entry->keyCode, entry->scanCode,
1277 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001279 newEntry->syntheticRepeat = true;
1280 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001281 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001282 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283}
1284
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001285bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001286 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001287 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1288 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290
1291 // Reset key repeating in case a keyboard device was added or removed or something.
1292 resetKeyRepeatLocked();
1293
1294 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001295 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1296 scoped_unlock unlock(mLock);
1297 mPolicy->notifyConfigurationChanged(eventTime);
1298 };
1299 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001300 return true;
1301}
1302
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001303bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1304 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001305 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1306 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1307 entry.deviceId);
1308 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309
liushenxiang42232912021-05-21 20:24:09 +08001310 // Reset key repeating in case a keyboard device was disabled or enabled.
1311 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1312 resetKeyRepeatLocked();
1313 }
1314
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001315 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001316 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317 synthesizeCancelationEventsForAllConnectionsLocked(options);
1318 return true;
1319}
1320
Vishnu Nairad321cd2020-08-20 16:40:21 -07001321void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001322 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001323 if (mPendingEvent != nullptr) {
1324 // Move the pending event to the front of the queue. This will give the chance
1325 // for the pending event to get dispatched to the newly focused window
1326 mInboundQueue.push_front(mPendingEvent);
1327 mPendingEvent = nullptr;
1328 }
1329
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001330 std::unique_ptr<FocusEntry> focusEntry =
1331 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1332 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001333
1334 // This event should go to the front of the queue, but behind all other focus events
1335 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001336 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001337 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001338 [](const std::shared_ptr<EventEntry>& event) {
1339 return event->type == EventEntry::Type::FOCUS;
1340 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001341
1342 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001343 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001344}
1345
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001346void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001347 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001348 if (channel == nullptr) {
1349 return; // Window has gone away
1350 }
1351 InputTarget target;
1352 target.inputChannel = channel;
1353 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1354 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001355 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1356 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001357 std::string reason = std::string("reason=").append(entry->reason);
1358 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001359 dispatchEventLocked(currentTime, entry, {target});
1360}
1361
Prabir Pradhan99987712020-11-10 18:43:05 -08001362void InputDispatcher::dispatchPointerCaptureChangedLocked(
1363 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1364 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001365 dropReason = DropReason::NOT_DROPPED;
1366
Prabir Pradhan99987712020-11-10 18:43:05 -08001367 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001368 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001369
1370 if (entry->pointerCaptureRequest.enable) {
1371 // Enable Pointer Capture.
1372 if (haveWindowWithPointerCapture &&
1373 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001374 // This can happen if pointer capture is disabled and re-enabled before we notify the
1375 // app of the state change, so there is no need to notify the app.
1376 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1377 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001378 }
1379 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001380 // This can happen if a window requests capture and immediately releases capture.
1381 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001382 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001383 return;
1384 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001385 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1386 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1387 return;
1388 }
1389
Vishnu Nairc519ff72021-01-21 08:23:08 -08001390 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001391 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1392 mWindowTokenWithPointerCapture = token;
1393 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001394 // Disable Pointer Capture.
1395 // We do not check if the sequence number matches for requests to disable Pointer Capture
1396 // for two reasons:
1397 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1398 // to disable capture with the same sequence number: one generated by
1399 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1400 // Capture being disabled in InputReader.
1401 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1402 // actual Pointer Capture state that affects events being generated by input devices is
1403 // in InputReader.
1404 if (!haveWindowWithPointerCapture) {
1405 // Pointer capture was already forcefully disabled because of focus change.
1406 dropReason = DropReason::NOT_DROPPED;
1407 return;
1408 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001409 token = mWindowTokenWithPointerCapture;
1410 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001411 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001412 setPointerCaptureLocked(false);
1413 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001414 }
1415
1416 auto channel = getInputChannelLocked(token);
1417 if (channel == nullptr) {
1418 // Window has gone away, clean up Pointer Capture state.
1419 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001420 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001421 setPointerCaptureLocked(false);
1422 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001423 return;
1424 }
1425 InputTarget target;
1426 target.inputChannel = channel;
1427 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1428 entry->dispatchInProgress = true;
1429 dispatchEventLocked(currentTime, entry, {target});
1430
1431 dropReason = DropReason::NOT_DROPPED;
1432}
1433
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001434void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1435 const std::shared_ptr<TouchModeEntry>& entry) {
1436 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1437 getWindowHandlesLocked(mFocusedDisplayId);
1438 if (windowHandles.empty()) {
1439 return;
1440 }
1441 const std::vector<InputTarget> inputTargets =
1442 getInputTargetsFromWindowHandlesLocked(windowHandles);
1443 if (inputTargets.empty()) {
1444 return;
1445 }
1446 entry->dispatchInProgress = true;
1447 dispatchEventLocked(currentTime, entry, inputTargets);
1448}
1449
1450std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1451 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1452 std::vector<InputTarget> inputTargets;
1453 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1454 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1455 const sp<IBinder>& token = handle->getToken();
1456 if (token == nullptr) {
1457 continue;
1458 }
1459 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1460 if (channel == nullptr) {
1461 continue; // Window has gone away
1462 }
1463 InputTarget target;
1464 target.inputChannel = channel;
1465 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1466 inputTargets.push_back(target);
1467 }
1468 return inputTargets;
1469}
1470
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001471bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001472 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001474 if (!entry->dispatchInProgress) {
1475 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1476 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1477 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1478 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001479 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 // We have seen two identical key downs in a row which indicates that the device
1481 // driver is automatically generating key repeats itself. We take note of the
1482 // repeat here, but we disable our own next key repeat timer since it is clear that
1483 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001484 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1485 // Make sure we don't get key down from a different device. If a different
1486 // device Id has same key pressed down, the new device Id will replace the
1487 // current one to hold the key repeat with repeat count reset.
1488 // In the future when got a KEY_UP on the device id, drop it and do not
1489 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001490 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1491 resetKeyRepeatLocked();
1492 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1493 } else {
1494 // Not a repeat. Save key down state in case we do see a repeat later.
1495 resetKeyRepeatLocked();
1496 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1497 }
1498 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001499 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1500 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001501 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001502 if (DEBUG_INBOUND_EVENT_DETAILS) {
1503 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1504 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001505 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506 resetKeyRepeatLocked();
1507 }
1508
1509 if (entry->repeatCount == 1) {
1510 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1511 } else {
1512 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1513 }
1514
1515 entry->dispatchInProgress = true;
1516
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001517 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518 }
1519
1520 // Handle case where the policy asked us to try again later last time.
1521 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1522 if (currentTime < entry->interceptKeyWakeupTime) {
1523 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1524 *nextWakeupTime = entry->interceptKeyWakeupTime;
1525 }
1526 return false; // wait until next wakeup
1527 }
1528 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1529 entry->interceptKeyWakeupTime = 0;
1530 }
1531
1532 // Give the policy a chance to intercept the key.
1533 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1534 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001535 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001536 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001537
1538 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1539 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1540 };
1541 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542 return false; // wait for the command to run
1543 } else {
1544 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1545 }
1546 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001547 if (*dropReason == DropReason::NOT_DROPPED) {
1548 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549 }
1550 }
1551
1552 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001553 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001554 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001555 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1556 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001557 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558 return true;
1559 }
1560
1561 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001562 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001563 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001564 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001565 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001566 return false;
1567 }
1568
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001569 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001570 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571 return true;
1572 }
1573
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001574 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001575 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576
1577 // Dispatch the key.
1578 dispatchEventLocked(currentTime, entry, inputTargets);
1579 return true;
1580}
1581
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001582void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001583 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1584 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1585 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1586 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1587 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1588 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1589 entry.metaState, entry.repeatCount, entry.downTime);
1590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591}
1592
Prabir Pradhancef936d2021-07-21 16:17:52 +00001593void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1594 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001595 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001596 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1597 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1598 "source=0x%x, sensorType=%s",
1599 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001600 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001601 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001602 auto command = [this, entry]() REQUIRES(mLock) {
1603 scoped_unlock unlock(mLock);
1604
1605 if (entry->accuracyChanged) {
1606 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1607 }
1608 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1609 entry->hwTimestamp, entry->values);
1610 };
1611 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001612}
1613
1614bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001615 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1616 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001617 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001618 }
Chris Yef59a2f42020-10-16 12:55:26 -07001619 { // acquire lock
1620 std::scoped_lock _l(mLock);
1621
1622 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1623 std::shared_ptr<EventEntry> entry = *it;
1624 if (entry->type == EventEntry::Type::SENSOR) {
1625 it = mInboundQueue.erase(it);
1626 releaseInboundEventLocked(entry);
1627 }
1628 }
1629 }
1630 return true;
1631}
1632
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001633bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001634 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001635 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001637 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001638 entry->dispatchInProgress = true;
1639
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001640 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641 }
1642
1643 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001644 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001645 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001646 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1647 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001648 return true;
1649 }
1650
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001651 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652
1653 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001654 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655
1656 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001657 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658 if (isPointerEvent) {
1659 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001660
1661 if (mDragState &&
1662 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1663 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1664 pilferPointersLocked(mDragState->dragWindow->getToken());
1665 }
1666
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001667 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001668 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001669 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670 } else {
1671 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001672 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001673 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001675 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 return false;
1677 }
1678
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001679 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001680 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001681 return true;
1682 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001683 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001684 CancelationOptions::Mode mode(isPointerEvent
1685 ? CancelationOptions::CANCEL_POINTER_EVENTS
1686 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1687 CancelationOptions options(mode, "input event injection failed");
1688 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689 return true;
1690 }
1691
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001692 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001693 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694
1695 // Dispatch the motion.
1696 if (conflictingPointerActions) {
1697 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001698 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001699 synthesizeCancelationEventsForAllConnectionsLocked(options);
1700 }
1701 dispatchEventLocked(currentTime, entry, inputTargets);
1702 return true;
1703}
1704
chaviw98318de2021-05-19 16:45:23 -05001705void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001706 bool isExiting, const int32_t rawX,
1707 const int32_t rawY) {
1708 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001709 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001710 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1711 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001712
1713 enqueueInboundEventLocked(std::move(dragEntry));
1714}
1715
1716void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1717 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1718 if (channel == nullptr) {
1719 return; // Window has gone away
1720 }
1721 InputTarget target;
1722 target.inputChannel = channel;
1723 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1724 entry->dispatchInProgress = true;
1725 dispatchEventLocked(currentTime, entry, {target});
1726}
1727
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001728void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001729 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1730 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1731 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001732 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001733 "metaState=0x%x, buttonState=0x%x,"
1734 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1735 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001736 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1737 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1738 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001740 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1741 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1742 "x=%f, y=%f, pressure=%f, size=%f, "
1743 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1744 "orientation=%f",
1745 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1746 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1747 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1748 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1749 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1750 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1751 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1752 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1753 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1754 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001757}
1758
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001759void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1760 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001761 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001762 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001763 if (DEBUG_DISPATCH_CYCLE) {
1764 ALOGD("dispatchEventToCurrentInputTargets");
1765 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001767 updateInteractionTokensLocked(*eventEntry, inputTargets);
1768
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1770
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001771 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001773 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001774 sp<Connection> connection =
1775 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001776 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001777 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001779 if (DEBUG_FOCUS) {
1780 ALOGD("Dropping event delivery to target with channel '%s' because it "
1781 "is no longer registered with the input dispatcher.",
1782 inputTarget.inputChannel->getName().c_str());
1783 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784 }
1785 }
1786}
1787
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001788void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1789 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1790 // If the policy decides to close the app, we will get a channel removal event via
1791 // unregisterInputChannel, and will clean up the connection that way. We are already not
1792 // sending new pointers to the connection when it blocked, but focused events will continue to
1793 // pile up.
1794 ALOGW("Canceling events for %s because it is unresponsive",
1795 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001796 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001797 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1798 "application not responding");
1799 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800 }
1801}
1802
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001803void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001804 if (DEBUG_FOCUS) {
1805 ALOGD("Resetting ANR timeouts.");
1806 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001807
1808 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001809 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001810 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811}
1812
Tiger Huang721e26f2018-07-24 22:26:19 +08001813/**
1814 * Get the display id that the given event should go to. If this event specifies a valid display id,
1815 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1816 * Focused display is the display that the user most recently interacted with.
1817 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001818int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001819 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001820 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001821 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001822 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1823 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001824 break;
1825 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001826 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001827 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1828 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001829 break;
1830 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001831 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001832 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001833 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001834 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001835 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001836 case EventEntry::Type::SENSOR:
1837 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001838 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001839 return ADISPLAY_ID_NONE;
1840 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001841 }
1842 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1843}
1844
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001845bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1846 const char* focusedWindowName) {
1847 if (mAnrTracker.empty()) {
1848 // already processed all events that we waited for
1849 mKeyIsWaitingForEventsTimeout = std::nullopt;
1850 return false;
1851 }
1852
1853 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1854 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001855 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001856 mKeyIsWaitingForEventsTimeout = currentTime +
1857 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1858 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001859 return true;
1860 }
1861
1862 // We still have pending events, and already started the timer
1863 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1864 return true; // Still waiting
1865 }
1866
1867 // Waited too long, and some connection still hasn't processed all motions
1868 // Just send the key to the focused window
1869 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1870 focusedWindowName);
1871 mKeyIsWaitingForEventsTimeout = std::nullopt;
1872 return false;
1873}
1874
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001875static std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
1876 if (eventEntry.type == EventEntry::Type::KEY) {
1877 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
1878 return keyEntry.downTime;
1879 } else if (eventEntry.type == EventEntry::Type::MOTION) {
1880 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
1881 return motionEntry.downTime;
1882 }
1883 return std::nullopt;
1884}
1885
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001886InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1887 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1888 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001889 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890
Tiger Huang721e26f2018-07-24 22:26:19 +08001891 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001892 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001893 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001894 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1895
Michael Wrightd02c5b62014-02-10 15:10:22 -08001896 // If there is no currently focused window and no focused application
1897 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001898 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1899 ALOGI("Dropping %s event because there is no focused window or focused application in "
1900 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001901 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001902 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903 }
1904
Vishnu Nair062a8672021-09-03 16:07:44 -07001905 // Drop key events if requested by input feature
1906 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1907 return InputEventInjectionResult::FAILED;
1908 }
1909
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001910 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1911 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1912 // start interacting with another application via touch (app switch). This code can be removed
1913 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1914 // an app is expected to have a focused window.
1915 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1916 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1917 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001918 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1919 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1920 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001921 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001922 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001923 ALOGW("Waiting because no window has focus but %s may eventually add a "
1924 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001925 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001926 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001927 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001928 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1929 // Already raised ANR. Drop the event
1930 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001931 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001932 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001933 } else {
1934 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001935 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001936 }
1937 }
1938
1939 // we have a valid, non-null focused window
1940 resetNoFocusedWindowTimeoutLocked();
1941
Prabir Pradhan5735a322022-04-11 17:23:34 +00001942 // Verify targeted injection.
1943 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
1944 ALOGW("Dropping injected event: %s", (*err).c_str());
1945 return InputEventInjectionResult::TARGET_MISMATCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946 }
1947
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001948 if (focusedWindowHandle->getInfo()->inputConfig.test(
1949 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001950 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001951 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001952 }
1953
1954 // If the event is a key event, then we must wait for all previous events to
1955 // complete before delivering it because previous events may have the
1956 // side-effect of transferring focus to a different window and we want to
1957 // ensure that the following keys are sent to the new window.
1958 //
1959 // Suppose the user touches a button in a window then immediately presses "A".
1960 // If the button causes a pop-up window to appear then we want to ensure that
1961 // the "A" key is delivered to the new pop-up window. This is because users
1962 // often anticipate pending UI changes when typing on a keyboard.
1963 // To obtain this behavior, we must serialize key events with respect to all
1964 // prior input events.
1965 if (entry.type == EventEntry::Type::KEY) {
1966 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1967 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001968 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001969 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 }
1971
1972 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001973 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001974 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001975 BitSet32(0), getDownTime(entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976
1977 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001978 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979}
1980
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001981/**
1982 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1983 * that are currently unresponsive.
1984 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001985std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1986 const std::vector<Monitor>& monitors) const {
1987 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001988 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001989 [this](const Monitor& monitor) REQUIRES(mLock) {
1990 sp<Connection> connection =
1991 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001992 if (connection == nullptr) {
1993 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001994 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001995 return false;
1996 }
1997 if (!connection->responsive) {
1998 ALOGW("Unresponsive monitor %s will not get the new gesture",
1999 connection->inputChannel->getName().c_str());
2000 return false;
2001 }
2002 return true;
2003 });
2004 return responsiveMonitors;
2005}
2006
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002007InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
2008 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
2009 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002010 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011
Michael Wrightd02c5b62014-02-10 15:10:22 -08002012 // For security reasons, we defer updating the touch state until we are sure that
2013 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002014 const int32_t displayId = entry.displayId;
2015 const int32_t action = entry.action;
2016 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017
2018 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002019 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
chaviw98318de2021-05-19 16:45:23 -05002020 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2021 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002022
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002023 // Copy current touch state into tempTouchState.
2024 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2025 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002026 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002027 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002028 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2029 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002030 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002031 }
2032
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002033 bool isSplit = tempTouchState.split;
2034 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2035 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2036 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002037
2038 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2039 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2040 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2041 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2042 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002043 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044 bool wrongDevice = false;
2045 if (newGesture) {
2046 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002047 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002048 ALOGI("Dropping event because a pointer for a different device is already down "
2049 "in display %" PRId32,
2050 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002051 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002052 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053 switchedDevice = false;
2054 wrongDevice = true;
2055 goto Failed;
2056 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002057 tempTouchState.reset();
2058 tempTouchState.down = down;
2059 tempTouchState.deviceId = entry.deviceId;
2060 tempTouchState.source = entry.source;
2061 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002063 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002064 ALOGI("Dropping move event because a pointer for a different device is already active "
2065 "in display %" PRId32,
2066 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002067 // TODO: test multiple simultaneous input streams.
Prabir Pradhan5735a322022-04-11 17:23:34 +00002068 injectionResult = InputEventInjectionResult::FAILED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002069 switchedDevice = false;
2070 wrongDevice = true;
2071 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 }
2073
2074 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2075 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2076
Garfield Tan00f511d2019-06-12 16:55:40 -07002077 int32_t x;
2078 int32_t y;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002079 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002080 // Always dispatch mouse events to cursor position.
2081 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002082 x = int32_t(entry.xCursorPosition);
2083 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002084 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002085 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2086 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002087 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002088 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002089 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002090 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002091 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002092
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002094 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002095 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2096 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002097 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002098 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002099 }
2100
Prabir Pradhan5735a322022-04-11 17:23:34 +00002101 // Verify targeted injection.
2102 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2103 ALOGW("Dropping injected touch event: %s", (*err).c_str());
2104 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2105 newTouchedWindowHandle = nullptr;
2106 goto Failed;
2107 }
2108
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002109 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002110 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002111 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2112 // New window supports splitting, but we should never split mouse events.
2113 isSplit = !isFromMouse;
2114 } else if (isSplit) {
2115 // New window does not support splitting but we have already split events.
2116 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002117 newTouchedWindowHandle = nullptr;
2118 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002119 } else {
2120 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002121 // be delivered to a new window which supports split touch. Pointers from a mouse device
2122 // should never be split.
2123 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002124 }
2125
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002126 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002127 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002128 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2129 newHoverWindowHandle = nullptr;
2130 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002131 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002132 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002133 }
2134
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002135 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002136 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002137 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002138 // Process the foreground window first so that it is the first to receive the event.
2139 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002140 }
2141
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002142 if (newTouchedWindows.empty()) {
2143 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2144 x, y, displayId);
2145 injectionResult = InputEventInjectionResult::FAILED;
2146 goto Failed;
2147 }
2148
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002149 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2150 const WindowInfo& info = *windowHandle->getInfo();
2151
Prabir Pradhan5735a322022-04-11 17:23:34 +00002152 // Skip spy window targets that are not valid for targeted injection.
2153 if (const auto err = verifyTargetedInjection(windowHandle, entry); err) {
2154 continue;
2155 }
2156
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002157 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002158 ALOGI("Not sending touch event to %s because it is paused",
2159 windowHandle->getName().c_str());
2160 continue;
2161 }
2162
2163 // Ensure the window has a connection and the connection is responsive
2164 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2165 if (!isResponsive) {
2166 ALOGW("Not sending touch gesture to %s because it is not responsive",
2167 windowHandle->getName().c_str());
2168 continue;
2169 }
2170
2171 // Drop events that can't be trusted due to occlusion
Hani Kazmi3ce9c3a2022-04-25 09:40:23 +00002172 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(windowHandle, x, y);
2173 if (!isTouchTrustedLocked(occlusionInfo)) {
2174 if (DEBUG_TOUCH_OCCLUSION) {
2175 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2176 for (const auto& log : occlusionInfo.debugInfo) {
2177 ALOGD("%s", log.c_str());
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002178 }
2179 }
Hani Kazmi3ce9c3a2022-04-25 09:40:23 +00002180 ALOGW("Dropping untrusted touch event due to %s/%d",
2181 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2182 continue;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002183 }
2184
2185 // Drop touch events if requested by input feature
2186 if (shouldDropInput(entry, windowHandle)) {
2187 continue;
2188 }
2189
2190 // Set target flags.
2191 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2192
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002193 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2194 // There should only be one touched window that can be "foreground" for the pointer.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002195 targetFlags |= InputTarget::FLAG_FOREGROUND;
2196 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002197
2198 if (isSplit) {
2199 targetFlags |= InputTarget::FLAG_SPLIT;
2200 }
2201 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2202 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2203 } else if (isWindowObscuredLocked(windowHandle)) {
2204 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2205 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002206
2207 // Update the temporary touch state.
2208 BitSet32 pointerIds;
2209 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002210 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002211 pointerIds.markBit(pointerId);
2212 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002213
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002214 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
2215 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002217
2218 // If any existing window is pilfering pointers from newly added window, remove it
2219 BitSet32 canceledPointers = BitSet32(0);
2220 for (const TouchedWindow& window : tempTouchState.windows) {
2221 if (window.isPilferingPointers) {
2222 canceledPointers |= window.pointerIds;
2223 }
2224 }
2225 tempTouchState.cancelPointersForNonPilferingWindows(canceledPointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226 } else {
2227 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2228
2229 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002230 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002231 if (DEBUG_FOCUS) {
2232 ALOGD("Dropping event because the pointer is not down or we previously "
2233 "dropped the pointer down event in display %" PRId32,
2234 displayId);
2235 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002236 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237 goto Failed;
2238 }
2239
arthurhung6d4bed92021-03-17 11:59:33 +08002240 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002241
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002243 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002244 tempTouchState.isSlippery()) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002245 const int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2246 const int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247
Prabir Pradhand65552b2021-10-07 11:23:50 -07002248 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002249 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002250 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002251 newTouchedWindowHandle =
2252 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002253
Prabir Pradhan5735a322022-04-11 17:23:34 +00002254 // Verify targeted injection.
2255 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2256 ALOGW("Dropping injected event: %s", (*err).c_str());
2257 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2258 newTouchedWindowHandle = nullptr;
2259 goto Failed;
2260 }
2261
Vishnu Nair062a8672021-09-03 16:07:44 -07002262 // Drop touch events if requested by input feature
2263 if (newTouchedWindowHandle != nullptr &&
2264 shouldDropInput(entry, newTouchedWindowHandle)) {
2265 newTouchedWindowHandle = nullptr;
2266 }
2267
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002268 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2269 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002270 if (DEBUG_FOCUS) {
2271 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2272 oldTouchedWindowHandle->getName().c_str(),
2273 newTouchedWindowHandle->getName().c_str(), displayId);
2274 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002276 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2277 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2278 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279
2280 // Make a slippery entrance into the new window.
2281 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002282 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 }
2284
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002285 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
2286 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
2287 targetFlags |= InputTarget::FLAG_FOREGROUND;
2288 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289 if (isSplit) {
2290 targetFlags |= InputTarget::FLAG_SPLIT;
2291 }
2292 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2293 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002294 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2295 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296 }
2297
2298 BitSet32 pointerIds;
2299 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002300 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002302 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2303 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304 }
2305 }
2306 }
2307
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002308 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002310 // Let the previous window know that the hover sequence is over, unless we already did
2311 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002312 if (mLastHoverWindowHandle != nullptr &&
2313 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2314 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002315 if (DEBUG_HOVER) {
2316 ALOGD("Sending hover exit event to window %s.",
2317 mLastHoverWindowHandle->getName().c_str());
2318 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002319 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2320 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321 }
2322
Garfield Tandf26e862020-07-01 20:18:19 -07002323 // Let the new window know that the hover sequence is starting, unless we already did it
2324 // when dispatching it as is to newTouchedWindowHandle.
2325 if (newHoverWindowHandle != nullptr &&
2326 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2327 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002328 if (DEBUG_HOVER) {
2329 ALOGD("Sending hover enter event to window %s.",
2330 newHoverWindowHandle->getName().c_str());
2331 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002332 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2333 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2334 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335 }
2336 }
2337
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002338 // Ensure that we have at least one foreground window or at least one window that cannot be a
2339 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2340 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2341 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002342 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2343 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002344 return !canReceiveForegroundTouches(
2345 *touchedWindow.windowHandle->getInfo()) ||
2346 (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002347 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002348 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2349 displayId, entry.getDescription().c_str());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002350 injectionResult = InputEventInjectionResult::FAILED;
2351 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 }
2353
Prabir Pradhan5735a322022-04-11 17:23:34 +00002354 // Ensure that all touched windows are valid for injection.
2355 if (entry.injectionState != nullptr) {
2356 std::string errs;
2357 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
2358 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2359 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2360 // dispatched to any uid, since the coords will be zeroed out later.
2361 continue;
2362 }
2363 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2364 if (err) errs += "\n - " + *err;
2365 }
2366 if (!errs.empty()) {
2367 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2368 "%d:%s",
2369 *entry.injectionState->targetUid, errs.c_str());
2370 injectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2371 goto Failed;
2372 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002373 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002374
Michael Wrightd02c5b62014-02-10 15:10:22 -08002375 // Check whether windows listening for outside touches are owned by the same UID. If it is
2376 // set the policy flag that we will not reveal coordinate information to this window.
2377 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002378 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002379 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002380 if (foregroundWindowHandle) {
2381 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002382 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002383 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002384 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2385 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2386 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002387 InputTarget::FLAG_ZERO_COORDS,
2388 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002390 }
2391 }
2392 }
2393 }
2394
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395 // If this is the first pointer going down and the touched window has a wallpaper
2396 // then also add the touched wallpaper windows so they are locked in for the duration
2397 // of the touch gesture.
2398 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2399 // engine only supports touch events. We would need to add a mechanism similar
2400 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2401 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002402 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002403 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002404 if (foregroundWindowHandle &&
2405 foregroundWindowHandle->getInfo()->inputConfig.test(
2406 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002407 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002408 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002409 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2410 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002411 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002412 windowHandle->getInfo()->inputConfig.test(
2413 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002414 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002415 .addOrUpdateWindow(windowHandle,
2416 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2417 InputTarget::
2418 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2419 InputTarget::FLAG_DISPATCH_AS_IS,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002420 BitSet32(0), entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421 }
2422 }
2423 }
2424 }
2425
2426 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002427 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002428
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002429 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002430 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002431 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2432 inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433 }
2434
2435 // Drop the outside or hover touch windows since we will not care about them
2436 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002437 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002438
2439Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002441 if (!wrongDevice) {
2442 if (switchedDevice) {
2443 if (DEBUG_FOCUS) {
2444 ALOGD("Conflicting pointer actions: Switched to a different device.");
2445 }
2446 *outConflictingPointerActions = true;
2447 }
2448
2449 if (isHoverAction) {
2450 // Started hovering, therefore no longer down.
2451 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002452 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002453 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2454 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002455 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002456 *outConflictingPointerActions = true;
2457 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002458 tempTouchState.reset();
2459 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2460 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2461 tempTouchState.deviceId = entry.deviceId;
2462 tempTouchState.source = entry.source;
2463 tempTouchState.displayId = displayId;
2464 }
2465 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2466 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2467 // All pointers up or canceled.
2468 tempTouchState.reset();
2469 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2470 // First pointer went down.
2471 if (oldState && oldState->down) {
2472 if (DEBUG_FOCUS) {
2473 ALOGD("Conflicting pointer actions: Down received while already down.");
2474 }
2475 *outConflictingPointerActions = true;
2476 }
2477 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2478 // One pointer went up.
2479 if (isSplit) {
2480 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2481 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002483 for (size_t i = 0; i < tempTouchState.windows.size();) {
2484 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2485 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2486 touchedWindow.pointerIds.clearBit(pointerId);
2487 if (touchedWindow.pointerIds.isEmpty()) {
2488 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2489 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002492 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002494 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002495 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002496
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002497 // Save changes unless the action was scroll in which case the temporary touch
2498 // state was only valid for this one action.
2499 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2500 if (tempTouchState.displayId >= 0) {
2501 mTouchStatesByDisplay[displayId] = tempTouchState;
2502 } else {
2503 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002505 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002506
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002507 // Update hover state.
2508 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002509 }
2510
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511 return injectionResult;
2512}
2513
arthurhung6d4bed92021-03-17 11:59:33 +08002514void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002515 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2516 // have an explicit reason to support it.
2517 constexpr bool isStylus = false;
2518
chaviw98318de2021-05-19 16:45:23 -05002519 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002520 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002521 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002522 if (dropWindow) {
2523 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002524 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002525 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002526 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002527 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002528 }
2529 mDragState.reset();
2530}
2531
2532void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002533 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002534 return;
2535 }
2536
arthurhung6d4bed92021-03-17 11:59:33 +08002537 if (!mDragState->isStartDrag) {
2538 mDragState->isStartDrag = true;
2539 mDragState->isStylusButtonDownAtStart =
2540 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2541 }
2542
Arthur Hung54745652022-04-20 07:17:41 +00002543 // Find the pointer index by id.
2544 int32_t pointerIndex = 0;
2545 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2546 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2547 if (pointerProperties.id == mDragState->pointerId) {
2548 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002549 }
Arthur Hung54745652022-04-20 07:17:41 +00002550 }
arthurhung6d4bed92021-03-17 11:59:33 +08002551
Arthur Hung54745652022-04-20 07:17:41 +00002552 if (uint32_t(pointerIndex) == entry.pointerCount) {
2553 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002554 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002555 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002556 return;
2557 }
2558
2559 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2560 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2561 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2562
2563 switch (maskedAction) {
2564 case AMOTION_EVENT_ACTION_MOVE: {
2565 // Handle the special case : stylus button no longer pressed.
2566 bool isStylusButtonDown =
2567 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2568 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2569 finishDragAndDrop(entry.displayId, x, y);
2570 return;
2571 }
2572
2573 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2574 // until we have an explicit reason to support it.
2575 constexpr bool isStylus = false;
2576
2577 const sp<WindowInfoHandle> hoverWindowHandle =
2578 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2579 isStylus, false /*addOutsideTargets*/,
2580 true /*ignoreDragWindow*/);
2581 // enqueue drag exit if needed.
2582 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2583 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2584 if (mDragState->dragHoverWindowHandle != nullptr) {
2585 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2586 y);
2587 }
2588 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2589 }
2590 // enqueue drag location if needed.
2591 if (hoverWindowHandle != nullptr) {
2592 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2593 }
2594 break;
2595 }
2596
2597 case AMOTION_EVENT_ACTION_POINTER_UP:
2598 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2599 break;
2600 }
2601 // The drag pointer is up.
2602 [[fallthrough]];
2603 case AMOTION_EVENT_ACTION_UP:
2604 finishDragAndDrop(entry.displayId, x, y);
2605 break;
2606 case AMOTION_EVENT_ACTION_CANCEL: {
2607 ALOGD("Receiving cancel when drag and drop.");
2608 sendDropWindowCommandLocked(nullptr, 0, 0);
2609 mDragState.reset();
2610 break;
2611 }
arthurhungb89ccb02020-12-30 16:19:01 +08002612 }
2613}
2614
chaviw98318de2021-05-19 16:45:23 -05002615void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002616 int32_t targetFlags, BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002617 std::optional<nsecs_t> firstDownTimeInTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002618 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002619 std::vector<InputTarget>::iterator it =
2620 std::find_if(inputTargets.begin(), inputTargets.end(),
2621 [&windowHandle](const InputTarget& inputTarget) {
2622 return inputTarget.inputChannel->getConnectionToken() ==
2623 windowHandle->getToken();
2624 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002625
chaviw98318de2021-05-19 16:45:23 -05002626 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002627
2628 if (it == inputTargets.end()) {
2629 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002630 std::shared_ptr<InputChannel> inputChannel =
2631 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002632 if (inputChannel == nullptr) {
2633 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2634 return;
2635 }
2636 inputTarget.inputChannel = inputChannel;
2637 inputTarget.flags = targetFlags;
2638 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002639 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002640 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2641 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002642 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002643 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002644 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002645 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002646 inputTargets.push_back(inputTarget);
2647 it = inputTargets.end() - 1;
2648 }
2649
2650 ALOG_ASSERT(it->flags == targetFlags);
2651 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2652
chaviw1ff3d1e2020-07-01 15:53:47 -07002653 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002654}
2655
Michael Wright3dd60e22019-03-27 22:06:44 +00002656void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002657 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002658 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2659 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002660
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002661 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2662 InputTarget target;
2663 target.inputChannel = monitor.inputChannel;
2664 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002665 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2666 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002667 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2668 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002669 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002670 target.setDefaultPointerTransform(target.displayTransform);
2671 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002672 }
2673}
2674
Robert Carrc9bf1d32020-04-13 17:21:08 -07002675/**
2676 * Indicate whether one window handle should be considered as obscuring
2677 * another window handle. We only check a few preconditions. Actually
2678 * checking the bounds is left to the caller.
2679 */
chaviw98318de2021-05-19 16:45:23 -05002680static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2681 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002682 // Compare by token so cloned layers aren't counted
2683 if (haveSameToken(windowHandle, otherHandle)) {
2684 return false;
2685 }
2686 auto info = windowHandle->getInfo();
2687 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002688 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002689 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002690 } else if (otherInfo->alpha == 0 &&
2691 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002692 // Those act as if they were invisible, so we don't need to flag them.
2693 // We do want to potentially flag touchable windows even if they have 0
2694 // opacity, since they can consume touches and alter the effects of the
2695 // user interaction (eg. apps that rely on
2696 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2697 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2698 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002699 } else if (info->ownerUid == otherInfo->ownerUid) {
2700 // If ownerUid is the same we don't generate occlusion events as there
2701 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002702 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002703 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002704 return false;
2705 } else if (otherInfo->displayId != info->displayId) {
2706 return false;
2707 }
2708 return true;
2709}
2710
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002711/**
2712 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2713 * untrusted, one should check:
2714 *
2715 * 1. If result.hasBlockingOcclusion is true.
2716 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2717 * BLOCK_UNTRUSTED.
2718 *
2719 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2720 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2721 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2722 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2723 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2724 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2725 *
2726 * If neither of those is true, then it means the touch can be allowed.
2727 */
2728InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002729 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2730 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002731 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002732 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002733 TouchOcclusionInfo info;
2734 info.hasBlockingOcclusion = false;
2735 info.obscuringOpacity = 0;
2736 info.obscuringUid = -1;
2737 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002738 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002739 if (windowHandle == otherHandle) {
2740 break; // All future windows are below us. Exit early.
2741 }
chaviw98318de2021-05-19 16:45:23 -05002742 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002743 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2744 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002745 if (DEBUG_TOUCH_OCCLUSION) {
2746 info.debugInfo.push_back(
2747 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2748 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002749 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2750 // we perform the checks below to see if the touch can be propagated or not based on the
2751 // window's touch occlusion mode
2752 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2753 info.hasBlockingOcclusion = true;
2754 info.obscuringUid = otherInfo->ownerUid;
2755 info.obscuringPackage = otherInfo->packageName;
2756 break;
2757 }
2758 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2759 uint32_t uid = otherInfo->ownerUid;
2760 float opacity =
2761 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2762 // Given windows A and B:
2763 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2764 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2765 opacityByUid[uid] = opacity;
2766 if (opacity > info.obscuringOpacity) {
2767 info.obscuringOpacity = opacity;
2768 info.obscuringUid = uid;
2769 info.obscuringPackage = otherInfo->packageName;
2770 }
2771 }
2772 }
2773 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002774 if (DEBUG_TOUCH_OCCLUSION) {
2775 info.debugInfo.push_back(
2776 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2777 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002778 return info;
2779}
2780
chaviw98318de2021-05-19 16:45:23 -05002781std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002782 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002783 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2784 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2785 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2786 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002787 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2788 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2789 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2790 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2791 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002792 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002793 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002794}
2795
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002796bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2797 if (occlusionInfo.hasBlockingOcclusion) {
2798 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2799 occlusionInfo.obscuringUid);
2800 return false;
2801 }
2802 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2803 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2804 "%.2f, maximum allowed = %.2f)",
2805 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2806 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2807 return false;
2808 }
2809 return true;
2810}
2811
chaviw98318de2021-05-19 16:45:23 -05002812bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002813 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002814 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002815 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2816 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002817 if (windowHandle == otherHandle) {
2818 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002819 }
chaviw98318de2021-05-19 16:45:23 -05002820 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002821 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002822 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823 return true;
2824 }
2825 }
2826 return false;
2827}
2828
chaviw98318de2021-05-19 16:45:23 -05002829bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002830 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002831 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2832 const WindowInfo* windowInfo = windowHandle->getInfo();
2833 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002834 if (windowHandle == otherHandle) {
2835 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002836 }
chaviw98318de2021-05-19 16:45:23 -05002837 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002838 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002839 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002840 return true;
2841 }
2842 }
2843 return false;
2844}
2845
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002846std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002847 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002848 if (applicationHandle != nullptr) {
2849 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002850 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851 } else {
2852 return applicationHandle->getName();
2853 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002854 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002855 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002856 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002857 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858 }
2859}
2860
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002861void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002862 if (!isUserActivityEvent(eventEntry)) {
2863 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002864 return;
2865 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002866 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002867 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002868 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002869 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002870 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002871 if (DEBUG_DISPATCH_CYCLE) {
2872 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002874 return;
2875 }
2876 }
2877
2878 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002879 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002880 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002881 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2882 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002883 return;
2884 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002885
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002886 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002887 eventType = USER_ACTIVITY_EVENT_TOUCH;
2888 }
2889 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002890 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002891 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002892 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2893 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002894 return;
2895 }
2896 eventType = USER_ACTIVITY_EVENT_BUTTON;
2897 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002898 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002899 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002900 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002901 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002902 break;
2903 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002904 }
2905
Prabir Pradhancef936d2021-07-21 16:17:52 +00002906 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2907 REQUIRES(mLock) {
2908 scoped_unlock unlock(mLock);
2909 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2910 };
2911 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002912}
2913
2914void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002915 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002916 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002917 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002918 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002919 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002920 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002921 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002922 ATRACE_NAME(message.c_str());
2923 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002924 if (DEBUG_DISPATCH_CYCLE) {
2925 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2926 "globalScaleFactor=%f, pointerIds=0x%x %s",
2927 connection->getInputChannelName().c_str(), inputTarget.flags,
2928 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2929 inputTarget.getPointerInfoString().c_str());
2930 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931
2932 // Skip this event if the connection status is not normal.
2933 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002934 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002935 if (DEBUG_DISPATCH_CYCLE) {
2936 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002937 connection->getInputChannelName().c_str(),
2938 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940 return;
2941 }
2942
2943 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002944 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2945 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2946 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002947 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002948
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002949 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002950 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002951 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
2952 "Splitting motion events requires a down time to be set for the "
2953 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002954 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002955 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
2956 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002957 if (!splitMotionEntry) {
2958 return; // split event was dropped
2959 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002960 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2961 std::string reason = std::string("reason=pointer cancel on split window");
2962 android_log_event_list(LOGTAG_INPUT_CANCEL)
2963 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2964 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002965 if (DEBUG_FOCUS) {
2966 ALOGD("channel '%s' ~ Split motion event.",
2967 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002968 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002969 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002970 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2971 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972 return;
2973 }
2974 }
2975
2976 // Not splitting. Enqueue dispatch entries for the event as is.
2977 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2978}
2979
2980void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002981 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002982 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002983 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002984 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002985 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002986 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002987 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002988 ATRACE_NAME(message.c_str());
2989 }
2990
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002991 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002992
2993 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002994 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002995 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002996 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002997 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002998 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002999 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003000 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003001 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003002 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003003 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003004 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003005 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003006
3007 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003008 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003009 startDispatchCycleLocked(currentTime, connection);
3010 }
3011}
3012
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003013void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003014 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003015 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003016 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003017 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003018 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3019 connection->getInputChannelName().c_str(),
3020 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003021 ATRACE_NAME(message.c_str());
3022 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003023 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003024 if (!(inputTargetFlags & dispatchMode)) {
3025 return;
3026 }
3027 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
3028
3029 // This is a new event.
3030 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003031 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003032 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003034 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3035 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003036 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003037 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003038 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003039 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003040 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003041 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003042 dispatchEntry->resolvedAction = keyEntry.action;
3043 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003044
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003045 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3046 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003047 if (DEBUG_DISPATCH_CYCLE) {
3048 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3049 "event",
3050 connection->getInputChannelName().c_str());
3051 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003052 return; // skip the inconsistent event
3053 }
3054 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003057 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003058 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003059 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3060 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3061 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3062 static_cast<int32_t>(IdGenerator::Source::OTHER);
3063 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003064 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3065 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3066 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3067 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3068 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3069 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3070 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3071 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3072 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3073 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3074 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003075 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003076 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003077 }
3078 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003079 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3080 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003081 if (DEBUG_DISPATCH_CYCLE) {
3082 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3083 "enter event",
3084 connection->getInputChannelName().c_str());
3085 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003086 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3087 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003088 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003090
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003091 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003092 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3093 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3094 }
3095 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3096 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3097 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003099 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3100 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003101 if (DEBUG_DISPATCH_CYCLE) {
3102 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3103 "event",
3104 connection->getInputChannelName().c_str());
3105 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003106 return; // skip the inconsistent event
3107 }
3108
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003109 dispatchEntry->resolvedEventId =
3110 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3111 ? mIdGenerator.nextId()
3112 : motionEntry.id;
3113 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3114 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3115 ") to MotionEvent(id=0x%" PRIx32 ").",
3116 motionEntry.id, dispatchEntry->resolvedEventId);
3117 ATRACE_NAME(message.c_str());
3118 }
3119
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003120 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3121 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3122 // Skip reporting pointer down outside focus to the policy.
3123 break;
3124 }
3125
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003126 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003127 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003128
3129 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003130 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003131 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003132 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003133 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3134 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003135 break;
3136 }
Chris Yef59a2f42020-10-16 12:55:26 -07003137 case EventEntry::Type::SENSOR: {
3138 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3139 break;
3140 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003141 case EventEntry::Type::CONFIGURATION_CHANGED:
3142 case EventEntry::Type::DEVICE_RESET: {
3143 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003144 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003145 break;
3146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 }
3148
3149 // Remember that we are waiting for this dispatch to complete.
3150 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003151 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152 }
3153
3154 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003155 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003156 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003157}
3158
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003159/**
3160 * This function is purely for debugging. It helps us understand where the user interaction
3161 * was taking place. For example, if user is touching launcher, we will see a log that user
3162 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3163 * We will see both launcher and wallpaper in that list.
3164 * Once the interaction with a particular set of connections starts, no new logs will be printed
3165 * until the set of interacted connections changes.
3166 *
3167 * The following items are skipped, to reduce the logspam:
3168 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3169 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3170 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3171 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3172 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003173 */
3174void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3175 const std::vector<InputTarget>& targets) {
3176 // Skip ACTION_UP events, and all events other than keys and motions
3177 if (entry.type == EventEntry::Type::KEY) {
3178 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3179 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3180 return;
3181 }
3182 } else if (entry.type == EventEntry::Type::MOTION) {
3183 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3184 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3185 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3186 return;
3187 }
3188 } else {
3189 return; // Not a key or a motion
3190 }
3191
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003192 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003193 std::vector<sp<Connection>> newConnections;
3194 for (const InputTarget& target : targets) {
3195 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3196 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3197 continue; // Skip windows that receive ACTION_OUTSIDE
3198 }
3199
3200 sp<IBinder> token = target.inputChannel->getConnectionToken();
3201 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003202 if (connection == nullptr) {
3203 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003204 }
3205 newConnectionTokens.insert(std::move(token));
3206 newConnections.emplace_back(connection);
3207 }
3208 if (newConnectionTokens == mInteractionConnectionTokens) {
3209 return; // no change
3210 }
3211 mInteractionConnectionTokens = newConnectionTokens;
3212
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003213 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003214 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003215 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003216 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003217 std::string message = "Interaction with: " + targetList;
3218 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003219 message += "<none>";
3220 }
3221 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3222}
3223
chaviwfd6d3512019-03-25 13:23:49 -07003224void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003225 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003226 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003227 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3228 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003229 return;
3230 }
3231
Vishnu Nairc519ff72021-01-21 08:23:08 -08003232 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003233 if (focusedToken == token) {
3234 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003235 return;
3236 }
3237
Prabir Pradhancef936d2021-07-21 16:17:52 +00003238 auto command = [this, token]() REQUIRES(mLock) {
3239 scoped_unlock unlock(mLock);
3240 mPolicy->onPointerDownOutsideFocus(token);
3241 };
3242 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243}
3244
3245void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003246 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003247 if (ATRACE_ENABLED()) {
3248 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003249 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003250 ATRACE_NAME(message.c_str());
3251 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003252 if (DEBUG_DISPATCH_CYCLE) {
3253 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3254 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003256 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003257 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003258 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003259 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003260 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261
3262 // Publish the event.
3263 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003264 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3265 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003266 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003267 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3268 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003270 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003271 status = connection->inputPublisher
3272 .publishKeyEvent(dispatchEntry->seq,
3273 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3274 keyEntry.source, keyEntry.displayId,
3275 std::move(hmac), dispatchEntry->resolvedAction,
3276 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3277 keyEntry.scanCode, keyEntry.metaState,
3278 keyEntry.repeatCount, keyEntry.downTime,
3279 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003280 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281 }
3282
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003283 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003284 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003286 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003287 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003288
chaviw82357092020-01-28 13:13:06 -08003289 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003290 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003291 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3292 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003293 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003294 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3295 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003296 // Don't apply window scale here since we don't want scale to affect raw
3297 // coordinates. The scale will be sent back to the client and applied
3298 // later when requesting relative coordinates.
3299 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3300 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003301 }
3302 usingCoords = scaledCoords;
3303 }
3304 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003305 // We don't want the dispatch target to know.
3306 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003307 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003308 scaledCoords[i].clear();
3309 }
3310 usingCoords = scaledCoords;
3311 }
3312 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003313
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003314 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003315
3316 // Publish the motion event.
3317 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003318 .publishMotionEvent(dispatchEntry->seq,
3319 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003320 motionEntry.deviceId, motionEntry.source,
3321 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003322 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003323 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003324 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003325 motionEntry.edgeFlags, motionEntry.metaState,
3326 motionEntry.buttonState,
3327 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003328 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003329 motionEntry.xPrecision, motionEntry.yPrecision,
3330 motionEntry.xCursorPosition,
3331 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003332 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003333 motionEntry.downTime, motionEntry.eventTime,
3334 motionEntry.pointerCount,
3335 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003336 break;
3337 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003338
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003339 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003340 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003341 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003342 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003343 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003344 break;
3345 }
3346
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003347 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3348 const TouchModeEntry& touchModeEntry =
3349 static_cast<const TouchModeEntry&>(eventEntry);
3350 status = connection->inputPublisher
3351 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3352 touchModeEntry.inTouchMode);
3353
3354 break;
3355 }
3356
Prabir Pradhan99987712020-11-10 18:43:05 -08003357 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3358 const auto& captureEntry =
3359 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3360 status = connection->inputPublisher
3361 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003362 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003363 break;
3364 }
3365
arthurhungb89ccb02020-12-30 16:19:01 +08003366 case EventEntry::Type::DRAG: {
3367 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3368 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3369 dragEntry.id, dragEntry.x,
3370 dragEntry.y,
3371 dragEntry.isExiting);
3372 break;
3373 }
3374
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003375 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003376 case EventEntry::Type::DEVICE_RESET:
3377 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003378 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003379 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003380 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003381 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382 }
3383
3384 // Check the result.
3385 if (status) {
3386 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003387 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003388 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003389 "This is unexpected because the wait queue is empty, so the pipe "
3390 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003391 "event to it, status=%s(%d)",
3392 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3393 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3395 } else {
3396 // Pipe is full and we are waiting for the app to finish process some events
3397 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003398 if (DEBUG_DISPATCH_CYCLE) {
3399 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3400 "waiting for the application to catch up",
3401 connection->getInputChannelName().c_str());
3402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003403 }
3404 } else {
3405 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003406 "status=%s(%d)",
3407 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3408 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3410 }
3411 return;
3412 }
3413
3414 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003415 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3416 connection->outboundQueue.end(),
3417 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003418 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003419 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003420 if (connection->responsive) {
3421 mAnrTracker.insert(dispatchEntry->timeoutTime,
3422 connection->inputChannel->getConnectionToken());
3423 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003424 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425 }
3426}
3427
chaviw09c8d2d2020-08-24 15:48:26 -07003428std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3429 size_t size;
3430 switch (event.type) {
3431 case VerifiedInputEvent::Type::KEY: {
3432 size = sizeof(VerifiedKeyEvent);
3433 break;
3434 }
3435 case VerifiedInputEvent::Type::MOTION: {
3436 size = sizeof(VerifiedMotionEvent);
3437 break;
3438 }
3439 }
3440 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3441 return mHmacKeyManager.sign(start, size);
3442}
3443
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003444const std::array<uint8_t, 32> InputDispatcher::getSignature(
3445 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003446 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3447 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003448 // Only sign events up and down events as the purely move events
3449 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003450 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003451 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003452
3453 VerifiedMotionEvent verifiedEvent =
3454 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3455 verifiedEvent.actionMasked = actionMasked;
3456 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3457 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003458}
3459
3460const std::array<uint8_t, 32> InputDispatcher::getSignature(
3461 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3462 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3463 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3464 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003465 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003466}
3467
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003469 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003470 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003471 if (DEBUG_DISPATCH_CYCLE) {
3472 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3473 connection->getInputChannelName().c_str(), seq, toString(handled));
3474 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003476 if (connection->status == Connection::Status::BROKEN ||
3477 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003478 return;
3479 }
3480
3481 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003482 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3483 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3484 };
3485 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486}
3487
3488void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003489 const sp<Connection>& connection,
3490 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003491 if (DEBUG_DISPATCH_CYCLE) {
3492 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3493 connection->getInputChannelName().c_str(), toString(notify));
3494 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003495
3496 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003497 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003498 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003499 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003500 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501
3502 // The connection appears to be unrecoverably broken.
3503 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003504 if (connection->status == Connection::Status::NORMAL) {
3505 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506
3507 if (notify) {
3508 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003509 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3510 connection->getInputChannelName().c_str());
3511
3512 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003513 scoped_unlock unlock(mLock);
3514 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3515 };
3516 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517 }
3518 }
3519}
3520
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003521void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3522 while (!queue.empty()) {
3523 DispatchEntry* dispatchEntry = queue.front();
3524 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003525 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526 }
3527}
3528
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003529void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003530 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003531 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 }
3533 delete dispatchEntry;
3534}
3535
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003536int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3537 std::scoped_lock _l(mLock);
3538 sp<Connection> connection = getConnectionLocked(connectionToken);
3539 if (connection == nullptr) {
3540 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3541 connectionToken.get(), events);
3542 return 0; // remove the callback
3543 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003544
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003545 bool notify;
3546 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3547 if (!(events & ALOOPER_EVENT_INPUT)) {
3548 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3549 "events=0x%x",
3550 connection->getInputChannelName().c_str(), events);
3551 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003552 }
3553
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003554 nsecs_t currentTime = now();
3555 bool gotOne = false;
3556 status_t status = OK;
3557 for (;;) {
3558 Result<InputPublisher::ConsumerResponse> result =
3559 connection->inputPublisher.receiveConsumerResponse();
3560 if (!result.ok()) {
3561 status = result.error().code();
3562 break;
3563 }
3564
3565 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3566 const InputPublisher::Finished& finish =
3567 std::get<InputPublisher::Finished>(*result);
3568 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3569 finish.consumeTime);
3570 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003571 if (shouldReportMetricsForConnection(*connection)) {
3572 const InputPublisher::Timeline& timeline =
3573 std::get<InputPublisher::Timeline>(*result);
3574 mLatencyTracker
3575 .trackGraphicsLatency(timeline.inputEventId,
3576 connection->inputChannel->getConnectionToken(),
3577 std::move(timeline.graphicsTimeline));
3578 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003579 }
3580 gotOne = true;
3581 }
3582 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003583 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003584 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003585 return 1;
3586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003587 }
3588
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003589 notify = status != DEAD_OBJECT || !connection->monitor;
3590 if (notify) {
3591 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3592 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3593 status);
3594 }
3595 } else {
3596 // Monitor channels are never explicitly unregistered.
3597 // We do it automatically when the remote endpoint is closed so don't warn about them.
3598 const bool stillHaveWindowHandle =
3599 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3600 notify = !connection->monitor && stillHaveWindowHandle;
3601 if (notify) {
3602 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3603 connection->getInputChannelName().c_str(), events);
3604 }
3605 }
3606
3607 // Remove the channel.
3608 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3609 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610}
3611
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003612void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003613 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003614 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003615 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616 }
3617}
3618
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003619void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003620 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003621 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003622 for (const Monitor& monitor : monitors) {
3623 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003624 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003625 }
3626}
3627
Michael Wrightd02c5b62014-02-10 15:10:22 -08003628void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003629 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003630 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003631 if (connection == nullptr) {
3632 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003634
3635 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636}
3637
3638void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3639 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003640 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641 return;
3642 }
3643
3644 nsecs_t currentTime = now();
3645
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003646 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003647 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003649 if (cancelationEvents.empty()) {
3650 return;
3651 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003652 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3653 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3654 "with reality: %s, mode=%d.",
3655 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3656 options.mode);
3657 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003658
Arthur Hungb3307ee2021-10-14 10:57:37 +00003659 std::string reason = std::string("reason=").append(options.reason);
3660 android_log_event_list(LOGTAG_INPUT_CANCEL)
3661 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3662
Svet Ganov5d3bc372020-01-26 23:11:07 -08003663 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003664 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003665 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3666 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003667 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003668 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003669 target.globalScaleFactor = windowInfo->globalScaleFactor;
3670 }
3671 target.inputChannel = connection->inputChannel;
3672 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3673
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003674 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003675 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003676 switch (cancelationEventEntry->type) {
3677 case EventEntry::Type::KEY: {
3678 logOutboundKeyDetails("cancel - ",
3679 static_cast<const KeyEntry&>(*cancelationEventEntry));
3680 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003682 case EventEntry::Type::MOTION: {
3683 logOutboundMotionDetails("cancel - ",
3684 static_cast<const MotionEntry&>(*cancelationEventEntry));
3685 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003686 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003687 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003688 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003689 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3690 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003691 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003692 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003693 break;
3694 }
3695 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003696 case EventEntry::Type::DEVICE_RESET:
3697 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003698 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003699 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003700 break;
3701 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702 }
3703
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003704 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3705 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003707
3708 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709}
3710
Svet Ganov5d3bc372020-01-26 23:11:07 -08003711void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003712 const nsecs_t downTime, const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003713 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003714 return;
3715 }
3716
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003717 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003718 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003719
3720 if (downEvents.empty()) {
3721 return;
3722 }
3723
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003724 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003725 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3726 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003727 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003728
3729 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003730 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003731 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3732 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003733 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003734 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003735 target.globalScaleFactor = windowInfo->globalScaleFactor;
3736 }
3737 target.inputChannel = connection->inputChannel;
3738 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3739
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003740 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003741 switch (downEventEntry->type) {
3742 case EventEntry::Type::MOTION: {
3743 logOutboundMotionDetails("down - ",
3744 static_cast<const MotionEntry&>(*downEventEntry));
3745 break;
3746 }
3747
3748 case EventEntry::Type::KEY:
3749 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003750 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003751 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003752 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003753 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003754 case EventEntry::Type::SENSOR:
3755 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003756 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003757 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003758 break;
3759 }
3760 }
3761
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003762 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3763 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003764 }
3765
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003766 startDispatchCycleLocked(downTime, connection);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003767}
3768
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003769std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003770 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771 ALOG_ASSERT(pointerIds.value != 0);
3772
3773 uint32_t splitPointerIndexMap[MAX_POINTERS];
3774 PointerProperties splitPointerProperties[MAX_POINTERS];
3775 PointerCoords splitPointerCoords[MAX_POINTERS];
3776
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003777 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003778 uint32_t splitPointerCount = 0;
3779
3780 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003781 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003783 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 uint32_t pointerId = uint32_t(pointerProperties.id);
3785 if (pointerIds.hasBit(pointerId)) {
3786 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3787 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3788 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003789 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790 splitPointerCount += 1;
3791 }
3792 }
3793
3794 if (splitPointerCount != pointerIds.count()) {
3795 // This is bad. We are missing some of the pointers that we expected to deliver.
3796 // Most likely this indicates that we received an ACTION_MOVE events that has
3797 // different pointer ids than we expected based on the previous ACTION_DOWN
3798 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3799 // in this way.
3800 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003801 "we expected there to be %d pointers. This probably means we received "
3802 "a broken sequence of pointer ids from the input device.",
3803 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003804 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 }
3806
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003807 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003808 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003809 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3810 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3812 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003813 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814 uint32_t pointerId = uint32_t(pointerProperties.id);
3815 if (pointerIds.hasBit(pointerId)) {
3816 if (pointerIds.count() == 1) {
3817 // The first/last pointer went down/up.
3818 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003819 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003820 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3821 ? AMOTION_EVENT_ACTION_CANCEL
3822 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003823 } else {
3824 // A secondary pointer went down/up.
3825 uint32_t splitPointerIndex = 0;
3826 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3827 splitPointerIndex += 1;
3828 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003829 action = maskedAction |
3830 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831 }
3832 } else {
3833 // An unrelated pointer changed.
3834 action = AMOTION_EVENT_ACTION_MOVE;
3835 }
3836 }
3837
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003838 if (action == AMOTION_EVENT_ACTION_DOWN) {
3839 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3840 "Split motion event has mismatching downTime and eventTime for "
3841 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3842 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3843 }
3844
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003845 int32_t newId = mIdGenerator.nextId();
3846 if (ATRACE_ENABLED()) {
3847 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3848 ") to MotionEvent(id=0x%" PRIx32 ").",
3849 originalMotionEntry.id, newId);
3850 ATRACE_NAME(message.c_str());
3851 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003852 std::unique_ptr<MotionEntry> splitMotionEntry =
3853 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3854 originalMotionEntry.deviceId, originalMotionEntry.source,
3855 originalMotionEntry.displayId,
3856 originalMotionEntry.policyFlags, action,
3857 originalMotionEntry.actionButton,
3858 originalMotionEntry.flags, originalMotionEntry.metaState,
3859 originalMotionEntry.buttonState,
3860 originalMotionEntry.classification,
3861 originalMotionEntry.edgeFlags,
3862 originalMotionEntry.xPrecision,
3863 originalMotionEntry.yPrecision,
3864 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003865 originalMotionEntry.yCursorPosition, splitDownTime,
3866 splitPointerCount, splitPointerProperties,
3867 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003868
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003869 if (originalMotionEntry.injectionState) {
3870 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871 splitMotionEntry->injectionState->refCount += 1;
3872 }
3873
3874 return splitMotionEntry;
3875}
3876
3877void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003878 if (DEBUG_INBOUND_EVENT_DETAILS) {
3879 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3880 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881
Antonio Kantekf16f2832021-09-28 04:39:20 +00003882 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003884 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003885
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003886 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3887 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3888 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889 } // release lock
3890
3891 if (needWake) {
3892 mLooper->wake();
3893 }
3894}
3895
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003896/**
3897 * If one of the meta shortcuts is detected, process them here:
3898 * Meta + Backspace -> generate BACK
3899 * Meta + Enter -> generate HOME
3900 * This will potentially overwrite keyCode and metaState.
3901 */
3902void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003903 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003904 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3905 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3906 if (keyCode == AKEYCODE_DEL) {
3907 newKeyCode = AKEYCODE_BACK;
3908 } else if (keyCode == AKEYCODE_ENTER) {
3909 newKeyCode = AKEYCODE_HOME;
3910 }
3911 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003912 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003913 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003914 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003915 keyCode = newKeyCode;
3916 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3917 }
3918 } else if (action == AKEY_EVENT_ACTION_UP) {
3919 // In order to maintain a consistent stream of up and down events, check to see if the key
3920 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3921 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003922 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003923 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003924 auto replacementIt = mReplacedKeys.find(replacement);
3925 if (replacementIt != mReplacedKeys.end()) {
3926 keyCode = replacementIt->second;
3927 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003928 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3929 }
3930 }
3931}
3932
Michael Wrightd02c5b62014-02-10 15:10:22 -08003933void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003934 if (DEBUG_INBOUND_EVENT_DETAILS) {
3935 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3936 "policyFlags=0x%x, action=0x%x, "
3937 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3938 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3939 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3940 args->downTime);
3941 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003942 if (!validateKeyEvent(args->action)) {
3943 return;
3944 }
3945
3946 uint32_t policyFlags = args->policyFlags;
3947 int32_t flags = args->flags;
3948 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003949 // InputDispatcher tracks and generates key repeats on behalf of
3950 // whatever notifies it, so repeatCount should always be set to 0
3951 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3953 policyFlags |= POLICY_FLAG_VIRTUAL;
3954 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956 if (policyFlags & POLICY_FLAG_FUNCTION) {
3957 metaState |= AMETA_FUNCTION_ON;
3958 }
3959
3960 policyFlags |= POLICY_FLAG_TRUSTED;
3961
Michael Wright78f24442014-08-06 15:55:28 -07003962 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003963 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003964
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003966 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003967 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3968 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969
Michael Wright2b3c3302018-03-02 17:19:13 +00003970 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003972 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3973 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003974 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003975 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976
Antonio Kantekf16f2832021-09-28 04:39:20 +00003977 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978 { // acquire lock
3979 mLock.lock();
3980
3981 if (shouldSendKeyToInputFilterLocked(args)) {
3982 mLock.unlock();
3983
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003984 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3986 return; // event was consumed by the filter
3987 }
3988
3989 mLock.lock();
3990 }
3991
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003992 std::unique_ptr<KeyEntry> newEntry =
3993 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3994 args->displayId, policyFlags, args->action, flags,
3995 keyCode, args->scanCode, metaState, repeatCount,
3996 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003997
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003998 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003999 mLock.unlock();
4000 } // release lock
4001
4002 if (needWake) {
4003 mLooper->wake();
4004 }
4005}
4006
4007bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4008 return mInputFilterEnabled;
4009}
4010
4011void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004012 if (DEBUG_INBOUND_EVENT_DETAILS) {
4013 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4014 "displayId=%" PRId32 ", policyFlags=0x%x, "
4015 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
4016 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4017 "yCursorPosition=%f, downTime=%" PRId64,
4018 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
4019 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
4020 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
4021 args->xCursorPosition, args->yCursorPosition, args->downTime);
4022 for (uint32_t i = 0; i < args->pointerCount; i++) {
4023 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4024 "x=%f, y=%f, pressure=%f, size=%f, "
4025 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4026 "orientation=%f",
4027 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4028 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4029 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4030 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4031 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4032 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4033 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4034 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4035 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4036 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4037 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004038 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004039 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4040 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004041 return;
4042 }
4043
4044 uint32_t policyFlags = args->policyFlags;
4045 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004046
4047 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004048 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004049 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4050 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004051 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004052 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004053
Antonio Kantekf16f2832021-09-28 04:39:20 +00004054 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055 { // acquire lock
4056 mLock.lock();
4057
4058 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004059 ui::Transform displayTransform;
4060 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4061 displayTransform = it->second.transform;
4062 }
4063
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064 mLock.unlock();
4065
4066 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004067 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4068 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004069 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004070 displayTransform, args->xPrecision, args->yPrecision,
4071 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004072 args->downTime, args->eventTime, args->pointerCount,
4073 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074
4075 policyFlags |= POLICY_FLAG_FILTERED;
4076 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4077 return; // event was consumed by the filter
4078 }
4079
4080 mLock.lock();
4081 }
4082
4083 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004084 std::unique_ptr<MotionEntry> newEntry =
4085 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4086 args->source, args->displayId, policyFlags,
4087 args->action, args->actionButton, args->flags,
4088 args->metaState, args->buttonState,
4089 args->classification, args->edgeFlags,
4090 args->xPrecision, args->yPrecision,
4091 args->xCursorPosition, args->yCursorPosition,
4092 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004093 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004095 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4096 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4097 !mInputFilterEnabled) {
4098 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4099 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4100 }
4101
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004102 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103 mLock.unlock();
4104 } // release lock
4105
4106 if (needWake) {
4107 mLooper->wake();
4108 }
4109}
4110
Chris Yef59a2f42020-10-16 12:55:26 -07004111void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004112 if (DEBUG_INBOUND_EVENT_DETAILS) {
4113 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4114 " sensorType=%s",
4115 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004116 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004117 }
Chris Yef59a2f42020-10-16 12:55:26 -07004118
Antonio Kantekf16f2832021-09-28 04:39:20 +00004119 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004120 { // acquire lock
4121 mLock.lock();
4122
4123 // Just enqueue a new sensor event.
4124 std::unique_ptr<SensorEntry> newEntry =
4125 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4126 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4127 args->sensorType, args->accuracy,
4128 args->accuracyChanged, args->values);
4129
4130 needWake = enqueueInboundEventLocked(std::move(newEntry));
4131 mLock.unlock();
4132 } // release lock
4133
4134 if (needWake) {
4135 mLooper->wake();
4136 }
4137}
4138
Chris Yefb552902021-02-03 17:18:37 -08004139void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004140 if (DEBUG_INBOUND_EVENT_DETAILS) {
4141 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4142 args->deviceId, args->isOn);
4143 }
Chris Yefb552902021-02-03 17:18:37 -08004144 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4145}
4146
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004148 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149}
4150
4151void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004152 if (DEBUG_INBOUND_EVENT_DETAILS) {
4153 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4154 "switchMask=0x%08x",
4155 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4156 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157
4158 uint32_t policyFlags = args->policyFlags;
4159 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004160 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161}
4162
4163void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004164 if (DEBUG_INBOUND_EVENT_DETAILS) {
4165 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4166 args->deviceId);
4167 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168
Antonio Kantekf16f2832021-09-28 04:39:20 +00004169 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004171 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004173 std::unique_ptr<DeviceResetEntry> newEntry =
4174 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4175 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176 } // release lock
4177
4178 if (needWake) {
4179 mLooper->wake();
4180 }
4181}
4182
Prabir Pradhan7e186182020-11-10 13:56:45 -08004183void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004184 if (DEBUG_INBOUND_EVENT_DETAILS) {
4185 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004186 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004187 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004188
Antonio Kantekf16f2832021-09-28 04:39:20 +00004189 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004190 { // acquire lock
4191 std::scoped_lock _l(mLock);
4192 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004193 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004194 needWake = enqueueInboundEventLocked(std::move(entry));
4195 } // release lock
4196
4197 if (needWake) {
4198 mLooper->wake();
4199 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004200}
4201
Prabir Pradhan5735a322022-04-11 17:23:34 +00004202InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4203 std::optional<int32_t> targetUid,
4204 InputEventInjectionSync syncMode,
4205 std::chrono::milliseconds timeout,
4206 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004207 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004208 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4209 "policyFlags=0x%08x",
4210 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4211 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004212 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004213 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214
Prabir Pradhan5735a322022-04-11 17:23:34 +00004215 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004216
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004217 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004218 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4219 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4220 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4221 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4222 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004223 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004224 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004225 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004226 }
4227
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004228 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004229 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004230 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004231 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4232 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004233 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004234 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004235 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004237 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004238 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4239 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4240 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004241 int32_t keyCode = incomingKey.getKeyCode();
4242 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004243 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004244 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004245 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004246 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004247 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4248 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4249 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004251 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4252 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004253 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004254
4255 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4256 android::base::Timer t;
4257 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4258 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4259 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4260 std::to_string(t.duration().count()).c_str());
4261 }
4262 }
4263
4264 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004265 std::unique_ptr<KeyEntry> injectedEntry =
4266 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004267 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004268 incomingKey.getDisplayId(), policyFlags, action,
4269 flags, keyCode, incomingKey.getScanCode(), metaState,
4270 incomingKey.getRepeatCount(),
4271 incomingKey.getDownTime());
4272 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004273 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274 }
4275
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004276 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004277 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004278 const int32_t action = motionEvent.getAction();
4279 const bool isPointerEvent =
4280 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4281 // If a pointer event has no displayId specified, inject it to the default display.
4282 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4283 ? ADISPLAY_ID_DEFAULT
4284 : event->getDisplayId();
4285 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004286 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004287 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004288 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004289 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004290 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004291 }
4292
4293 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004294 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004295 android::base::Timer t;
4296 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4297 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4298 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4299 std::to_string(t.duration().count()).c_str());
4300 }
4301 }
4302
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004303 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4304 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4305 }
4306
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004307 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004308 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4309 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004310 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004311 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4312 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004313 displayId, policyFlags, action, actionButton,
4314 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004315 motionEvent.getButtonState(),
4316 motionEvent.getClassification(),
4317 motionEvent.getEdgeFlags(),
4318 motionEvent.getXPrecision(),
4319 motionEvent.getYPrecision(),
4320 motionEvent.getRawXCursorPosition(),
4321 motionEvent.getRawYCursorPosition(),
4322 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004323 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004324 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004325 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004326 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004327 sampleEventTimes += 1;
4328 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004329 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004330 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4331 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004332 displayId, policyFlags, action, actionButton,
4333 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004334 motionEvent.getButtonState(),
4335 motionEvent.getClassification(),
4336 motionEvent.getEdgeFlags(),
4337 motionEvent.getXPrecision(),
4338 motionEvent.getYPrecision(),
4339 motionEvent.getRawXCursorPosition(),
4340 motionEvent.getRawYCursorPosition(),
4341 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004342 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004343 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004344 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4345 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004346 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004347 }
4348 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004351 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004352 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004353 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004354 }
4355
Prabir Pradhan5735a322022-04-11 17:23:34 +00004356 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004357 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358 injectionState->injectionIsAsync = true;
4359 }
4360
4361 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004362 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004363
4364 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004365 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004366 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004367 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368 }
4369
4370 mLock.unlock();
4371
4372 if (needWake) {
4373 mLooper->wake();
4374 }
4375
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004376 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004378 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004379
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004380 if (syncMode == InputEventInjectionSync::NONE) {
4381 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382 } else {
4383 for (;;) {
4384 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004385 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386 break;
4387 }
4388
4389 nsecs_t remainingTimeout = endTime - now();
4390 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004391 if (DEBUG_INJECTION) {
4392 ALOGD("injectInputEvent - Timed out waiting for injection result "
4393 "to become available.");
4394 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004395 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396 break;
4397 }
4398
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004399 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400 }
4401
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004402 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4403 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004405 if (DEBUG_INJECTION) {
4406 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4407 injectionState->pendingForegroundDispatches);
4408 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004409 nsecs_t remainingTimeout = endTime - now();
4410 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004411 if (DEBUG_INJECTION) {
4412 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4413 "dispatches to finish.");
4414 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004415 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004416 break;
4417 }
4418
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004419 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420 }
4421 }
4422 }
4423
4424 injectionState->release();
4425 } // release lock
4426
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004427 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004428 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004429 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004430
4431 return injectionResult;
4432}
4433
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004434std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004435 std::array<uint8_t, 32> calculatedHmac;
4436 std::unique_ptr<VerifiedInputEvent> result;
4437 switch (event.getType()) {
4438 case AINPUT_EVENT_TYPE_KEY: {
4439 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4440 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4441 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004442 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004443 break;
4444 }
4445 case AINPUT_EVENT_TYPE_MOTION: {
4446 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4447 VerifiedMotionEvent verifiedMotionEvent =
4448 verifiedMotionEventFromMotionEvent(motionEvent);
4449 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004450 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004451 break;
4452 }
4453 default: {
4454 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4455 return nullptr;
4456 }
4457 }
4458 if (calculatedHmac == INVALID_HMAC) {
4459 return nullptr;
4460 }
4461 if (calculatedHmac != event.getHmac()) {
4462 return nullptr;
4463 }
4464 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004465}
4466
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004467void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004468 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004469 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004471 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004472 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004473 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004474
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004475 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004476 // Log the outcome since the injector did not wait for the injection result.
4477 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004478 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004479 ALOGV("Asynchronous input event injection succeeded.");
4480 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004481 case InputEventInjectionResult::TARGET_MISMATCH:
4482 ALOGV("Asynchronous input event injection target mismatch.");
4483 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004484 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004485 ALOGW("Asynchronous input event injection failed.");
4486 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004487 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004488 ALOGW("Asynchronous input event injection timed out.");
4489 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004490 case InputEventInjectionResult::PENDING:
4491 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4492 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493 }
4494 }
4495
4496 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004497 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004498 }
4499}
4500
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004501void InputDispatcher::transformMotionEntryForInjectionLocked(
4502 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004503 // Input injection works in the logical display coordinate space, but the input pipeline works
4504 // display space, so we need to transform the injected events accordingly.
4505 const auto it = mDisplayInfos.find(entry.displayId);
4506 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004507 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004508
4509 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004510 entry.pointerCoords[i] =
4511 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4512 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004513 }
4514}
4515
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004516void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4517 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004518 if (injectionState) {
4519 injectionState->pendingForegroundDispatches += 1;
4520 }
4521}
4522
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004523void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4524 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525 if (injectionState) {
4526 injectionState->pendingForegroundDispatches -= 1;
4527
4528 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004529 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004530 }
4531 }
4532}
4533
chaviw98318de2021-05-19 16:45:23 -05004534const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004535 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004536 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004537 auto it = mWindowHandlesByDisplay.find(displayId);
4538 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004539}
4540
chaviw98318de2021-05-19 16:45:23 -05004541sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004542 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004543 if (windowHandleToken == nullptr) {
4544 return nullptr;
4545 }
4546
Arthur Hungb92218b2018-08-14 12:00:21 +08004547 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004548 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4549 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004550 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004551 return windowHandle;
4552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553 }
4554 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004555 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004556}
4557
chaviw98318de2021-05-19 16:45:23 -05004558sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4559 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004560 if (windowHandleToken == nullptr) {
4561 return nullptr;
4562 }
4563
chaviw98318de2021-05-19 16:45:23 -05004564 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004565 if (windowHandle->getToken() == windowHandleToken) {
4566 return windowHandle;
4567 }
4568 }
4569 return nullptr;
4570}
4571
chaviw98318de2021-05-19 16:45:23 -05004572sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4573 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004574 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004575 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4576 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004577 if (handle->getId() == windowHandle->getId() &&
4578 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004579 if (windowHandle->getInfo()->displayId != it.first) {
4580 ALOGE("Found window %s in display %" PRId32
4581 ", but it should belong to display %" PRId32,
4582 windowHandle->getName().c_str(), it.first,
4583 windowHandle->getInfo()->displayId);
4584 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004585 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587 }
4588 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004589 return nullptr;
4590}
4591
chaviw98318de2021-05-19 16:45:23 -05004592sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004593 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4594 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004595}
4596
chaviw98318de2021-05-19 16:45:23 -05004597bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004598 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4599 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004600 windowHandle.getInfo()->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004601 if (connection != nullptr && noInputChannel) {
4602 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4603 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4604 return false;
4605 }
4606
4607 if (connection == nullptr) {
4608 if (!noInputChannel) {
4609 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4610 }
4611 return false;
4612 }
4613 if (!connection->responsive) {
4614 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4615 return false;
4616 }
4617 return true;
4618}
4619
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004620std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4621 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004622 auto connectionIt = mConnectionsByToken.find(token);
4623 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004624 return nullptr;
4625 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004626 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004627}
4628
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004629void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004630 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4631 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004632 // Remove all handles on a display if there are no windows left.
4633 mWindowHandlesByDisplay.erase(displayId);
4634 return;
4635 }
4636
4637 // Since we compare the pointer of input window handles across window updates, we need
4638 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004639 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4640 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4641 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004642 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004643 }
4644
chaviw98318de2021-05-19 16:45:23 -05004645 std::vector<sp<WindowInfoHandle>> newHandles;
4646 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004647 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004648 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004649 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004650 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004651 const bool canReceiveInput =
4652 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4653 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004654 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004655 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004656 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004657 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004658 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004659 }
4660
4661 if (info->displayId != displayId) {
4662 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4663 handle->getName().c_str(), displayId, info->displayId);
4664 continue;
4665 }
4666
Robert Carredd13602020-04-13 17:24:34 -07004667 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4668 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004669 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004670 oldHandle->updateFrom(handle);
4671 newHandles.push_back(oldHandle);
4672 } else {
4673 newHandles.push_back(handle);
4674 }
4675 }
4676
4677 // Insert or replace
4678 mWindowHandlesByDisplay[displayId] = newHandles;
4679}
4680
Arthur Hung72d8dc32020-03-28 00:48:39 +00004681void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004682 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004683 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004684 { // acquire lock
4685 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004686 for (const auto& [displayId, handles] : handlesPerDisplay) {
4687 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004688 }
4689 }
4690 // Wake up poll loop since it may need to make new input dispatching choices.
4691 mLooper->wake();
4692}
4693
Arthur Hungb92218b2018-08-14 12:00:21 +08004694/**
4695 * Called from InputManagerService, update window handle list by displayId that can receive input.
4696 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4697 * If set an empty list, remove all handles from the specific display.
4698 * For focused handle, check if need to change and send a cancel event to previous one.
4699 * For removed handle, check if need to send a cancel event if already in touch.
4700 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004701void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004702 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004703 if (DEBUG_FOCUS) {
4704 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004705 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004706 windowList += iwh->getName() + " ";
4707 }
4708 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4709 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004710
Prabir Pradhand65552b2021-10-07 11:23:50 -07004711 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004712 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004713 const WindowInfo& info = *window->getInfo();
4714
4715 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004716 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004717 if (noInputWindow && window->getToken() != nullptr) {
4718 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4719 window->getName().c_str());
4720 window->releaseChannel();
4721 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004722
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004723 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004724 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4725 !info.inputConfig.test(
4726 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004727 "%s has feature SPY, but is not a trusted overlay.",
4728 window->getName().c_str());
4729
Prabir Pradhand65552b2021-10-07 11:23:50 -07004730 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004731 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4732 !info.inputConfig.test(
4733 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004734 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4735 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004736 }
4737
Arthur Hung72d8dc32020-03-28 00:48:39 +00004738 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004739 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004741 // Save the old windows' orientation by ID before it gets updated.
4742 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004743 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004744 oldWindowOrientations.emplace(handle->getId(),
4745 handle->getInfo()->transform.getOrientation());
4746 }
4747
chaviw98318de2021-05-19 16:45:23 -05004748 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004749
chaviw98318de2021-05-19 16:45:23 -05004750 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004751 if (mLastHoverWindowHandle &&
4752 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4753 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004754 mLastHoverWindowHandle = nullptr;
4755 }
4756
Vishnu Nairc519ff72021-01-21 08:23:08 -08004757 std::optional<FocusResolver::FocusChanges> changes =
4758 mFocusResolver.setInputWindows(displayId, windowHandles);
4759 if (changes) {
4760 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004761 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004762
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004763 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4764 mTouchStatesByDisplay.find(displayId);
4765 if (stateIt != mTouchStatesByDisplay.end()) {
4766 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004767 for (size_t i = 0; i < state.windows.size();) {
4768 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004769 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004770 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004771 ALOGD("Touched window was removed: %s in display %" PRId32,
4772 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004773 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004774 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004775 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4776 if (touchedInputChannel != nullptr) {
4777 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4778 "touched window was removed");
4779 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004780 // Since we are about to drop the touch, cancel the events for the wallpaper as
4781 // well.
4782 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004783 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4784 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004785 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4786 if (wallpaper != nullptr) {
4787 sp<Connection> wallpaperConnection =
4788 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004789 if (wallpaperConnection != nullptr) {
4790 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4791 options);
4792 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004793 }
4794 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004795 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004796 state.windows.erase(state.windows.begin() + i);
4797 } else {
4798 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004799 }
4800 }
arthurhungb89ccb02020-12-30 16:19:01 +08004801
arthurhung6d4bed92021-03-17 11:59:33 +08004802 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004803 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004804 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004805 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004806 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004807 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4808 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004809 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004810 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004811 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004812
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004813 // Determine if the orientation of any of the input windows have changed, and cancel all
4814 // pointer events if necessary.
4815 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4816 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4817 if (newWindowHandle != nullptr &&
4818 newWindowHandle->getInfo()->transform.getOrientation() !=
4819 oldWindowOrientations[oldWindowHandle->getId()]) {
4820 std::shared_ptr<InputChannel> inputChannel =
4821 getInputChannelLocked(newWindowHandle->getToken());
4822 if (inputChannel != nullptr) {
4823 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4824 "touched window's orientation changed");
4825 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004826 }
4827 }
4828 }
4829
Arthur Hung72d8dc32020-03-28 00:48:39 +00004830 // Release information for windows that are no longer present.
4831 // This ensures that unused input channels are released promptly.
4832 // Otherwise, they might stick around until the window handle is destroyed
4833 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004834 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004835 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004836 if (DEBUG_FOCUS) {
4837 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004838 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004839 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004840 }
chaviw291d88a2019-02-14 10:33:58 -08004841 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842}
4843
4844void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004845 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004846 if (DEBUG_FOCUS) {
4847 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4848 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4849 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004850 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004851 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004852 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853 } // release lock
4854
4855 // Wake up poll loop since it may need to make new input dispatching choices.
4856 mLooper->wake();
4857}
4858
Vishnu Nair599f1412021-06-21 10:39:58 -07004859void InputDispatcher::setFocusedApplicationLocked(
4860 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4861 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4862 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4863
4864 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4865 return; // This application is already focused. No need to wake up or change anything.
4866 }
4867
4868 // Set the new application handle.
4869 if (inputApplicationHandle != nullptr) {
4870 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4871 } else {
4872 mFocusedApplicationHandlesByDisplay.erase(displayId);
4873 }
4874
4875 // No matter what the old focused application was, stop waiting on it because it is
4876 // no longer focused.
4877 resetNoFocusedWindowTimeoutLocked();
4878}
4879
Tiger Huang721e26f2018-07-24 22:26:19 +08004880/**
4881 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4882 * the display not specified.
4883 *
4884 * We track any unreleased events for each window. If a window loses the ability to receive the
4885 * released event, we will send a cancel event to it. So when the focused display is changed, we
4886 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4887 * display. The display-specified events won't be affected.
4888 */
4889void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004890 if (DEBUG_FOCUS) {
4891 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4892 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004893 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004894 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004895
4896 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004897 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004898 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004899 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004900 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004901 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004902 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004903 CancelationOptions
4904 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4905 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004906 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004907 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4908 }
4909 }
4910 mFocusedDisplayId = displayId;
4911
Chris Ye3c2d6f52020-08-09 10:39:48 -07004912 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004913 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004914 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004915
Vishnu Nairad321cd2020-08-20 16:40:21 -07004916 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004917 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004918 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004919 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004920 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004921 }
4922 }
4923 }
4924
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004925 if (DEBUG_FOCUS) {
4926 logDispatchStateLocked();
4927 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004928 } // release lock
4929
4930 // Wake up poll loop since it may need to make new input dispatching choices.
4931 mLooper->wake();
4932}
4933
Michael Wrightd02c5b62014-02-10 15:10:22 -08004934void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004935 if (DEBUG_FOCUS) {
4936 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4937 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004938
4939 bool changed;
4940 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004941 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004942
4943 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4944 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004945 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004946 }
4947
4948 if (mDispatchEnabled && !enabled) {
4949 resetAndDropEverythingLocked("dispatcher is being disabled");
4950 }
4951
4952 mDispatchEnabled = enabled;
4953 mDispatchFrozen = frozen;
4954 changed = true;
4955 } else {
4956 changed = false;
4957 }
4958
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004959 if (DEBUG_FOCUS) {
4960 logDispatchStateLocked();
4961 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004962 } // release lock
4963
4964 if (changed) {
4965 // Wake up poll loop since it may need to make new input dispatching choices.
4966 mLooper->wake();
4967 }
4968}
4969
4970void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004971 if (DEBUG_FOCUS) {
4972 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4973 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004974
4975 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004976 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004977
4978 if (mInputFilterEnabled == enabled) {
4979 return;
4980 }
4981
4982 mInputFilterEnabled = enabled;
4983 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4984 } // release lock
4985
4986 // Wake up poll loop since there might be work to do to drop everything.
4987 mLooper->wake();
4988}
4989
Antonio Kantekea47acb2021-12-23 12:41:25 -08004990bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid,
4991 bool hasPermission) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00004992 bool needWake = false;
4993 {
4994 std::scoped_lock lock(mLock);
4995 if (mInTouchMode == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004996 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00004997 }
4998 if (DEBUG_TOUCH_MODE) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004999 ALOGD("Request to change touch mode from %s to %s (calling pid=%d, uid=%d, "
5000 "hasPermission=%s)",
5001 toString(mInTouchMode), toString(inTouchMode), pid, uid, toString(hasPermission));
5002 }
5003 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005004 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5005 !recentWindowsAreOwnedByLocked(pid, uid)) {
5006 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5007 "window nor none of the previously interacted window",
5008 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005009 return false;
5010 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005011 }
5012
5013 // TODO(b/198499018): Store touch mode per display.
5014 mInTouchMode = inTouchMode;
5015
Antonio Kantekf16f2832021-09-28 04:39:20 +00005016 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
5017 needWake = enqueueInboundEventLocked(std::move(entry));
5018 } // release lock
5019
5020 if (needWake) {
5021 mLooper->wake();
5022 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005023 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005024}
5025
Antonio Kantek48710e42022-03-24 14:19:30 -07005026bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5027 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5028 if (focusedToken == nullptr) {
5029 return false;
5030 }
5031 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5032 return isWindowOwnedBy(windowHandle, pid, uid);
5033}
5034
5035bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5036 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5037 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5038 const sp<WindowInfoHandle> windowHandle =
5039 getWindowHandleLocked(connectionToken);
5040 return isWindowOwnedBy(windowHandle, pid, uid);
5041 }) != mInteractionConnectionTokens.end();
5042}
5043
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005044void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5045 if (opacity < 0 || opacity > 1) {
5046 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5047 return;
5048 }
5049
5050 std::scoped_lock lock(mLock);
5051 mMaximumObscuringOpacityForTouch = opacity;
5052}
5053
Arthur Hungabbb9d82021-09-01 14:52:30 +00005054std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
5055 const sp<IBinder>& token) {
5056 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5057 for (TouchedWindow& w : state.windows) {
5058 if (w.windowHandle->getToken() == token) {
5059 return std::make_pair(&state, &w);
5060 }
5061 }
5062 }
5063 return std::make_pair(nullptr, nullptr);
5064}
5065
arthurhungb89ccb02020-12-30 16:19:01 +08005066bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5067 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005068 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005069 if (DEBUG_FOCUS) {
5070 ALOGD("Trivial transfer to same window.");
5071 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005072 return true;
5073 }
5074
Michael Wrightd02c5b62014-02-10 15:10:22 -08005075 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005076 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005077
Arthur Hungabbb9d82021-09-01 14:52:30 +00005078 // Find the target touch state and touched window by fromToken.
5079 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5080 if (state == nullptr || touchedWindow == nullptr) {
5081 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005082 return false;
5083 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005084
5085 const int32_t displayId = state->displayId;
5086 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5087 if (toWindowHandle == nullptr) {
5088 ALOGW("Cannot transfer focus because to window not found.");
5089 return false;
5090 }
5091
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005092 if (DEBUG_FOCUS) {
5093 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005094 touchedWindow->windowHandle->getName().c_str(),
5095 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005096 }
5097
Arthur Hungabbb9d82021-09-01 14:52:30 +00005098 // Erase old window.
5099 int32_t oldTargetFlags = touchedWindow->targetFlags;
5100 BitSet32 pointerIds = touchedWindow->pointerIds;
5101 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005102
Arthur Hungabbb9d82021-09-01 14:52:30 +00005103 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005104 nsecs_t downTimeInTarget = now();
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005105 int32_t newTargetFlags =
5106 oldTargetFlags & (InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
5107 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
5108 newTargetFlags |= InputTarget::FLAG_FOREGROUND;
5109 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005110 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005111
Arthur Hungabbb9d82021-09-01 14:52:30 +00005112 // Store the dragging window.
5113 if (isDragDrop) {
Arthur Hung54745652022-04-20 07:17:41 +00005114 if (pointerIds.count() > 1) {
5115 ALOGW("The drag and drop cannot be started when there is more than 1 pointer on the"
5116 " window.");
5117 return false;
5118 }
5119 // If the window didn't not support split or the source is mouse, the pointerIds count
5120 // would be 0, so we have to track the pointer 0.
5121 const int32_t id = pointerIds.count() == 0 ? 0 : pointerIds.firstMarkedBit();
5122 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005123 }
5124
Arthur Hungabbb9d82021-09-01 14:52:30 +00005125 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005126 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5127 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005128 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005129 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005130 CancelationOptions
5131 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5132 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005133 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005134 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005135 }
5136
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005137 if (DEBUG_FOCUS) {
5138 logDispatchStateLocked();
5139 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005140 } // release lock
5141
5142 // Wake up poll loop since it may need to make new input dispatching choices.
5143 mLooper->wake();
5144 return true;
5145}
5146
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005147/**
5148 * Get the touched foreground window on the given display.
5149 * Return null if there are no windows touched on that display, or if more than one foreground
5150 * window is being touched.
5151 */
5152sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5153 auto stateIt = mTouchStatesByDisplay.find(displayId);
5154 if (stateIt == mTouchStatesByDisplay.end()) {
5155 ALOGI("No touch state on display %" PRId32, displayId);
5156 return nullptr;
5157 }
5158
5159 const TouchState& state = stateIt->second;
5160 sp<WindowInfoHandle> touchedForegroundWindow;
5161 // If multiple foreground windows are touched, return nullptr
5162 for (const TouchedWindow& window : state.windows) {
5163 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5164 if (touchedForegroundWindow != nullptr) {
5165 ALOGI("Two or more foreground windows: %s and %s",
5166 touchedForegroundWindow->getName().c_str(),
5167 window.windowHandle->getName().c_str());
5168 return nullptr;
5169 }
5170 touchedForegroundWindow = window.windowHandle;
5171 }
5172 }
5173 return touchedForegroundWindow;
5174}
5175
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005176// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005177bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005178 sp<IBinder> fromToken;
5179 { // acquire lock
5180 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005181 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005182 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005183 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5184 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005185 return false;
5186 }
5187
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005188 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5189 if (from == nullptr) {
5190 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5191 return false;
5192 }
5193
5194 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005195 } // release lock
5196
5197 return transferTouchFocus(fromToken, destChannelToken);
5198}
5199
Michael Wrightd02c5b62014-02-10 15:10:22 -08005200void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005201 if (DEBUG_FOCUS) {
5202 ALOGD("Resetting and dropping all events (%s).", reason);
5203 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005204
5205 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5206 synthesizeCancelationEventsForAllConnectionsLocked(options);
5207
5208 resetKeyRepeatLocked();
5209 releasePendingEventLocked();
5210 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005211 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005212
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005213 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005214 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005215 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005216 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005217}
5218
5219void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005220 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005221 dumpDispatchStateLocked(dump);
5222
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005223 std::istringstream stream(dump);
5224 std::string line;
5225
5226 while (std::getline(stream, line, '\n')) {
5227 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005228 }
5229}
5230
Prabir Pradhan99987712020-11-10 18:43:05 -08005231std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5232 std::string dump;
5233
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005234 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5235 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005236
5237 std::string windowName = "None";
5238 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005239 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005240 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5241 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5242 : "token has capture without window";
5243 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005244 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005245
5246 return dump;
5247}
5248
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005249void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005250 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5251 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5252 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005253 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005254
Tiger Huang721e26f2018-07-24 22:26:19 +08005255 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5256 dump += StringPrintf(INDENT "FocusedApplications:\n");
5257 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5258 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005259 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005260 const std::chrono::duration timeout =
5261 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005262 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005263 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005264 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005265 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005267 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005268 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005269
Vishnu Nairc519ff72021-01-21 08:23:08 -08005270 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005271 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005273 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005274 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005275 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5276 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005277 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005278 state.displayId, toString(state.down), toString(state.split),
5279 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005280 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005281 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005282 for (size_t i = 0; i < state.windows.size(); i++) {
5283 const TouchedWindow& touchedWindow = state.windows[i];
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005284 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, "
5285 "targetFlags=0x%x, firstDownTimeInTarget=%" PRId64
5286 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005287 i, touchedWindow.windowHandle->getName().c_str(),
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005288 touchedWindow.pointerIds.value, touchedWindow.targetFlags,
5289 ns2ms(touchedWindow.firstDownTimeInTarget.value_or(0)));
Jeff Brownf086ddb2014-02-11 14:28:48 -08005290 }
5291 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005292 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005293 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005294 }
5295 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005296 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005297 }
5298
arthurhung6d4bed92021-03-17 11:59:33 +08005299 if (mDragState) {
5300 dump += StringPrintf(INDENT "DragState:\n");
5301 mDragState->dump(dump, INDENT2);
5302 }
5303
Arthur Hungb92218b2018-08-14 12:00:21 +08005304 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005305 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5306 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5307 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5308 const auto& displayInfo = it->second;
5309 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5310 displayInfo.logicalHeight);
5311 displayInfo.transform.dump(dump, "transform", INDENT4);
5312 } else {
5313 dump += INDENT2 "No DisplayInfo found!\n";
5314 }
5315
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005316 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005317 dump += INDENT2 "Windows:\n";
5318 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005319 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5320 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005321
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005322 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005323 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005324 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005325 "applicationInfo.name=%s, "
5326 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005327 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005328 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005329 windowInfo->displayId,
5330 windowInfo->inputConfig.string().c_str(),
5331 windowInfo->alpha, windowInfo->frameLeft,
5332 windowInfo->frameTop, windowInfo->frameRight,
5333 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005334 windowInfo->applicationInfo.name.c_str(),
5335 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005336 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005337 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005338 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005339 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005340 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005341 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005342 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005343 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005344 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005345 }
5346 } else {
5347 dump += INDENT2 "Windows: <none>\n";
5348 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005349 }
5350 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005351 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005352 }
5353
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005354 if (!mGlobalMonitorsByDisplay.empty()) {
5355 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5356 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005357 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005358 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005360 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005361 }
5362
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005363 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005364
5365 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005366 if (!mRecentQueue.empty()) {
5367 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005368 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005369 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005370 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005371 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005372 }
5373 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005374 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005375 }
5376
5377 // Dump event currently being dispatched.
5378 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005379 dump += INDENT "PendingEvent:\n";
5380 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005381 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005382 dump += StringPrintf(", age=%" PRId64 "ms\n",
5383 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005384 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005385 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005386 }
5387
5388 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005389 if (!mInboundQueue.empty()) {
5390 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005391 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005392 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005393 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005394 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005395 }
5396 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005397 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005398 }
5399
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005400 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005401 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005402 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5403 const KeyReplacement& replacement = pair.first;
5404 int32_t newKeyCode = pair.second;
5405 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005406 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005407 }
5408 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005409 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005410 }
5411
Prabir Pradhancef936d2021-07-21 16:17:52 +00005412 if (!mCommandQueue.empty()) {
5413 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5414 } else {
5415 dump += INDENT "CommandQueue: <empty>\n";
5416 }
5417
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005418 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005419 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005420 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005421 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005422 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005423 connection->inputChannel->getFd().get(),
5424 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005425 connection->getWindowName().c_str(),
5426 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005427 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005428
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005429 if (!connection->outboundQueue.empty()) {
5430 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5431 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005432 dump += dumpQueue(connection->outboundQueue, currentTime);
5433
Michael Wrightd02c5b62014-02-10 15:10:22 -08005434 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005435 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005436 }
5437
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005438 if (!connection->waitQueue.empty()) {
5439 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5440 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005441 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005442 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005443 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005444 }
5445 }
5446 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005447 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005448 }
5449
5450 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005451 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5452 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005453 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005454 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005455 }
5456
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005457 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005458 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5459 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5460 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005461 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005462 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005463}
5464
Michael Wright3dd60e22019-03-27 22:06:44 +00005465void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5466 const size_t numMonitors = monitors.size();
5467 for (size_t i = 0; i < numMonitors; i++) {
5468 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005469 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005470 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5471 dump += "\n";
5472 }
5473}
5474
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005475class LooperEventCallback : public LooperCallback {
5476public:
5477 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5478 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5479
5480private:
5481 std::function<int(int events)> mCallback;
5482};
5483
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005484Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005485 if (DEBUG_CHANNEL_CREATION) {
5486 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5487 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005489 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005490 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005491 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005492
5493 if (result) {
5494 return base::Error(result) << "Failed to open input channel pair with name " << name;
5495 }
5496
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005498 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005499 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005500 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005501 sp<Connection> connection =
5502 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005503
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005504 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5505 ALOGE("Created a new connection, but the token %p is already known", token.get());
5506 }
5507 mConnectionsByToken.emplace(token, connection);
5508
5509 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5510 this, std::placeholders::_1, token);
5511
5512 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005513 } // release lock
5514
5515 // Wake the looper because some connections have changed.
5516 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005517 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005518}
5519
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005520Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005521 const std::string& name,
5522 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005523 std::shared_ptr<InputChannel> serverChannel;
5524 std::unique_ptr<InputChannel> clientChannel;
5525 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5526 if (result) {
5527 return base::Error(result) << "Failed to open input channel pair with name " << name;
5528 }
5529
Michael Wright3dd60e22019-03-27 22:06:44 +00005530 { // acquire lock
5531 std::scoped_lock _l(mLock);
5532
5533 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005534 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5535 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005536 }
5537
Garfield Tan15601662020-09-22 15:32:38 -07005538 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005539 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005540 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005541
5542 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5543 ALOGE("Created a new connection, but the token %p is already known", token.get());
5544 }
5545 mConnectionsByToken.emplace(token, connection);
5546 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5547 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005548
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005549 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005550
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005551 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005552 }
Garfield Tan15601662020-09-22 15:32:38 -07005553
Michael Wright3dd60e22019-03-27 22:06:44 +00005554 // Wake the looper because some connections have changed.
5555 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005556 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005557}
5558
Garfield Tan15601662020-09-22 15:32:38 -07005559status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005560 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005561 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562
Garfield Tan15601662020-09-22 15:32:38 -07005563 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005564 if (status) {
5565 return status;
5566 }
5567 } // release lock
5568
5569 // Wake the poll loop because removing the connection may have changed the current
5570 // synchronization state.
5571 mLooper->wake();
5572 return OK;
5573}
5574
Garfield Tan15601662020-09-22 15:32:38 -07005575status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5576 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005577 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005578 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005579 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005580 return BAD_VALUE;
5581 }
5582
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005583 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005584
Michael Wrightd02c5b62014-02-10 15:10:22 -08005585 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005586 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005587 }
5588
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005589 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005590
5591 nsecs_t currentTime = now();
5592 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5593
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005594 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005595 return OK;
5596}
5597
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005598void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005599 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5600 auto& [displayId, monitors] = *it;
5601 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5602 return monitor.inputChannel->getConnectionToken() == connectionToken;
5603 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005604
Michael Wright3dd60e22019-03-27 22:06:44 +00005605 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005606 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005607 } else {
5608 ++it;
5609 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005610 }
5611}
5612
Michael Wright3dd60e22019-03-27 22:06:44 +00005613status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005614 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005615 return pilferPointersLocked(token);
5616}
Michael Wright3dd60e22019-03-27 22:06:44 +00005617
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005618status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005619 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5620 if (!requestingChannel) {
5621 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5622 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005623 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005624
5625 auto [statePtr, windowPtr] = findTouchStateAndWindowLocked(token);
5626 if (statePtr == nullptr || windowPtr == nullptr || !statePtr->down) {
5627 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5628 " Ignoring.");
5629 return BAD_VALUE;
5630 }
5631
5632 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005633 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005634 // Send cancel events to all the input channels we're stealing from.
5635 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5636 "input channel stole pointer stream");
5637 options.deviceId = state.deviceId;
5638 options.displayId = state.displayId;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005639 if (state.split) {
5640 // If split pointers then selectively cancel pointers otherwise cancel all pointers
5641 options.pointerIds = window.pointerIds;
5642 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005643 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005644 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005645 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005646 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005647 if (channel != nullptr && channel->getConnectionToken() != token) {
5648 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5649 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5650 canceledWindows += channel->getName();
5651 }
5652 }
5653 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5654 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5655 canceledWindows.c_str());
5656
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005657 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005658 // This only blocks relevant pointers to be sent to other windows
5659 window.isPilferingPointers = true;
5660
5661 if (state.split) {
5662 state.cancelPointersForWindowsExcept(window.pointerIds, token);
5663 } else {
5664 state.filterWindowsExcept(token);
5665 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005666 return OK;
5667}
5668
Prabir Pradhan99987712020-11-10 18:43:05 -08005669void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5670 { // acquire lock
5671 std::scoped_lock _l(mLock);
5672 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005673 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005674 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5675 windowHandle != nullptr ? windowHandle->getName().c_str()
5676 : "token without window");
5677 }
5678
Vishnu Nairc519ff72021-01-21 08:23:08 -08005679 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005680 if (focusedToken != windowToken) {
5681 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5682 enabled ? "enable" : "disable");
5683 return;
5684 }
5685
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005686 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005687 ALOGW("Ignoring request to %s Pointer Capture: "
5688 "window has %s requested pointer capture.",
5689 enabled ? "enable" : "disable", enabled ? "already" : "not");
5690 return;
5691 }
5692
Christine Franksb768bb42021-11-29 12:11:31 -08005693 if (enabled) {
5694 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5695 mIneligibleDisplaysForPointerCapture.end(),
5696 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5697 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5698 return;
5699 }
5700 }
5701
Prabir Pradhan99987712020-11-10 18:43:05 -08005702 setPointerCaptureLocked(enabled);
5703 } // release lock
5704
5705 // Wake the thread to process command entries.
5706 mLooper->wake();
5707}
5708
Christine Franksb768bb42021-11-29 12:11:31 -08005709void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5710 { // acquire lock
5711 std::scoped_lock _l(mLock);
5712 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5713 if (!isEligible) {
5714 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5715 }
5716 } // release lock
5717}
5718
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005719std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5720 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005721 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005722 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005723 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005724 }
5725 }
5726 }
5727 return std::nullopt;
5728}
5729
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005730sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005731 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005732 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005733 }
5734
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005735 for (const auto& [token, connection] : mConnectionsByToken) {
5736 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005737 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005738 }
5739 }
Robert Carr4e670e52018-08-15 13:26:12 -07005740
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005741 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005742}
5743
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005744std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5745 sp<Connection> connection = getConnectionLocked(connectionToken);
5746 if (connection == nullptr) {
5747 return "<nullptr>";
5748 }
5749 return connection->getInputChannelName();
5750}
5751
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005752void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005753 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005754 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005755}
5756
Prabir Pradhancef936d2021-07-21 16:17:52 +00005757void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5758 const sp<Connection>& connection, uint32_t seq,
5759 bool handled, nsecs_t consumeTime) {
5760 // Handle post-event policy actions.
5761 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5762 if (dispatchEntryIt == connection->waitQueue.end()) {
5763 return;
5764 }
5765 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5766 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5767 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5768 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5769 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5770 }
5771 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5772 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5773 connection->inputChannel->getConnectionToken(),
5774 dispatchEntry->deliveryTime, consumeTime, finishTime);
5775 }
5776
5777 bool restartEvent;
5778 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5779 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5780 restartEvent =
5781 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5782 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5783 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5784 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5785 handled);
5786 } else {
5787 restartEvent = false;
5788 }
5789
5790 // Dequeue the event and start the next cycle.
5791 // Because the lock might have been released, it is possible that the
5792 // contents of the wait queue to have been drained, so we need to double-check
5793 // a few things.
5794 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5795 if (dispatchEntryIt != connection->waitQueue.end()) {
5796 dispatchEntry = *dispatchEntryIt;
5797 connection->waitQueue.erase(dispatchEntryIt);
5798 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5799 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5800 if (!connection->responsive) {
5801 connection->responsive = isConnectionResponsive(*connection);
5802 if (connection->responsive) {
5803 // The connection was unresponsive, and now it's responsive.
5804 processConnectionResponsiveLocked(*connection);
5805 }
5806 }
5807 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005808 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005809 connection->outboundQueue.push_front(dispatchEntry);
5810 traceOutboundQueueLength(*connection);
5811 } else {
5812 releaseDispatchEntry(dispatchEntry);
5813 }
5814 }
5815
5816 // Start the next dispatch cycle for this connection.
5817 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005818}
5819
Prabir Pradhancef936d2021-07-21 16:17:52 +00005820void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5821 const sp<IBinder>& newToken) {
5822 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5823 scoped_unlock unlock(mLock);
5824 mPolicy->notifyFocusChanged(oldToken, newToken);
5825 };
5826 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005827}
5828
Prabir Pradhancef936d2021-07-21 16:17:52 +00005829void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5830 auto command = [this, token, x, y]() REQUIRES(mLock) {
5831 scoped_unlock unlock(mLock);
5832 mPolicy->notifyDropWindow(token, x, y);
5833 };
5834 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005835}
5836
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005837void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5838 if (connection == nullptr) {
5839 LOG_ALWAYS_FATAL("Caller must check for nullness");
5840 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005841 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5842 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005843 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005844 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005845 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005846 return;
5847 }
5848 /**
5849 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5850 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5851 * has changed. This could cause newer entries to time out before the already dispatched
5852 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5853 * processes the events linearly. So providing information about the oldest entry seems to be
5854 * most useful.
5855 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005856 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005857 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5858 std::string reason =
5859 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005860 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005861 ns2ms(currentWait),
5862 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005863 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005864 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005865
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005866 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5867
5868 // Stop waking up for events on this connection, it is already unresponsive
5869 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005870}
5871
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005872void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5873 std::string reason =
5874 StringPrintf("%s does not have a focused window", application->getName().c_str());
5875 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005876
Prabir Pradhancef936d2021-07-21 16:17:52 +00005877 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5878 scoped_unlock unlock(mLock);
5879 mPolicy->notifyNoFocusedWindowAnr(application);
5880 };
5881 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005882}
5883
chaviw98318de2021-05-19 16:45:23 -05005884void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005885 const std::string& reason) {
5886 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5887 updateLastAnrStateLocked(windowLabel, reason);
5888}
5889
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005890void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5891 const std::string& reason) {
5892 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005893 updateLastAnrStateLocked(windowLabel, reason);
5894}
5895
5896void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5897 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005898 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005899 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005900 struct tm tm;
5901 localtime_r(&t, &tm);
5902 char timestr[64];
5903 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005904 mLastAnrState.clear();
5905 mLastAnrState += INDENT "ANR:\n";
5906 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005907 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5908 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005909 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005910}
5911
Prabir Pradhancef936d2021-07-21 16:17:52 +00005912void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5913 KeyEntry& entry) {
5914 const KeyEvent event = createKeyEvent(entry);
5915 nsecs_t delay = 0;
5916 { // release lock
5917 scoped_unlock unlock(mLock);
5918 android::base::Timer t;
5919 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5920 entry.policyFlags);
5921 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5922 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5923 std::to_string(t.duration().count()).c_str());
5924 }
5925 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005926
5927 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005928 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005929 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005930 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005931 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005932 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5933 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005934 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005935}
5936
Prabir Pradhancef936d2021-07-21 16:17:52 +00005937void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005938 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005939 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005940 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005941 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005942 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005943 };
5944 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005945}
5946
Prabir Pradhanedd96402022-02-15 01:46:16 -08005947void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5948 std::optional<int32_t> pid) {
5949 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005950 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005951 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005952 };
5953 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005954}
5955
5956/**
5957 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5958 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5959 * command entry to the command queue.
5960 */
5961void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5962 std::string reason) {
5963 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005964 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005965 if (connection.monitor) {
5966 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5967 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005968 pid = findMonitorPidByTokenLocked(connectionToken);
5969 } else {
5970 // The connection is a window
5971 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5972 reason.c_str());
5973 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
5974 if (handle != nullptr) {
5975 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005976 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005977 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08005978 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005979}
5980
5981/**
5982 * Tell the policy that a connection has become responsive so that it can stop ANR.
5983 */
5984void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5985 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005986 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005987 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005988 pid = findMonitorPidByTokenLocked(connectionToken);
5989 } else {
5990 // The connection is a window
5991 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
5992 if (handle != nullptr) {
5993 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005994 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005995 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08005996 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005997}
5998
Prabir Pradhancef936d2021-07-21 16:17:52 +00005999bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006000 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006001 KeyEntry& keyEntry, bool handled) {
6002 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006003 if (!handled) {
6004 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006005 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006006 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006007 return false;
6008 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006009
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006010 // Get the fallback key state.
6011 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006012 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006013 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006014 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006015 connection->inputState.removeFallbackKey(originalKeyCode);
6016 }
6017
6018 if (handled || !dispatchEntry->hasForegroundTarget()) {
6019 // If the application handles the original key for which we previously
6020 // generated a fallback or if the window is not a foreground window,
6021 // then cancel the associated fallback key, if any.
6022 if (fallbackKeyCode != -1) {
6023 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006024 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6025 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6026 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6027 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6028 keyEntry.policyFlags);
6029 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006030 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006031 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006032
6033 mLock.unlock();
6034
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006035 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006036 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006037
6038 mLock.lock();
6039
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006040 // Cancel the fallback key.
6041 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006042 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006043 "application handled the original non-fallback key "
6044 "or is no longer a foreground target, "
6045 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006046 options.keyCode = fallbackKeyCode;
6047 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006048 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006049 connection->inputState.removeFallbackKey(originalKeyCode);
6050 }
6051 } else {
6052 // If the application did not handle a non-fallback key, first check
6053 // that we are in a good state to perform unhandled key event processing
6054 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006055 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006056 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006057 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6058 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6059 "since this is not an initial down. "
6060 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6061 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6062 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006063 return false;
6064 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006065
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006066 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006067 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6068 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6069 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6070 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6071 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006072 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006073
6074 mLock.unlock();
6075
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006076 bool fallback =
6077 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006078 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006079
6080 mLock.lock();
6081
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006082 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006083 connection->inputState.removeFallbackKey(originalKeyCode);
6084 return false;
6085 }
6086
6087 // Latch the fallback keycode for this key on an initial down.
6088 // The fallback keycode cannot change at any other point in the lifecycle.
6089 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006090 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006091 fallbackKeyCode = event.getKeyCode();
6092 } else {
6093 fallbackKeyCode = AKEYCODE_UNKNOWN;
6094 }
6095 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6096 }
6097
6098 ALOG_ASSERT(fallbackKeyCode != -1);
6099
6100 // Cancel the fallback key if the policy decides not to send it anymore.
6101 // We will continue to dispatch the key to the policy but we will no
6102 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006103 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6104 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006105 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6106 if (fallback) {
6107 ALOGD("Unhandled key event: Policy requested to send key %d"
6108 "as a fallback for %d, but on the DOWN it had requested "
6109 "to send %d instead. Fallback canceled.",
6110 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6111 } else {
6112 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6113 "but on the DOWN it had requested to send %d. "
6114 "Fallback canceled.",
6115 originalKeyCode, fallbackKeyCode);
6116 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006117 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006118
6119 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6120 "canceling fallback, policy no longer desires it");
6121 options.keyCode = fallbackKeyCode;
6122 synthesizeCancelationEventsForConnectionLocked(connection, options);
6123
6124 fallback = false;
6125 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006126 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006127 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006128 }
6129 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006130
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006131 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6132 {
6133 std::string msg;
6134 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6135 connection->inputState.getFallbackKeys();
6136 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6137 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6138 }
6139 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6140 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006141 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006142 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006143
6144 if (fallback) {
6145 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006146 keyEntry.eventTime = event.getEventTime();
6147 keyEntry.deviceId = event.getDeviceId();
6148 keyEntry.source = event.getSource();
6149 keyEntry.displayId = event.getDisplayId();
6150 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6151 keyEntry.keyCode = fallbackKeyCode;
6152 keyEntry.scanCode = event.getScanCode();
6153 keyEntry.metaState = event.getMetaState();
6154 keyEntry.repeatCount = event.getRepeatCount();
6155 keyEntry.downTime = event.getDownTime();
6156 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006157
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006158 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6159 ALOGD("Unhandled key event: Dispatching fallback key. "
6160 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6161 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6162 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006163 return true; // restart the event
6164 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006165 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6166 ALOGD("Unhandled key event: No fallback key.");
6167 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006168
6169 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006170 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006171 }
6172 }
6173 return false;
6174}
6175
Prabir Pradhancef936d2021-07-21 16:17:52 +00006176bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006177 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006178 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006179 return false;
6180}
6181
Michael Wrightd02c5b62014-02-10 15:10:22 -08006182void InputDispatcher::traceInboundQueueLengthLocked() {
6183 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006184 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006185 }
6186}
6187
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006188void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006189 if (ATRACE_ENABLED()) {
6190 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006191 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6192 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006193 }
6194}
6195
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006196void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006197 if (ATRACE_ENABLED()) {
6198 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006199 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6200 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006201 }
6202}
6203
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006204void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006205 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006206
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006207 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006208 dumpDispatchStateLocked(dump);
6209
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006210 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006211 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006212 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006213 }
6214}
6215
6216void InputDispatcher::monitor() {
6217 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006218 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006219 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006220 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006221}
6222
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006223/**
6224 * Wake up the dispatcher and wait until it processes all events and commands.
6225 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6226 * this method can be safely called from any thread, as long as you've ensured that
6227 * the work you are interested in completing has already been queued.
6228 */
6229bool InputDispatcher::waitForIdle() {
6230 /**
6231 * Timeout should represent the longest possible time that a device might spend processing
6232 * events and commands.
6233 */
6234 constexpr std::chrono::duration TIMEOUT = 100ms;
6235 std::unique_lock lock(mLock);
6236 mLooper->wake();
6237 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6238 return result == std::cv_status::no_timeout;
6239}
6240
Vishnu Naire798b472020-07-23 13:52:21 -07006241/**
6242 * Sets focus to the window identified by the token. This must be called
6243 * after updating any input window handles.
6244 *
6245 * Params:
6246 * request.token - input channel token used to identify the window that should gain focus.
6247 * request.focusedToken - the token that the caller expects currently to be focused. If the
6248 * specified token does not match the currently focused window, this request will be dropped.
6249 * If the specified focused token matches the currently focused window, the call will succeed.
6250 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6251 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6252 * when requesting the focus change. This determines which request gets
6253 * precedence if there is a focus change request from another source such as pointer down.
6254 */
Vishnu Nair958da932020-08-21 17:12:37 -07006255void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6256 { // acquire lock
6257 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006258 std::optional<FocusResolver::FocusChanges> changes =
6259 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6260 if (changes) {
6261 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006262 }
6263 } // release lock
6264 // Wake up poll loop since it may need to make new input dispatching choices.
6265 mLooper->wake();
6266}
6267
Vishnu Nairc519ff72021-01-21 08:23:08 -08006268void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6269 if (changes.oldFocus) {
6270 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006271 if (focusedInputChannel) {
6272 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6273 "focus left window");
6274 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006275 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006276 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006277 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006278 if (changes.newFocus) {
6279 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006280 }
6281
Prabir Pradhan99987712020-11-10 18:43:05 -08006282 // If a window has pointer capture, then it must have focus. We need to ensure that this
6283 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6284 // If the window loses focus before it loses pointer capture, then the window can be in a state
6285 // where it has pointer capture but not focus, violating the contract. Therefore we must
6286 // dispatch the pointer capture event before the focus event. Since focus events are added to
6287 // the front of the queue (above), we add the pointer capture event to the front of the queue
6288 // after the focus events are added. This ensures the pointer capture event ends up at the
6289 // front.
6290 disablePointerCaptureForcedLocked();
6291
Vishnu Nairc519ff72021-01-21 08:23:08 -08006292 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006293 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006294 }
6295}
Vishnu Nair958da932020-08-21 17:12:37 -07006296
Prabir Pradhan99987712020-11-10 18:43:05 -08006297void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006298 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006299 return;
6300 }
6301
6302 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6303
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006304 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006305 setPointerCaptureLocked(false);
6306 }
6307
6308 if (!mWindowTokenWithPointerCapture) {
6309 // No need to send capture changes because no window has capture.
6310 return;
6311 }
6312
6313 if (mPendingEvent != nullptr) {
6314 // Move the pending event to the front of the queue. This will give the chance
6315 // for the pending event to be dropped if it is a captured event.
6316 mInboundQueue.push_front(mPendingEvent);
6317 mPendingEvent = nullptr;
6318 }
6319
6320 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006321 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006322 mInboundQueue.push_front(std::move(entry));
6323}
6324
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006325void InputDispatcher::setPointerCaptureLocked(bool enable) {
6326 mCurrentPointerCaptureRequest.enable = enable;
6327 mCurrentPointerCaptureRequest.seq++;
6328 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006329 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006330 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006331 };
6332 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006333}
6334
Vishnu Nair599f1412021-06-21 10:39:58 -07006335void InputDispatcher::displayRemoved(int32_t displayId) {
6336 { // acquire lock
6337 std::scoped_lock _l(mLock);
6338 // Set an empty list to remove all handles from the specific display.
6339 setInputWindowsLocked(/* window handles */ {}, displayId);
6340 setFocusedApplicationLocked(displayId, nullptr);
6341 // Call focus resolver to clean up stale requests. This must be called after input windows
6342 // have been removed for the removed display.
6343 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006344 // Reset pointer capture eligibility, regardless of previous state.
6345 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006346 } // release lock
6347
6348 // Wake up poll loop since it may need to make new input dispatching choices.
6349 mLooper->wake();
6350}
6351
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006352void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6353 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006354 // The listener sends the windows as a flattened array. Separate the windows by display for
6355 // more convenient parsing.
6356 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006357 for (const auto& info : windowInfos) {
6358 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6359 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6360 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006361
6362 { // acquire lock
6363 std::scoped_lock _l(mLock);
6364 mDisplayInfos.clear();
6365 for (const auto& displayInfo : displayInfos) {
6366 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6367 }
6368
6369 for (const auto& [displayId, handles] : handlesPerDisplay) {
6370 setInputWindowsLocked(handles, displayId);
6371 }
6372 }
6373 // Wake up poll loop since it may need to make new input dispatching choices.
6374 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006375}
6376
Vishnu Nair062a8672021-09-03 16:07:44 -07006377bool InputDispatcher::shouldDropInput(
6378 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006379 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6380 (windowHandle->getInfo()->inputConfig.test(
6381 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006382 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006383 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6384 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006385 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006386 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006387 windowHandle->getInfo()->displayId);
6388 return true;
6389 }
6390 return false;
6391}
6392
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006393void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6394 const std::vector<gui::WindowInfo>& windowInfos,
6395 const std::vector<DisplayInfo>& displayInfos) {
6396 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6397}
6398
Arthur Hungdfd528e2021-12-08 13:23:04 +00006399void InputDispatcher::cancelCurrentTouch() {
6400 {
6401 std::scoped_lock _l(mLock);
6402 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6403 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6404 "cancel current touch");
6405 synthesizeCancelationEventsForAllConnectionsLocked(options);
6406
6407 mTouchStatesByDisplay.clear();
6408 mLastHoverWindowHandle.clear();
6409 }
6410 // Wake up poll loop since there might be work to do.
6411 mLooper->wake();
6412}
6413
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006414void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6415 std::scoped_lock _l(mLock);
6416 mMonitorDispatchingTimeout = timeout;
6417}
6418
Garfield Tane84e6f92019-08-29 17:28:41 -07006419} // namespace android::inputdispatcher