blob: 399153c0d7132882686df6be10e7f2bbfa44df36 [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),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100547 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000548 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800549 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800550 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000551 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000552 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700553 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800554 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800555
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700556 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700557 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
558
Yi Kong9b14ac62018-07-17 13:48:38 -0700559 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800560 policy->getDispatcherConfiguration(&mConfig);
561}
562
563InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000564 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800565
Prabir Pradhancef936d2021-07-21 16:17:52 +0000566 resetKeyRepeatLocked();
567 releasePendingEventLocked();
568 drainInboundQueueLocked();
569 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800570
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000571 while (!mConnectionsByToken.empty()) {
572 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000573 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
574 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800575 }
576}
577
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700578status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700579 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700580 return ALREADY_EXISTS;
581 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700582 mThread = std::make_unique<InputThread>(
583 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
584 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700585}
586
587status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700588 if (mThread && mThread->isCallingThread()) {
589 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700590 return INVALID_OPERATION;
591 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700592 mThread.reset();
593 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700594}
595
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596void InputDispatcher::dispatchOnce() {
597 nsecs_t nextWakeupTime = LONG_LONG_MAX;
598 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800599 std::scoped_lock _l(mLock);
600 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800601
602 // Run a dispatch loop if there are no pending commands.
603 // The dispatch loop might enqueue commands to run afterwards.
604 if (!haveCommandsLocked()) {
605 dispatchOnceInnerLocked(&nextWakeupTime);
606 }
607
608 // Run all pending commands if there are any.
609 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000610 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611 nextWakeupTime = LONG_LONG_MIN;
612 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800613
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700614 // If we are still waiting for ack on some events,
615 // we might have to wake up earlier to check if an app is anr'ing.
616 const nsecs_t nextAnrCheck = processAnrsLocked();
617 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
618
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800619 // We are about to enter an infinitely long sleep, because we have no commands or
620 // pending or queued events
621 if (nextWakeupTime == LONG_LONG_MAX) {
622 mDispatcherEnteredIdle.notify_all();
623 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800624 } // release lock
625
626 // Wait for callback or timeout or wake. (make sure we round up, not down)
627 nsecs_t currentTime = now();
628 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
629 mLooper->pollOnce(timeoutMillis);
630}
631
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700632/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500633 * Raise ANR if there is no focused window.
634 * Before the ANR is raised, do a final state check:
635 * 1. The currently focused application must be the same one we are waiting for.
636 * 2. Ensure we still don't have a focused window.
637 */
638void InputDispatcher::processNoFocusedWindowAnrLocked() {
639 // Check if the application that we are waiting for is still focused.
640 std::shared_ptr<InputApplicationHandle> focusedApplication =
641 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
642 if (focusedApplication == nullptr ||
643 focusedApplication->getApplicationToken() !=
644 mAwaitedFocusedApplication->getApplicationToken()) {
645 // Unexpected because we should have reset the ANR timer when focused application changed
646 ALOGE("Waited for a focused window, but focused application has already changed to %s",
647 focusedApplication->getName().c_str());
648 return; // The focused application has changed.
649 }
650
chaviw98318de2021-05-19 16:45:23 -0500651 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500652 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
653 if (focusedWindowHandle != nullptr) {
654 return; // We now have a focused window. No need for ANR.
655 }
656 onAnrLocked(mAwaitedFocusedApplication);
657}
658
659/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700660 * Check if any of the connections' wait queues have events that are too old.
661 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
662 * Return the time at which we should wake up next.
663 */
664nsecs_t InputDispatcher::processAnrsLocked() {
665 const nsecs_t currentTime = now();
666 nsecs_t nextAnrCheck = LONG_LONG_MAX;
667 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
668 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
669 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500670 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700671 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500672 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700673 return LONG_LONG_MIN;
674 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500675 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700676 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
677 }
678 }
679
680 // Check if any connection ANRs are due
681 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
682 if (currentTime < nextAnrCheck) { // most likely scenario
683 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
684 }
685
686 // If we reached here, we have an unresponsive connection.
687 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
688 if (connection == nullptr) {
689 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
690 return nextAnrCheck;
691 }
692 connection->responsive = false;
693 // Stop waking up for this unresponsive connection
694 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000695 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700696 return LONG_LONG_MIN;
697}
698
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800699std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
700 const sp<Connection>& connection) {
701 if (connection->monitor) {
702 return mMonitorDispatchingTimeout;
703 }
704 const sp<WindowInfoHandle> window =
705 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700706 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500707 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700708 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500709 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700710}
711
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
713 nsecs_t currentTime = now();
714
Jeff Browndc5992e2014-04-11 01:27:26 -0700715 // Reset the key repeat timer whenever normal dispatch is suspended while the
716 // device is in a non-interactive state. This is to ensure that we abort a key
717 // repeat if the device is just coming out of sleep.
718 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800719 resetKeyRepeatLocked();
720 }
721
722 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
723 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100724 if (DEBUG_FOCUS) {
725 ALOGD("Dispatch frozen. Waiting some more.");
726 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800727 return;
728 }
729
730 // Optimize latency of app switches.
731 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
732 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
733 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
734 if (mAppSwitchDueTime < *nextWakeupTime) {
735 *nextWakeupTime = mAppSwitchDueTime;
736 }
737
738 // Ready to start a new event.
739 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700740 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700741 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742 if (isAppSwitchDue) {
743 // The inbound queue is empty so the app switch key we were waiting
744 // for will never arrive. Stop waiting for it.
745 resetPendingAppSwitchLocked(false);
746 isAppSwitchDue = false;
747 }
748
749 // Synthesize a key repeat if appropriate.
750 if (mKeyRepeatState.lastKeyEntry) {
751 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
752 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
753 } else {
754 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
755 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
756 }
757 }
758 }
759
760 // Nothing to do if there is no pending event.
761 if (!mPendingEvent) {
762 return;
763 }
764 } else {
765 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700766 mPendingEvent = mInboundQueue.front();
767 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800768 traceInboundQueueLengthLocked();
769 }
770
771 // Poke user activity for this event.
772 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700773 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800775 }
776
777 // Now we have an event to dispatch.
778 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700779 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700781 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700783 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800784 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700785 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786 }
787
788 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700789 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800790 }
791
792 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700793 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700794 const ConfigurationChangedEntry& typedEntry =
795 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700796 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700797 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700798 break;
799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800800
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700801 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700802 const DeviceResetEntry& typedEntry =
803 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700804 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700805 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700806 break;
807 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800808
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100809 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700810 std::shared_ptr<FocusEntry> typedEntry =
811 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100812 dispatchFocusLocked(currentTime, typedEntry);
813 done = true;
814 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
815 break;
816 }
817
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700818 case EventEntry::Type::TOUCH_MODE_CHANGED: {
819 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
820 dispatchTouchModeChangeLocked(currentTime, typedEntry);
821 done = true;
822 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
823 break;
824 }
825
Prabir Pradhan99987712020-11-10 18:43:05 -0800826 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
827 const auto typedEntry =
828 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
829 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
830 done = true;
831 break;
832 }
833
arthurhungb89ccb02020-12-30 16:19:01 +0800834 case EventEntry::Type::DRAG: {
835 std::shared_ptr<DragEntry> typedEntry =
836 std::static_pointer_cast<DragEntry>(mPendingEvent);
837 dispatchDragLocked(currentTime, typedEntry);
838 done = true;
839 break;
840 }
841
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700842 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700843 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700844 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700845 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700846 resetPendingAppSwitchLocked(true);
847 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700848 } else if (dropReason == DropReason::NOT_DROPPED) {
849 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700850 }
851 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700852 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700853 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700854 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700855 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
856 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700857 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700858 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700859 break;
860 }
861
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700862 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700863 std::shared_ptr<MotionEntry> motionEntry =
864 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700865 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
866 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700868 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700869 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700870 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700871 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
872 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700873 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700874 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700875 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800876 }
Chris Yef59a2f42020-10-16 12:55:26 -0700877
878 case EventEntry::Type::SENSOR: {
879 std::shared_ptr<SensorEntry> sensorEntry =
880 std::static_pointer_cast<SensorEntry>(mPendingEvent);
881 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
882 dropReason = DropReason::APP_SWITCH;
883 }
884 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
885 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
886 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
887 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
888 dropReason = DropReason::STALE;
889 }
890 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
891 done = true;
892 break;
893 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 }
895
896 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700897 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700898 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 }
Michael Wright3a981722015-06-10 15:26:13 +0100900 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901
902 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700903 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 }
905}
906
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800907bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
908 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
909}
910
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700911/**
912 * Return true if the events preceding this incoming motion event should be dropped
913 * Return false otherwise (the default behaviour)
914 */
915bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700916 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700917 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700918
919 // Optimize case where the current application is unresponsive and the user
920 // decides to touch a window in a different application.
921 // If the application takes too long to catch up then we drop all events preceding
922 // the touch into the other window.
923 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700924 int32_t displayId = motionEntry.displayId;
925 int32_t x = static_cast<int32_t>(
926 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
927 int32_t y = static_cast<int32_t>(
928 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Prabir Pradhand65552b2021-10-07 11:23:50 -0700929
930 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -0500931 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700932 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700933 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700934 touchedWindowHandle->getApplicationToken() !=
935 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700936 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700937 ALOGI("Pruning input queue because user touched a different application while waiting "
938 "for %s",
939 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700940 return true;
941 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700942
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800943 // Alternatively, maybe there's a spy window that could handle this event.
944 const std::vector<sp<WindowInfoHandle>> touchedSpies =
945 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
946 for (const auto& windowHandle : touchedSpies) {
947 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000948 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800949 // This spy window could take more input. Drop all events preceding this
950 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700951 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800952 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700953 mAwaitedFocusedApplication->getName().c_str());
954 return true;
955 }
956 }
957 }
958
959 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
960 // yet been processed by some connections, the dispatcher will wait for these motion
961 // events to be processed before dispatching the key event. This is because these motion events
962 // may cause a new window to be launched, which the user might expect to receive focus.
963 // To prevent waiting forever for such events, just send the key to the currently focused window
964 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
965 ALOGD("Received a new pointer down event, stop waiting for events to process and "
966 "just send the pending key event to the focused window.");
967 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700968 }
969 return false;
970}
971
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700972bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700973 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700974 mInboundQueue.push_back(std::move(newEntry));
975 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800976 traceInboundQueueLengthLocked();
977
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700978 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700979 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +0000980 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
981 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700982 // Optimize app switch latency.
983 // If the application takes too long to catch up then we drop all events preceding
984 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700985 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700986 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700987 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700988 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700989 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700990 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000991 if (DEBUG_APP_SWITCH) {
992 ALOGD("App switch is pending!");
993 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700994 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700995 mAppSwitchSawKeyDown = false;
996 needWake = true;
997 }
998 }
999 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001000
1001 // If a new up event comes in, and the pending event with same key code has been asked
1002 // to try again later because of the policy. We have to reset the intercept key wake up
1003 // time for it may have been handled in the policy and could be dropped.
1004 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1005 mPendingEvent->type == EventEntry::Type::KEY) {
1006 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1007 if (pendingKey.keyCode == keyEntry.keyCode &&
1008 pendingKey.interceptKeyResult ==
1009 KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1010 pendingKey.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1011 pendingKey.interceptKeyWakeupTime = 0;
1012 needWake = true;
1013 }
1014 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001015 break;
1016 }
1017
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001018 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001019 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1020 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001021 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1022 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001023 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001025 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001027 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001028 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1029 break;
1030 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001031 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001032 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001033 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001034 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001035 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1036 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001037 // nothing to do
1038 break;
1039 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040 }
1041
1042 return needWake;
1043}
1044
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001045void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001046 // Do not store sensor event in recent queue to avoid flooding the queue.
1047 if (entry->type != EventEntry::Type::SENSOR) {
1048 mRecentQueue.push_back(entry);
1049 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001050 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001051 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001052 }
1053}
1054
chaviw98318de2021-05-19 16:45:23 -05001055sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1056 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001057 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001058 bool addOutsideTargets,
1059 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001060 if (addOutsideTargets && touchState == nullptr) {
1061 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001063 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001064 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001065 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001066 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001067 continue;
1068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001070 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001071 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001072 return windowHandle;
1073 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001074
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001075 if (addOutsideTargets &&
1076 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001077 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1078 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079 }
1080 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001081 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082}
1083
Prabir Pradhand65552b2021-10-07 11:23:50 -07001084std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1085 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001086 // Traverse windows from front to back and gather the touched spy windows.
1087 std::vector<sp<WindowInfoHandle>> spyWindows;
1088 const auto& windowHandles = getWindowHandlesLocked(displayId);
1089 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1090 const WindowInfo& info = *windowHandle->getInfo();
1091
Prabir Pradhand65552b2021-10-07 11:23:50 -07001092 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001093 continue;
1094 }
1095 if (!info.isSpy()) {
1096 // The first touched non-spy window was found, so return the spy windows touched so far.
1097 return spyWindows;
1098 }
1099 spyWindows.push_back(windowHandle);
1100 }
1101 return spyWindows;
1102}
1103
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001104void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001105 const char* reason;
1106 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001107 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001108 if (DEBUG_INBOUND_EVENT_DETAILS) {
1109 ALOGD("Dropped event because policy consumed it.");
1110 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001111 reason = "inbound event was dropped because the policy consumed it";
1112 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001113 case DropReason::DISABLED:
1114 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001115 ALOGI("Dropped event because input dispatch is disabled.");
1116 }
1117 reason = "inbound event was dropped because input dispatch is disabled";
1118 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001119 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001120 ALOGI("Dropped event because of pending overdue app switch.");
1121 reason = "inbound event was dropped because of pending overdue app switch";
1122 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001123 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001124 ALOGI("Dropped event because the current application is not responding and the user "
1125 "has started interacting with a different application.");
1126 reason = "inbound event was dropped because the current application is not responding "
1127 "and the user has started interacting with a different application";
1128 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001129 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001130 ALOGI("Dropped event because it is stale.");
1131 reason = "inbound event was dropped because it is stale";
1132 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001133 case DropReason::NO_POINTER_CAPTURE:
1134 ALOGI("Dropped event because there is no window with Pointer Capture.");
1135 reason = "inbound event was dropped because there is no window with Pointer Capture";
1136 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001137 case DropReason::NOT_DROPPED: {
1138 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001139 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001140 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141 }
1142
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001143 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001144 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001145 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1146 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001147 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001149 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001150 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1151 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001152 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1153 synthesizeCancelationEventsForAllConnectionsLocked(options);
1154 } else {
1155 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1156 synthesizeCancelationEventsForAllConnectionsLocked(options);
1157 }
1158 break;
1159 }
Chris Yef59a2f42020-10-16 12:55:26 -07001160 case EventEntry::Type::SENSOR: {
1161 break;
1162 }
arthurhungb89ccb02020-12-30 16:19:01 +08001163 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1164 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001165 break;
1166 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001167 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001168 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001169 case EventEntry::Type::CONFIGURATION_CHANGED:
1170 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001171 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001172 break;
1173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 }
1175}
1176
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001177static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001178 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1179 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180}
1181
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001182bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1183 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1184 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1185 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186}
1187
1188bool InputDispatcher::isAppSwitchPendingLocked() {
1189 return mAppSwitchDueTime != LONG_LONG_MAX;
1190}
1191
1192void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1193 mAppSwitchDueTime = LONG_LONG_MAX;
1194
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001195 if (DEBUG_APP_SWITCH) {
1196 if (handled) {
1197 ALOGD("App switch has arrived.");
1198 } else {
1199 ALOGD("App switch was abandoned.");
1200 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202}
1203
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001205 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206}
1207
Prabir Pradhancef936d2021-07-21 16:17:52 +00001208bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001209 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210 return false;
1211 }
1212
1213 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001214 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001215 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001216 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1217 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001218 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219 return true;
1220}
1221
Prabir Pradhancef936d2021-07-21 16:17:52 +00001222void InputDispatcher::postCommandLocked(Command&& command) {
1223 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224}
1225
1226void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001227 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001228 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001229 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230 releaseInboundEventLocked(entry);
1231 }
1232 traceInboundQueueLengthLocked();
1233}
1234
1235void InputDispatcher::releasePendingEventLocked() {
1236 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001238 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239 }
1240}
1241
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001242void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001244 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001245 if (DEBUG_DISPATCH_CYCLE) {
1246 ALOGD("Injected inbound event was dropped.");
1247 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001248 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 }
1250 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001251 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 }
1253 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254}
1255
1256void InputDispatcher::resetKeyRepeatLocked() {
1257 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001258 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259 }
1260}
1261
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001262std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1263 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264
Michael Wright2e732952014-09-24 13:26:59 -07001265 uint32_t policyFlags = entry->policyFlags &
1266 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001268 std::shared_ptr<KeyEntry> newEntry =
1269 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1270 entry->source, entry->displayId, policyFlags, entry->action,
1271 entry->flags, entry->keyCode, entry->scanCode,
1272 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001274 newEntry->syntheticRepeat = true;
1275 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001277 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278}
1279
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001280bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001281 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001282 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1283 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1284 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001285
1286 // Reset key repeating in case a keyboard device was added or removed or something.
1287 resetKeyRepeatLocked();
1288
1289 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001290 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1291 scoped_unlock unlock(mLock);
1292 mPolicy->notifyConfigurationChanged(eventTime);
1293 };
1294 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295 return true;
1296}
1297
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001298bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1299 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001300 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1301 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1302 entry.deviceId);
1303 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304
liushenxiang42232912021-05-21 20:24:09 +08001305 // Reset key repeating in case a keyboard device was disabled or enabled.
1306 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1307 resetKeyRepeatLocked();
1308 }
1309
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001310 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001311 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001312 synthesizeCancelationEventsForAllConnectionsLocked(options);
1313 return true;
1314}
1315
Vishnu Nairad321cd2020-08-20 16:40:21 -07001316void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001317 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001318 if (mPendingEvent != nullptr) {
1319 // Move the pending event to the front of the queue. This will give the chance
1320 // for the pending event to get dispatched to the newly focused window
1321 mInboundQueue.push_front(mPendingEvent);
1322 mPendingEvent = nullptr;
1323 }
1324
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001325 std::unique_ptr<FocusEntry> focusEntry =
1326 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1327 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001328
1329 // This event should go to the front of the queue, but behind all other focus events
1330 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001331 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001332 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001333 [](const std::shared_ptr<EventEntry>& event) {
1334 return event->type == EventEntry::Type::FOCUS;
1335 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001336
1337 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001338 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001339}
1340
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001341void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001342 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001343 if (channel == nullptr) {
1344 return; // Window has gone away
1345 }
1346 InputTarget target;
1347 target.inputChannel = channel;
1348 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1349 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001350 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1351 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001352 std::string reason = std::string("reason=").append(entry->reason);
1353 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001354 dispatchEventLocked(currentTime, entry, {target});
1355}
1356
Prabir Pradhan99987712020-11-10 18:43:05 -08001357void InputDispatcher::dispatchPointerCaptureChangedLocked(
1358 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1359 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001360 dropReason = DropReason::NOT_DROPPED;
1361
Prabir Pradhan99987712020-11-10 18:43:05 -08001362 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001363 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001364
1365 if (entry->pointerCaptureRequest.enable) {
1366 // Enable Pointer Capture.
1367 if (haveWindowWithPointerCapture &&
1368 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001369 // This can happen if pointer capture is disabled and re-enabled before we notify the
1370 // app of the state change, so there is no need to notify the app.
1371 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1372 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001373 }
1374 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001375 // This can happen if a window requests capture and immediately releases capture.
1376 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001377 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001378 return;
1379 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001380 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1381 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1382 return;
1383 }
1384
Vishnu Nairc519ff72021-01-21 08:23:08 -08001385 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001386 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1387 mWindowTokenWithPointerCapture = token;
1388 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001389 // Disable Pointer Capture.
1390 // We do not check if the sequence number matches for requests to disable Pointer Capture
1391 // for two reasons:
1392 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1393 // to disable capture with the same sequence number: one generated by
1394 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1395 // Capture being disabled in InputReader.
1396 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1397 // actual Pointer Capture state that affects events being generated by input devices is
1398 // in InputReader.
1399 if (!haveWindowWithPointerCapture) {
1400 // Pointer capture was already forcefully disabled because of focus change.
1401 dropReason = DropReason::NOT_DROPPED;
1402 return;
1403 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001404 token = mWindowTokenWithPointerCapture;
1405 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001406 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001407 setPointerCaptureLocked(false);
1408 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001409 }
1410
1411 auto channel = getInputChannelLocked(token);
1412 if (channel == nullptr) {
1413 // Window has gone away, clean up Pointer Capture state.
1414 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001415 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001416 setPointerCaptureLocked(false);
1417 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001418 return;
1419 }
1420 InputTarget target;
1421 target.inputChannel = channel;
1422 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1423 entry->dispatchInProgress = true;
1424 dispatchEventLocked(currentTime, entry, {target});
1425
1426 dropReason = DropReason::NOT_DROPPED;
1427}
1428
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001429void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1430 const std::shared_ptr<TouchModeEntry>& entry) {
1431 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001432 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001433 if (windowHandles.empty()) {
1434 return;
1435 }
1436 const std::vector<InputTarget> inputTargets =
1437 getInputTargetsFromWindowHandlesLocked(windowHandles);
1438 if (inputTargets.empty()) {
1439 return;
1440 }
1441 entry->dispatchInProgress = true;
1442 dispatchEventLocked(currentTime, entry, inputTargets);
1443}
1444
1445std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1446 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1447 std::vector<InputTarget> inputTargets;
1448 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001449 const sp<IBinder>& token = handle->getToken();
1450 if (token == nullptr) {
1451 continue;
1452 }
1453 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1454 if (channel == nullptr) {
1455 continue; // Window has gone away
1456 }
1457 InputTarget target;
1458 target.inputChannel = channel;
1459 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1460 inputTargets.push_back(target);
1461 }
1462 return inputTargets;
1463}
1464
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001465bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001466 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001467 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001468 if (!entry->dispatchInProgress) {
1469 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1470 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1471 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1472 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001473 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474 // We have seen two identical key downs in a row which indicates that the device
1475 // driver is automatically generating key repeats itself. We take note of the
1476 // repeat here, but we disable our own next key repeat timer since it is clear that
1477 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001478 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1479 // Make sure we don't get key down from a different device. If a different
1480 // device Id has same key pressed down, the new device Id will replace the
1481 // current one to hold the key repeat with repeat count reset.
1482 // In the future when got a KEY_UP on the device id, drop it and do not
1483 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1485 resetKeyRepeatLocked();
1486 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1487 } else {
1488 // Not a repeat. Save key down state in case we do see a repeat later.
1489 resetKeyRepeatLocked();
1490 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1491 }
1492 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001493 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1494 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001495 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001496 if (DEBUG_INBOUND_EVENT_DETAILS) {
1497 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1498 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001499 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001500 resetKeyRepeatLocked();
1501 }
1502
1503 if (entry->repeatCount == 1) {
1504 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1505 } else {
1506 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1507 }
1508
1509 entry->dispatchInProgress = true;
1510
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001511 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 }
1513
1514 // Handle case where the policy asked us to try again later last time.
1515 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1516 if (currentTime < entry->interceptKeyWakeupTime) {
1517 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1518 *nextWakeupTime = entry->interceptKeyWakeupTime;
1519 }
1520 return false; // wait until next wakeup
1521 }
1522 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1523 entry->interceptKeyWakeupTime = 0;
1524 }
1525
1526 // Give the policy a chance to intercept the key.
1527 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1528 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001529 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001530 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001531
1532 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1533 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1534 };
1535 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001536 return false; // wait for the command to run
1537 } else {
1538 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1539 }
1540 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001541 if (*dropReason == DropReason::NOT_DROPPED) {
1542 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543 }
1544 }
1545
1546 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001547 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001548 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001549 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1550 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001551 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552 return true;
1553 }
1554
1555 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001556 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001557 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001558 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001559 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560 return false;
1561 }
1562
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001563 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001564 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 return true;
1566 }
1567
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001568 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001569 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570
1571 // Dispatch the key.
1572 dispatchEventLocked(currentTime, entry, inputTargets);
1573 return true;
1574}
1575
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001576void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001577 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1578 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1579 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1580 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1581 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1582 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1583 entry.metaState, entry.repeatCount, entry.downTime);
1584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585}
1586
Prabir Pradhancef936d2021-07-21 16:17:52 +00001587void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1588 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001589 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001590 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1591 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1592 "source=0x%x, sensorType=%s",
1593 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001594 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001595 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001596 auto command = [this, entry]() REQUIRES(mLock) {
1597 scoped_unlock unlock(mLock);
1598
1599 if (entry->accuracyChanged) {
1600 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1601 }
1602 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1603 entry->hwTimestamp, entry->values);
1604 };
1605 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001606}
1607
1608bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001609 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1610 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001611 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001612 }
Chris Yef59a2f42020-10-16 12:55:26 -07001613 { // acquire lock
1614 std::scoped_lock _l(mLock);
1615
1616 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1617 std::shared_ptr<EventEntry> entry = *it;
1618 if (entry->type == EventEntry::Type::SENSOR) {
1619 it = mInboundQueue.erase(it);
1620 releaseInboundEventLocked(entry);
1621 }
1622 }
1623 }
1624 return true;
1625}
1626
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001627bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001628 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001629 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001631 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632 entry->dispatchInProgress = true;
1633
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001634 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635 }
1636
1637 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001638 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001639 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001640 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1641 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642 return true;
1643 }
1644
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001645 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001646
1647 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001648 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649
1650 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001651 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 if (isPointerEvent) {
1653 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001654
1655 if (mDragState &&
1656 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1657 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1658 pilferPointersLocked(mDragState->dragWindow->getToken());
1659 }
1660
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001661 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001662 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001663 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 } else {
1665 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001666 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001667 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001669 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670 return false;
1671 }
1672
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001673 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001674 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001675 return true;
1676 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001677 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001678 CancelationOptions::Mode mode(isPointerEvent
1679 ? CancelationOptions::CANCEL_POINTER_EVENTS
1680 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1681 CancelationOptions options(mode, "input event injection failed");
1682 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 return true;
1684 }
1685
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001686 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001687 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688
1689 // Dispatch the motion.
1690 if (conflictingPointerActions) {
1691 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001692 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001693 synthesizeCancelationEventsForAllConnectionsLocked(options);
1694 }
1695 dispatchEventLocked(currentTime, entry, inputTargets);
1696 return true;
1697}
1698
chaviw98318de2021-05-19 16:45:23 -05001699void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001700 bool isExiting, const int32_t rawX,
1701 const int32_t rawY) {
1702 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001703 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001704 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1705 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001706
1707 enqueueInboundEventLocked(std::move(dragEntry));
1708}
1709
1710void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1711 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1712 if (channel == nullptr) {
1713 return; // Window has gone away
1714 }
1715 InputTarget target;
1716 target.inputChannel = channel;
1717 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1718 entry->dispatchInProgress = true;
1719 dispatchEventLocked(currentTime, entry, {target});
1720}
1721
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001722void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001723 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1724 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1725 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001726 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001727 "metaState=0x%x, buttonState=0x%x,"
1728 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1729 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001730 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1731 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1732 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001734 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1735 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1736 "x=%f, y=%f, pressure=%f, size=%f, "
1737 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1738 "orientation=%f",
1739 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1740 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1741 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1742 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1743 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1744 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1745 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1746 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1747 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1748 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751}
1752
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001753void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1754 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001755 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001756 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001757 if (DEBUG_DISPATCH_CYCLE) {
1758 ALOGD("dispatchEventToCurrentInputTargets");
1759 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001760
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001761 updateInteractionTokensLocked(*eventEntry, inputTargets);
1762
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1764
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001765 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001767 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001768 sp<Connection> connection =
1769 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001770 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001771 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001773 if (DEBUG_FOCUS) {
1774 ALOGD("Dropping event delivery to target with channel '%s' because it "
1775 "is no longer registered with the input dispatcher.",
1776 inputTarget.inputChannel->getName().c_str());
1777 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778 }
1779 }
1780}
1781
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001782void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1783 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1784 // If the policy decides to close the app, we will get a channel removal event via
1785 // unregisterInputChannel, and will clean up the connection that way. We are already not
1786 // sending new pointers to the connection when it blocked, but focused events will continue to
1787 // pile up.
1788 ALOGW("Canceling events for %s because it is unresponsive",
1789 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001790 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001791 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1792 "application not responding");
1793 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794 }
1795}
1796
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001797void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001798 if (DEBUG_FOCUS) {
1799 ALOGD("Resetting ANR timeouts.");
1800 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001801
1802 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001803 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001804 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805}
1806
Tiger Huang721e26f2018-07-24 22:26:19 +08001807/**
1808 * Get the display id that the given event should go to. If this event specifies a valid display id,
1809 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1810 * Focused display is the display that the user most recently interacted with.
1811 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001812int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001813 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001814 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001815 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001816 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1817 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001818 break;
1819 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001820 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001821 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1822 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001823 break;
1824 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001825 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001826 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001827 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001828 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001829 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001830 case EventEntry::Type::SENSOR:
1831 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001832 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001833 return ADISPLAY_ID_NONE;
1834 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001835 }
1836 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1837}
1838
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001839bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1840 const char* focusedWindowName) {
1841 if (mAnrTracker.empty()) {
1842 // already processed all events that we waited for
1843 mKeyIsWaitingForEventsTimeout = std::nullopt;
1844 return false;
1845 }
1846
1847 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1848 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001849 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001850 mKeyIsWaitingForEventsTimeout = currentTime +
1851 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1852 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001853 return true;
1854 }
1855
1856 // We still have pending events, and already started the timer
1857 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1858 return true; // Still waiting
1859 }
1860
1861 // Waited too long, and some connection still hasn't processed all motions
1862 // Just send the key to the focused window
1863 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1864 focusedWindowName);
1865 mKeyIsWaitingForEventsTimeout = std::nullopt;
1866 return false;
1867}
1868
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001869static std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
1870 if (eventEntry.type == EventEntry::Type::KEY) {
1871 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
1872 return keyEntry.downTime;
1873 } else if (eventEntry.type == EventEntry::Type::MOTION) {
1874 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
1875 return motionEntry.downTime;
1876 }
1877 return std::nullopt;
1878}
1879
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001880InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1881 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1882 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001883 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001884
Tiger Huang721e26f2018-07-24 22:26:19 +08001885 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001886 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001887 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001888 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1889
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890 // If there is no currently focused window and no focused application
1891 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001892 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1893 ALOGI("Dropping %s event because there is no focused window or focused application in "
1894 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001895 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001896 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897 }
1898
Vishnu Nair062a8672021-09-03 16:07:44 -07001899 // Drop key events if requested by input feature
1900 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1901 return InputEventInjectionResult::FAILED;
1902 }
1903
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001904 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1905 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1906 // start interacting with another application via touch (app switch). This code can be removed
1907 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1908 // an app is expected to have a focused window.
1909 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1910 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1911 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001912 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1913 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1914 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001915 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001916 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001917 ALOGW("Waiting because no window has focus but %s may eventually add a "
1918 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001919 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001920 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001921 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001922 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1923 // Already raised ANR. Drop the event
1924 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001925 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001926 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001927 } else {
1928 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001929 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001930 }
1931 }
1932
1933 // we have a valid, non-null focused window
1934 resetNoFocusedWindowTimeoutLocked();
1935
Prabir Pradhan5735a322022-04-11 17:23:34 +00001936 // Verify targeted injection.
1937 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
1938 ALOGW("Dropping injected event: %s", (*err).c_str());
1939 return InputEventInjectionResult::TARGET_MISMATCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001940 }
1941
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001942 if (focusedWindowHandle->getInfo()->inputConfig.test(
1943 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001944 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001945 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001946 }
1947
1948 // If the event is a key event, then we must wait for all previous events to
1949 // complete before delivering it because previous events may have the
1950 // side-effect of transferring focus to a different window and we want to
1951 // ensure that the following keys are sent to the new window.
1952 //
1953 // Suppose the user touches a button in a window then immediately presses "A".
1954 // If the button causes a pop-up window to appear then we want to ensure that
1955 // the "A" key is delivered to the new pop-up window. This is because users
1956 // often anticipate pending UI changes when typing on a keyboard.
1957 // To obtain this behavior, we must serialize key events with respect to all
1958 // prior input events.
1959 if (entry.type == EventEntry::Type::KEY) {
1960 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1961 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001962 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001963 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 }
1965
1966 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001967 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001968 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001969 BitSet32(0), getDownTime(entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970
1971 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001972 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973}
1974
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001975/**
1976 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1977 * that are currently unresponsive.
1978 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001979std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1980 const std::vector<Monitor>& monitors) const {
1981 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001982 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001983 [this](const Monitor& monitor) REQUIRES(mLock) {
1984 sp<Connection> connection =
1985 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001986 if (connection == nullptr) {
1987 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001988 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001989 return false;
1990 }
1991 if (!connection->responsive) {
1992 ALOGW("Unresponsive monitor %s will not get the new gesture",
1993 connection->inputChannel->getName().c_str());
1994 return false;
1995 }
1996 return true;
1997 });
1998 return responsiveMonitors;
1999}
2000
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002001InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
2002 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
2003 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002004 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 // For security reasons, we defer updating the touch state until we are sure that
2007 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002008 const int32_t displayId = entry.displayId;
2009 const int32_t action = entry.action;
2010 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011
2012 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002013 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
chaviw98318de2021-05-19 16:45:23 -05002014 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2015 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002017 // Copy current touch state into tempTouchState.
2018 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2019 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002020 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002021 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002022 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2023 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002024 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002025 }
2026
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002027 bool isSplit = tempTouchState.split;
2028 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2029 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2030 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002031
2032 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2033 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2034 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2035 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2036 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002037 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038 bool wrongDevice = false;
2039 if (newGesture) {
2040 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002041 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002042 ALOGI("Dropping event because a pointer for a different device is already down "
2043 "in display %" PRId32,
2044 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002045 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002046 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047 switchedDevice = false;
2048 wrongDevice = true;
2049 goto Failed;
2050 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002051 tempTouchState.reset();
2052 tempTouchState.down = down;
2053 tempTouchState.deviceId = entry.deviceId;
2054 tempTouchState.source = entry.source;
2055 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002056 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002057 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002058 ALOGI("Dropping move event because a pointer for a different device is already active "
2059 "in display %" PRId32,
2060 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002061 // TODO: test multiple simultaneous input streams.
Prabir Pradhan5735a322022-04-11 17:23:34 +00002062 injectionResult = InputEventInjectionResult::FAILED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002063 switchedDevice = false;
2064 wrongDevice = true;
2065 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002066 }
2067
2068 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2069 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2070
Garfield Tan00f511d2019-06-12 16:55:40 -07002071 int32_t x;
2072 int32_t y;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002073 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002074 // Always dispatch mouse events to cursor position.
2075 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002076 x = int32_t(entry.xCursorPosition);
2077 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002078 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002079 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2080 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002081 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002082 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002083 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002084 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002085 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002086
Michael Wrightd02c5b62014-02-10 15:10:22 -08002087 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002088 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002089 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2090 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002092 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002093 }
2094
Prabir Pradhan5735a322022-04-11 17:23:34 +00002095 // Verify targeted injection.
2096 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2097 ALOGW("Dropping injected touch event: %s", (*err).c_str());
2098 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2099 newTouchedWindowHandle = nullptr;
2100 goto Failed;
2101 }
2102
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002103 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002104 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002105 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2106 // New window supports splitting, but we should never split mouse events.
2107 isSplit = !isFromMouse;
2108 } else if (isSplit) {
2109 // New window does not support splitting but we have already split events.
2110 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002111 newTouchedWindowHandle = nullptr;
2112 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002113 } else {
2114 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002115 // be delivered to a new window which supports split touch. Pointers from a mouse device
2116 // should never be split.
2117 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002118 }
2119
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002120 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002121 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002122 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2123 newHoverWindowHandle = nullptr;
2124 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002125 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002126 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002127 }
2128
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002129 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002130 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002131 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002132 // Process the foreground window first so that it is the first to receive the event.
2133 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002134 }
2135
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002136 if (newTouchedWindows.empty()) {
2137 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2138 x, y, displayId);
2139 injectionResult = InputEventInjectionResult::FAILED;
2140 goto Failed;
2141 }
2142
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002143 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2144 const WindowInfo& info = *windowHandle->getInfo();
2145
Prabir Pradhan5735a322022-04-11 17:23:34 +00002146 // Skip spy window targets that are not valid for targeted injection.
2147 if (const auto err = verifyTargetedInjection(windowHandle, entry); err) {
2148 continue;
2149 }
2150
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002151 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002152 ALOGI("Not sending touch event to %s because it is paused",
2153 windowHandle->getName().c_str());
2154 continue;
2155 }
2156
2157 // Ensure the window has a connection and the connection is responsive
2158 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2159 if (!isResponsive) {
2160 ALOGW("Not sending touch gesture to %s because it is not responsive",
2161 windowHandle->getName().c_str());
2162 continue;
2163 }
2164
2165 // Drop events that can't be trusted due to occlusion
Hani Kazmi3ce9c3a2022-04-25 09:40:23 +00002166 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(windowHandle, x, y);
2167 if (!isTouchTrustedLocked(occlusionInfo)) {
2168 if (DEBUG_TOUCH_OCCLUSION) {
2169 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2170 for (const auto& log : occlusionInfo.debugInfo) {
2171 ALOGD("%s", log.c_str());
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002172 }
2173 }
Hani Kazmi3ce9c3a2022-04-25 09:40:23 +00002174 ALOGW("Dropping untrusted touch event due to %s/%d",
2175 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2176 continue;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002177 }
2178
2179 // Drop touch events if requested by input feature
2180 if (shouldDropInput(entry, windowHandle)) {
2181 continue;
2182 }
2183
2184 // Set target flags.
2185 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2186
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002187 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2188 // There should only be one touched window that can be "foreground" for the pointer.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002189 targetFlags |= InputTarget::FLAG_FOREGROUND;
2190 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002191
2192 if (isSplit) {
2193 targetFlags |= InputTarget::FLAG_SPLIT;
2194 }
2195 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2196 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2197 } else if (isWindowObscuredLocked(windowHandle)) {
2198 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2199 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002200
2201 // Update the temporary touch state.
2202 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002203 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002204
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002205 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
2206 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002208
2209 // If any existing window is pilfering pointers from newly added window, remove it
2210 BitSet32 canceledPointers = BitSet32(0);
2211 for (const TouchedWindow& window : tempTouchState.windows) {
2212 if (window.isPilferingPointers) {
2213 canceledPointers |= window.pointerIds;
2214 }
2215 }
2216 tempTouchState.cancelPointersForNonPilferingWindows(canceledPointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002217 } else {
2218 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2219
2220 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002221 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002222 if (DEBUG_FOCUS) {
2223 ALOGD("Dropping event because the pointer is not down or we previously "
2224 "dropped the pointer down event in display %" PRId32,
2225 displayId);
2226 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002227 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228 goto Failed;
2229 }
2230
arthurhung6d4bed92021-03-17 11:59:33 +08002231 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002232
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002234 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002235 tempTouchState.isSlippery()) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002236 const int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2237 const int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238
Prabir Pradhand65552b2021-10-07 11:23:50 -07002239 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002240 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002241 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002242 newTouchedWindowHandle =
2243 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002244
Prabir Pradhan5735a322022-04-11 17:23:34 +00002245 // Verify targeted injection.
2246 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2247 ALOGW("Dropping injected event: %s", (*err).c_str());
2248 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2249 newTouchedWindowHandle = nullptr;
2250 goto Failed;
2251 }
2252
Vishnu Nair062a8672021-09-03 16:07:44 -07002253 // Drop touch events if requested by input feature
2254 if (newTouchedWindowHandle != nullptr &&
2255 shouldDropInput(entry, newTouchedWindowHandle)) {
2256 newTouchedWindowHandle = nullptr;
2257 }
2258
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002259 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2260 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002261 if (DEBUG_FOCUS) {
2262 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2263 oldTouchedWindowHandle->getName().c_str(),
2264 newTouchedWindowHandle->getName().c_str(), displayId);
2265 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002267 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2268 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2269 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270
2271 // Make a slippery entrance into the new window.
2272 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002273 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274 }
2275
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002276 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
2277 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
2278 targetFlags |= InputTarget::FLAG_FOREGROUND;
2279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 if (isSplit) {
2281 targetFlags |= InputTarget::FLAG_SPLIT;
2282 }
2283 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2284 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002285 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2286 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002287 }
2288
2289 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002290 pointerIds.markBit(entry.pointerProperties[0].id);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002291 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2292 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293 }
2294 }
2295 }
2296
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002297 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002298 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002299 // Let the previous window know that the hover sequence is over, unless we already did
2300 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002301 if (mLastHoverWindowHandle != nullptr &&
2302 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2303 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002304 if (DEBUG_HOVER) {
2305 ALOGD("Sending hover exit event to window %s.",
2306 mLastHoverWindowHandle->getName().c_str());
2307 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002308 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2309 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310 }
2311
Garfield Tandf26e862020-07-01 20:18:19 -07002312 // Let the new window know that the hover sequence is starting, unless we already did it
2313 // when dispatching it as is to newTouchedWindowHandle.
2314 if (newHoverWindowHandle != nullptr &&
2315 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2316 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002317 if (DEBUG_HOVER) {
2318 ALOGD("Sending hover enter event to window %s.",
2319 newHoverWindowHandle->getName().c_str());
2320 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002321 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2322 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2323 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324 }
2325 }
2326
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002327 // Ensure that we have at least one foreground window or at least one window that cannot be a
2328 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2329 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2330 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002331 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2332 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002333 return !canReceiveForegroundTouches(
2334 *touchedWindow.windowHandle->getInfo()) ||
2335 (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002336 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002337 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2338 displayId, entry.getDescription().c_str());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002339 injectionResult = InputEventInjectionResult::FAILED;
2340 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341 }
2342
Prabir Pradhan5735a322022-04-11 17:23:34 +00002343 // Ensure that all touched windows are valid for injection.
2344 if (entry.injectionState != nullptr) {
2345 std::string errs;
2346 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
2347 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2348 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2349 // dispatched to any uid, since the coords will be zeroed out later.
2350 continue;
2351 }
2352 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2353 if (err) errs += "\n - " + *err;
2354 }
2355 if (!errs.empty()) {
2356 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2357 "%d:%s",
2358 *entry.injectionState->targetUid, errs.c_str());
2359 injectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2360 goto Failed;
2361 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002362 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002363
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364 // Check whether windows listening for outside touches are owned by the same UID. If it is
2365 // set the policy flag that we will not reveal coordinate information to this window.
2366 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002367 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002368 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002369 if (foregroundWindowHandle) {
2370 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002371 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002372 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002373 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2374 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2375 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002376 InputTarget::FLAG_ZERO_COORDS,
2377 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002379 }
2380 }
2381 }
2382 }
2383
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384 // If this is the first pointer going down and the touched window has a wallpaper
2385 // then also add the touched wallpaper windows so they are locked in for the duration
2386 // of the touch gesture.
2387 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2388 // engine only supports touch events. We would need to add a mechanism similar
2389 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2390 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002391 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002392 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002393 if (foregroundWindowHandle &&
2394 foregroundWindowHandle->getInfo()->inputConfig.test(
2395 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002396 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002397 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002398 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2399 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002400 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002401 windowHandle->getInfo()->inputConfig.test(
2402 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002403 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002404 .addOrUpdateWindow(windowHandle,
2405 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2406 InputTarget::
2407 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2408 InputTarget::FLAG_DISPATCH_AS_IS,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002409 BitSet32(0), entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410 }
2411 }
2412 }
2413 }
2414
2415 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002416 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002418 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002420 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2421 inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422 }
2423
2424 // Drop the outside or hover touch windows since we will not care about them
2425 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002426 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002427
2428Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002429 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002430 if (!wrongDevice) {
2431 if (switchedDevice) {
2432 if (DEBUG_FOCUS) {
2433 ALOGD("Conflicting pointer actions: Switched to a different device.");
2434 }
2435 *outConflictingPointerActions = true;
2436 }
2437
2438 if (isHoverAction) {
2439 // Started hovering, therefore no longer down.
2440 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002441 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002442 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2443 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002444 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002445 *outConflictingPointerActions = true;
2446 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002447 tempTouchState.reset();
2448 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2449 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2450 tempTouchState.deviceId = entry.deviceId;
2451 tempTouchState.source = entry.source;
2452 tempTouchState.displayId = displayId;
2453 }
2454 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2455 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2456 // All pointers up or canceled.
2457 tempTouchState.reset();
2458 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2459 // First pointer went down.
2460 if (oldState && oldState->down) {
2461 if (DEBUG_FOCUS) {
2462 ALOGD("Conflicting pointer actions: Down received while already down.");
2463 }
2464 *outConflictingPointerActions = true;
2465 }
2466 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2467 // One pointer went up.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002468 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2469 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002471 for (size_t i = 0; i < tempTouchState.windows.size();) {
2472 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2473 touchedWindow.pointerIds.clearBit(pointerId);
2474 if (touchedWindow.pointerIds.isEmpty()) {
2475 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2476 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002477 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002478 i += 1;
2479 }
2480 } else if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2481 // If no split, we suppose all touched windows should receive pointer down.
2482 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2483 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2484 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2485 // Ignore drag window for it should just track one pointer.
2486 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2487 continue;
2488 }
2489 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Jeff Brownf086ddb2014-02-11 14:28:48 -08002490 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002491 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002492
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002493 // Save changes unless the action was scroll in which case the temporary touch
2494 // state was only valid for this one action.
2495 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2496 if (tempTouchState.displayId >= 0) {
2497 mTouchStatesByDisplay[displayId] = tempTouchState;
2498 } else {
2499 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002502
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002503 // Update hover state.
2504 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505 }
2506
Michael Wrightd02c5b62014-02-10 15:10:22 -08002507 return injectionResult;
2508}
2509
arthurhung6d4bed92021-03-17 11:59:33 +08002510void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002511 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2512 // have an explicit reason to support it.
2513 constexpr bool isStylus = false;
2514
chaviw98318de2021-05-19 16:45:23 -05002515 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002516 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002517 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002518 if (dropWindow) {
2519 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002520 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002521 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002522 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002523 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002524 }
2525 mDragState.reset();
2526}
2527
2528void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002529 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002530 return;
2531 }
2532
arthurhung6d4bed92021-03-17 11:59:33 +08002533 if (!mDragState->isStartDrag) {
2534 mDragState->isStartDrag = true;
2535 mDragState->isStylusButtonDownAtStart =
2536 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2537 }
2538
Arthur Hung54745652022-04-20 07:17:41 +00002539 // Find the pointer index by id.
2540 int32_t pointerIndex = 0;
2541 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2542 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2543 if (pointerProperties.id == mDragState->pointerId) {
2544 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002545 }
Arthur Hung54745652022-04-20 07:17:41 +00002546 }
arthurhung6d4bed92021-03-17 11:59:33 +08002547
Arthur Hung54745652022-04-20 07:17:41 +00002548 if (uint32_t(pointerIndex) == entry.pointerCount) {
2549 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002550 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002551 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002552 return;
2553 }
2554
2555 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2556 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2557 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2558
2559 switch (maskedAction) {
2560 case AMOTION_EVENT_ACTION_MOVE: {
2561 // Handle the special case : stylus button no longer pressed.
2562 bool isStylusButtonDown =
2563 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2564 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2565 finishDragAndDrop(entry.displayId, x, y);
2566 return;
2567 }
2568
2569 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2570 // until we have an explicit reason to support it.
2571 constexpr bool isStylus = false;
2572
2573 const sp<WindowInfoHandle> hoverWindowHandle =
2574 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2575 isStylus, false /*addOutsideTargets*/,
2576 true /*ignoreDragWindow*/);
2577 // enqueue drag exit if needed.
2578 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2579 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2580 if (mDragState->dragHoverWindowHandle != nullptr) {
2581 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2582 y);
2583 }
2584 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2585 }
2586 // enqueue drag location if needed.
2587 if (hoverWindowHandle != nullptr) {
2588 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2589 }
2590 break;
2591 }
2592
2593 case AMOTION_EVENT_ACTION_POINTER_UP:
2594 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2595 break;
2596 }
2597 // The drag pointer is up.
2598 [[fallthrough]];
2599 case AMOTION_EVENT_ACTION_UP:
2600 finishDragAndDrop(entry.displayId, x, y);
2601 break;
2602 case AMOTION_EVENT_ACTION_CANCEL: {
2603 ALOGD("Receiving cancel when drag and drop.");
2604 sendDropWindowCommandLocked(nullptr, 0, 0);
2605 mDragState.reset();
2606 break;
2607 }
arthurhungb89ccb02020-12-30 16:19:01 +08002608 }
2609}
2610
chaviw98318de2021-05-19 16:45:23 -05002611void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002612 int32_t targetFlags, BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002613 std::optional<nsecs_t> firstDownTimeInTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002614 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002615 std::vector<InputTarget>::iterator it =
2616 std::find_if(inputTargets.begin(), inputTargets.end(),
2617 [&windowHandle](const InputTarget& inputTarget) {
2618 return inputTarget.inputChannel->getConnectionToken() ==
2619 windowHandle->getToken();
2620 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002621
chaviw98318de2021-05-19 16:45:23 -05002622 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002623
2624 if (it == inputTargets.end()) {
2625 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002626 std::shared_ptr<InputChannel> inputChannel =
2627 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002628 if (inputChannel == nullptr) {
2629 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2630 return;
2631 }
2632 inputTarget.inputChannel = inputChannel;
2633 inputTarget.flags = targetFlags;
2634 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002635 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002636 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2637 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002638 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002639 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002640 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002641 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002642 inputTargets.push_back(inputTarget);
2643 it = inputTargets.end() - 1;
2644 }
2645
2646 ALOG_ASSERT(it->flags == targetFlags);
2647 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2648
chaviw1ff3d1e2020-07-01 15:53:47 -07002649 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650}
2651
Michael Wright3dd60e22019-03-27 22:06:44 +00002652void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002653 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002654 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2655 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002656
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002657 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2658 InputTarget target;
2659 target.inputChannel = monitor.inputChannel;
2660 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002661 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2662 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002663 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2664 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002665 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002666 target.setDefaultPointerTransform(target.displayTransform);
2667 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668 }
2669}
2670
Robert Carrc9bf1d32020-04-13 17:21:08 -07002671/**
2672 * Indicate whether one window handle should be considered as obscuring
2673 * another window handle. We only check a few preconditions. Actually
2674 * checking the bounds is left to the caller.
2675 */
chaviw98318de2021-05-19 16:45:23 -05002676static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2677 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002678 // Compare by token so cloned layers aren't counted
2679 if (haveSameToken(windowHandle, otherHandle)) {
2680 return false;
2681 }
2682 auto info = windowHandle->getInfo();
2683 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002684 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002685 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002686 } else if (otherInfo->alpha == 0 &&
2687 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002688 // Those act as if they were invisible, so we don't need to flag them.
2689 // We do want to potentially flag touchable windows even if they have 0
2690 // opacity, since they can consume touches and alter the effects of the
2691 // user interaction (eg. apps that rely on
2692 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2693 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2694 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002695 } else if (info->ownerUid == otherInfo->ownerUid) {
2696 // If ownerUid is the same we don't generate occlusion events as there
2697 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002698 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002699 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002700 return false;
2701 } else if (otherInfo->displayId != info->displayId) {
2702 return false;
2703 }
2704 return true;
2705}
2706
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002707/**
2708 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2709 * untrusted, one should check:
2710 *
2711 * 1. If result.hasBlockingOcclusion is true.
2712 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2713 * BLOCK_UNTRUSTED.
2714 *
2715 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2716 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2717 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2718 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2719 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2720 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2721 *
2722 * If neither of those is true, then it means the touch can be allowed.
2723 */
2724InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002725 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2726 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002727 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002728 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002729 TouchOcclusionInfo info;
2730 info.hasBlockingOcclusion = false;
2731 info.obscuringOpacity = 0;
2732 info.obscuringUid = -1;
2733 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002734 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002735 if (windowHandle == otherHandle) {
2736 break; // All future windows are below us. Exit early.
2737 }
chaviw98318de2021-05-19 16:45:23 -05002738 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002739 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2740 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002741 if (DEBUG_TOUCH_OCCLUSION) {
2742 info.debugInfo.push_back(
2743 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2744 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002745 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2746 // we perform the checks below to see if the touch can be propagated or not based on the
2747 // window's touch occlusion mode
2748 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2749 info.hasBlockingOcclusion = true;
2750 info.obscuringUid = otherInfo->ownerUid;
2751 info.obscuringPackage = otherInfo->packageName;
2752 break;
2753 }
2754 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2755 uint32_t uid = otherInfo->ownerUid;
2756 float opacity =
2757 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2758 // Given windows A and B:
2759 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2760 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2761 opacityByUid[uid] = opacity;
2762 if (opacity > info.obscuringOpacity) {
2763 info.obscuringOpacity = opacity;
2764 info.obscuringUid = uid;
2765 info.obscuringPackage = otherInfo->packageName;
2766 }
2767 }
2768 }
2769 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002770 if (DEBUG_TOUCH_OCCLUSION) {
2771 info.debugInfo.push_back(
2772 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2773 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002774 return info;
2775}
2776
chaviw98318de2021-05-19 16:45:23 -05002777std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002778 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002779 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2780 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2781 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2782 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002783 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2784 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2785 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2786 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2787 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002788 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002789 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002790}
2791
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002792bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2793 if (occlusionInfo.hasBlockingOcclusion) {
2794 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2795 occlusionInfo.obscuringUid);
2796 return false;
2797 }
2798 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2799 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2800 "%.2f, maximum allowed = %.2f)",
2801 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2802 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2803 return false;
2804 }
2805 return true;
2806}
2807
chaviw98318de2021-05-19 16:45:23 -05002808bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002809 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002811 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2812 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002813 if (windowHandle == otherHandle) {
2814 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002815 }
chaviw98318de2021-05-19 16:45:23 -05002816 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002817 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002818 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002819 return true;
2820 }
2821 }
2822 return false;
2823}
2824
chaviw98318de2021-05-19 16:45:23 -05002825bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002826 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002827 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2828 const WindowInfo* windowInfo = windowHandle->getInfo();
2829 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002830 if (windowHandle == otherHandle) {
2831 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002832 }
chaviw98318de2021-05-19 16:45:23 -05002833 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002834 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002835 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002836 return true;
2837 }
2838 }
2839 return false;
2840}
2841
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002842std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002843 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002844 if (applicationHandle != nullptr) {
2845 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002846 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847 } else {
2848 return applicationHandle->getName();
2849 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002850 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002851 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002853 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002854 }
2855}
2856
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002857void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002858 if (!isUserActivityEvent(eventEntry)) {
2859 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002860 return;
2861 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002862 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002863 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002864 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002865 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002866 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002867 if (DEBUG_DISPATCH_CYCLE) {
2868 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002870 return;
2871 }
2872 }
2873
2874 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002875 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002876 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002877 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2878 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002879 return;
2880 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002881
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002882 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002883 eventType = USER_ACTIVITY_EVENT_TOUCH;
2884 }
2885 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002887 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002888 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2889 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002890 return;
2891 }
2892 eventType = USER_ACTIVITY_EVENT_BUTTON;
2893 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002894 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002895 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002896 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002897 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002898 break;
2899 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002900 }
2901
Prabir Pradhancef936d2021-07-21 16:17:52 +00002902 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2903 REQUIRES(mLock) {
2904 scoped_unlock unlock(mLock);
2905 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2906 };
2907 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002908}
2909
2910void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002911 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002912 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002913 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002914 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002915 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002916 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002917 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002918 ATRACE_NAME(message.c_str());
2919 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002920 if (DEBUG_DISPATCH_CYCLE) {
2921 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2922 "globalScaleFactor=%f, pointerIds=0x%x %s",
2923 connection->getInputChannelName().c_str(), inputTarget.flags,
2924 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2925 inputTarget.getPointerInfoString().c_str());
2926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927
2928 // Skip this event if the connection status is not normal.
2929 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002930 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002931 if (DEBUG_DISPATCH_CYCLE) {
2932 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002933 connection->getInputChannelName().c_str(),
2934 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002935 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002936 return;
2937 }
2938
2939 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002940 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2941 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2942 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002943 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002944
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002945 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002946 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002947 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
2948 "Splitting motion events requires a down time to be set for the "
2949 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002950 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002951 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
2952 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002953 if (!splitMotionEntry) {
2954 return; // split event was dropped
2955 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002956 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2957 std::string reason = std::string("reason=pointer cancel on split window");
2958 android_log_event_list(LOGTAG_INPUT_CANCEL)
2959 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2960 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002961 if (DEBUG_FOCUS) {
2962 ALOGD("channel '%s' ~ Split motion event.",
2963 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002964 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002965 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002966 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2967 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002968 return;
2969 }
2970 }
2971
2972 // Not splitting. Enqueue dispatch entries for the event as is.
2973 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2974}
2975
2976void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002977 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002978 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002979 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002980 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002981 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002982 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002983 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002984 ATRACE_NAME(message.c_str());
2985 }
2986
hongzuo liu95785e22022-09-06 02:51:35 +00002987 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002988
2989 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002990 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002991 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002992 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002993 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002994 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002995 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002996 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002997 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002998 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002999 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003000 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003001 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003002
3003 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003004 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003005 startDispatchCycleLocked(currentTime, connection);
3006 }
3007}
3008
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003009void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003010 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003011 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003012 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003013 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003014 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3015 connection->getInputChannelName().c_str(),
3016 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003017 ATRACE_NAME(message.c_str());
3018 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003019 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003020 if (!(inputTargetFlags & dispatchMode)) {
3021 return;
3022 }
3023 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
3024
3025 // This is a new event.
3026 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003027 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003028 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003030 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3031 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003032 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003034 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003035 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003036 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003037 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003038 dispatchEntry->resolvedAction = keyEntry.action;
3039 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003040
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003041 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3042 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003043 if (DEBUG_DISPATCH_CYCLE) {
3044 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3045 "event",
3046 connection->getInputChannelName().c_str());
3047 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003048 return; // skip the inconsistent event
3049 }
3050 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003051 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003053 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003054 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003055 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3056 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3057 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3058 static_cast<int32_t>(IdGenerator::Source::OTHER);
3059 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003060 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3061 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3062 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3063 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3064 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3065 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3066 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3067 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3068 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3069 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3070 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003071 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003072 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003073 }
3074 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003075 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3076 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003077 if (DEBUG_DISPATCH_CYCLE) {
3078 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3079 "enter event",
3080 connection->getInputChannelName().c_str());
3081 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003082 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3083 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003084 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3085 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003087 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003088 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3089 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3090 }
3091 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3092 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3093 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003095 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3096 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003097 if (DEBUG_DISPATCH_CYCLE) {
3098 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3099 "event",
3100 connection->getInputChannelName().c_str());
3101 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003102 return; // skip the inconsistent event
3103 }
3104
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003105 dispatchEntry->resolvedEventId =
3106 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3107 ? mIdGenerator.nextId()
3108 : motionEntry.id;
3109 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3110 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3111 ") to MotionEvent(id=0x%" PRIx32 ").",
3112 motionEntry.id, dispatchEntry->resolvedEventId);
3113 ATRACE_NAME(message.c_str());
3114 }
3115
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003116 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3117 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3118 // Skip reporting pointer down outside focus to the policy.
3119 break;
3120 }
3121
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003122 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003123 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003124
3125 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003126 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003127 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003128 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003129 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3130 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003131 break;
3132 }
Chris Yef59a2f42020-10-16 12:55:26 -07003133 case EventEntry::Type::SENSOR: {
3134 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3135 break;
3136 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003137 case EventEntry::Type::CONFIGURATION_CHANGED:
3138 case EventEntry::Type::DEVICE_RESET: {
3139 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003140 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003141 break;
3142 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003143 }
3144
3145 // Remember that we are waiting for this dispatch to complete.
3146 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003147 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148 }
3149
3150 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003151 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003152 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003153}
3154
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003155/**
3156 * This function is purely for debugging. It helps us understand where the user interaction
3157 * was taking place. For example, if user is touching launcher, we will see a log that user
3158 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3159 * We will see both launcher and wallpaper in that list.
3160 * Once the interaction with a particular set of connections starts, no new logs will be printed
3161 * until the set of interacted connections changes.
3162 *
3163 * The following items are skipped, to reduce the logspam:
3164 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3165 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3166 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3167 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3168 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003169 */
3170void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3171 const std::vector<InputTarget>& targets) {
3172 // Skip ACTION_UP events, and all events other than keys and motions
3173 if (entry.type == EventEntry::Type::KEY) {
3174 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3175 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3176 return;
3177 }
3178 } else if (entry.type == EventEntry::Type::MOTION) {
3179 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3180 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3181 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3182 return;
3183 }
3184 } else {
3185 return; // Not a key or a motion
3186 }
3187
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003188 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003189 std::vector<sp<Connection>> newConnections;
3190 for (const InputTarget& target : targets) {
3191 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3192 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3193 continue; // Skip windows that receive ACTION_OUTSIDE
3194 }
3195
3196 sp<IBinder> token = target.inputChannel->getConnectionToken();
3197 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003198 if (connection == nullptr) {
3199 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003200 }
3201 newConnectionTokens.insert(std::move(token));
3202 newConnections.emplace_back(connection);
3203 }
3204 if (newConnectionTokens == mInteractionConnectionTokens) {
3205 return; // no change
3206 }
3207 mInteractionConnectionTokens = newConnectionTokens;
3208
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003209 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003210 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003211 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003212 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003213 std::string message = "Interaction with: " + targetList;
3214 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003215 message += "<none>";
3216 }
3217 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3218}
3219
chaviwfd6d3512019-03-25 13:23:49 -07003220void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003221 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003222 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003223 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3224 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003225 return;
3226 }
3227
Vishnu Nairc519ff72021-01-21 08:23:08 -08003228 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003229 if (focusedToken == token) {
3230 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003231 return;
3232 }
3233
Prabir Pradhancef936d2021-07-21 16:17:52 +00003234 auto command = [this, token]() REQUIRES(mLock) {
3235 scoped_unlock unlock(mLock);
3236 mPolicy->onPointerDownOutsideFocus(token);
3237 };
3238 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239}
3240
3241void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003242 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003243 if (ATRACE_ENABLED()) {
3244 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003245 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003246 ATRACE_NAME(message.c_str());
3247 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003248 if (DEBUG_DISPATCH_CYCLE) {
3249 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3250 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003252 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003253 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003254 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003255 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003256 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257
3258 // Publish the event.
3259 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003260 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3261 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003262 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003263 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3264 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003266 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003267 status = connection->inputPublisher
3268 .publishKeyEvent(dispatchEntry->seq,
3269 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3270 keyEntry.source, keyEntry.displayId,
3271 std::move(hmac), dispatchEntry->resolvedAction,
3272 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3273 keyEntry.scanCode, keyEntry.metaState,
3274 keyEntry.repeatCount, keyEntry.downTime,
3275 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003276 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003277 }
3278
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003279 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003280 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003282 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003283 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003284
chaviw82357092020-01-28 13:13:06 -08003285 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003286 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003287 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3288 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003289 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003290 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3291 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003292 // Don't apply window scale here since we don't want scale to affect raw
3293 // coordinates. The scale will be sent back to the client and applied
3294 // later when requesting relative coordinates.
3295 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3296 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003297 }
3298 usingCoords = scaledCoords;
3299 }
3300 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003301 // We don't want the dispatch target to know.
3302 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003303 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003304 scaledCoords[i].clear();
3305 }
3306 usingCoords = scaledCoords;
3307 }
3308 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003309
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003310 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003311
3312 // Publish the motion event.
3313 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003314 .publishMotionEvent(dispatchEntry->seq,
3315 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003316 motionEntry.deviceId, motionEntry.source,
3317 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003318 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003319 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003320 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003321 motionEntry.edgeFlags, motionEntry.metaState,
3322 motionEntry.buttonState,
3323 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003324 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003325 motionEntry.xPrecision, motionEntry.yPrecision,
3326 motionEntry.xCursorPosition,
3327 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003328 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003329 motionEntry.downTime, motionEntry.eventTime,
3330 motionEntry.pointerCount,
3331 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003332 break;
3333 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003334
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003335 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003336 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003337 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003338 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003339 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003340 break;
3341 }
3342
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003343 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3344 const TouchModeEntry& touchModeEntry =
3345 static_cast<const TouchModeEntry&>(eventEntry);
3346 status = connection->inputPublisher
3347 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3348 touchModeEntry.inTouchMode);
3349
3350 break;
3351 }
3352
Prabir Pradhan99987712020-11-10 18:43:05 -08003353 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3354 const auto& captureEntry =
3355 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3356 status = connection->inputPublisher
3357 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003358 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003359 break;
3360 }
3361
arthurhungb89ccb02020-12-30 16:19:01 +08003362 case EventEntry::Type::DRAG: {
3363 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3364 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3365 dragEntry.id, dragEntry.x,
3366 dragEntry.y,
3367 dragEntry.isExiting);
3368 break;
3369 }
3370
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003371 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003372 case EventEntry::Type::DEVICE_RESET:
3373 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003374 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003375 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003376 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003377 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003378 }
3379
3380 // Check the result.
3381 if (status) {
3382 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003383 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003385 "This is unexpected because the wait queue is empty, so the pipe "
3386 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003387 "event to it, status=%s(%d)",
3388 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3389 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3391 } else {
3392 // Pipe is full and we are waiting for the app to finish process some events
3393 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003394 if (DEBUG_DISPATCH_CYCLE) {
3395 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3396 "waiting for the application to catch up",
3397 connection->getInputChannelName().c_str());
3398 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399 }
3400 } else {
3401 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003402 "status=%s(%d)",
3403 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3404 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3406 }
3407 return;
3408 }
3409
3410 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003411 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3412 connection->outboundQueue.end(),
3413 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003414 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003415 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003416 if (connection->responsive) {
3417 mAnrTracker.insert(dispatchEntry->timeoutTime,
3418 connection->inputChannel->getConnectionToken());
3419 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003420 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421 }
3422}
3423
chaviw09c8d2d2020-08-24 15:48:26 -07003424std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3425 size_t size;
3426 switch (event.type) {
3427 case VerifiedInputEvent::Type::KEY: {
3428 size = sizeof(VerifiedKeyEvent);
3429 break;
3430 }
3431 case VerifiedInputEvent::Type::MOTION: {
3432 size = sizeof(VerifiedMotionEvent);
3433 break;
3434 }
3435 }
3436 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3437 return mHmacKeyManager.sign(start, size);
3438}
3439
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003440const std::array<uint8_t, 32> InputDispatcher::getSignature(
3441 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003442 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3443 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003444 // Only sign events up and down events as the purely move events
3445 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003446 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003447 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003448
3449 VerifiedMotionEvent verifiedEvent =
3450 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3451 verifiedEvent.actionMasked = actionMasked;
3452 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3453 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003454}
3455
3456const std::array<uint8_t, 32> InputDispatcher::getSignature(
3457 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3458 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3459 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3460 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003461 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003462}
3463
Michael Wrightd02c5b62014-02-10 15:10:22 -08003464void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003465 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003466 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003467 if (DEBUG_DISPATCH_CYCLE) {
3468 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3469 connection->getInputChannelName().c_str(), seq, toString(handled));
3470 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003472 if (connection->status == Connection::Status::BROKEN ||
3473 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474 return;
3475 }
3476
3477 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003478 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3479 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3480 };
3481 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482}
3483
3484void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003485 const sp<Connection>& connection,
3486 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003487 if (DEBUG_DISPATCH_CYCLE) {
3488 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3489 connection->getInputChannelName().c_str(), toString(notify));
3490 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003491
3492 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003493 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003494 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003495 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003496 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003497
3498 // The connection appears to be unrecoverably broken.
3499 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003500 if (connection->status == Connection::Status::NORMAL) {
3501 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502
3503 if (notify) {
3504 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003505 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3506 connection->getInputChannelName().c_str());
3507
3508 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003509 scoped_unlock unlock(mLock);
3510 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3511 };
3512 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513 }
3514 }
3515}
3516
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003517void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3518 while (!queue.empty()) {
3519 DispatchEntry* dispatchEntry = queue.front();
3520 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003521 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522 }
3523}
3524
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003525void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003527 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528 }
3529 delete dispatchEntry;
3530}
3531
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003532int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3533 std::scoped_lock _l(mLock);
3534 sp<Connection> connection = getConnectionLocked(connectionToken);
3535 if (connection == nullptr) {
3536 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3537 connectionToken.get(), events);
3538 return 0; // remove the callback
3539 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003541 bool notify;
3542 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3543 if (!(events & ALOOPER_EVENT_INPUT)) {
3544 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3545 "events=0x%x",
3546 connection->getInputChannelName().c_str(), events);
3547 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548 }
3549
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003550 nsecs_t currentTime = now();
3551 bool gotOne = false;
3552 status_t status = OK;
3553 for (;;) {
3554 Result<InputPublisher::ConsumerResponse> result =
3555 connection->inputPublisher.receiveConsumerResponse();
3556 if (!result.ok()) {
3557 status = result.error().code();
3558 break;
3559 }
3560
3561 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3562 const InputPublisher::Finished& finish =
3563 std::get<InputPublisher::Finished>(*result);
3564 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3565 finish.consumeTime);
3566 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003567 if (shouldReportMetricsForConnection(*connection)) {
3568 const InputPublisher::Timeline& timeline =
3569 std::get<InputPublisher::Timeline>(*result);
3570 mLatencyTracker
3571 .trackGraphicsLatency(timeline.inputEventId,
3572 connection->inputChannel->getConnectionToken(),
3573 std::move(timeline.graphicsTimeline));
3574 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003575 }
3576 gotOne = true;
3577 }
3578 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003579 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003580 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003581 return 1;
3582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003583 }
3584
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003585 notify = status != DEAD_OBJECT || !connection->monitor;
3586 if (notify) {
3587 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3588 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3589 status);
3590 }
3591 } else {
3592 // Monitor channels are never explicitly unregistered.
3593 // We do it automatically when the remote endpoint is closed so don't warn about them.
3594 const bool stillHaveWindowHandle =
3595 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3596 notify = !connection->monitor && stillHaveWindowHandle;
3597 if (notify) {
3598 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3599 connection->getInputChannelName().c_str(), events);
3600 }
3601 }
3602
3603 // Remove the channel.
3604 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3605 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606}
3607
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003608void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003610 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003611 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612 }
3613}
3614
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003615void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003616 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003617 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003618 for (const Monitor& monitor : monitors) {
3619 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003620 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003621 }
3622}
3623
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003625 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003626 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003627 if (connection == nullptr) {
3628 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003630
3631 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632}
3633
3634void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3635 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003636 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637 return;
3638 }
3639
3640 nsecs_t currentTime = now();
3641
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003642 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003643 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003645 if (cancelationEvents.empty()) {
3646 return;
3647 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003648 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3649 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3650 "with reality: %s, mode=%d.",
3651 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3652 options.mode);
3653 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003654
Arthur Hungb3307ee2021-10-14 10:57:37 +00003655 std::string reason = std::string("reason=").append(options.reason);
3656 android_log_event_list(LOGTAG_INPUT_CANCEL)
3657 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3658
Svet Ganov5d3bc372020-01-26 23:11:07 -08003659 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003660 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003661 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3662 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003663 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003664 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003665 target.globalScaleFactor = windowInfo->globalScaleFactor;
3666 }
3667 target.inputChannel = connection->inputChannel;
3668 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3669
hongzuo liu95785e22022-09-06 02:51:35 +00003670 const bool wasEmpty = connection->outboundQueue.empty();
3671
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003672 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003673 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003674 switch (cancelationEventEntry->type) {
3675 case EventEntry::Type::KEY: {
3676 logOutboundKeyDetails("cancel - ",
3677 static_cast<const KeyEntry&>(*cancelationEventEntry));
3678 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003679 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003680 case EventEntry::Type::MOTION: {
3681 logOutboundMotionDetails("cancel - ",
3682 static_cast<const MotionEntry&>(*cancelationEventEntry));
3683 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003685 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003686 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003687 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3688 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003689 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003690 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003691 break;
3692 }
3693 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003694 case EventEntry::Type::DEVICE_RESET:
3695 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003696 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003697 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003698 break;
3699 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 }
3701
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003702 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3703 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003705
hongzuo liu95785e22022-09-06 02:51:35 +00003706 // If the outbound queue was previously empty, start the dispatch cycle going.
3707 if (wasEmpty && !connection->outboundQueue.empty()) {
3708 startDispatchCycleLocked(currentTime, connection);
3709 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710}
3711
Svet Ganov5d3bc372020-01-26 23:11:07 -08003712void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003713 const nsecs_t downTime, const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003714 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003715 return;
3716 }
3717
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003718 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003719 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003720
3721 if (downEvents.empty()) {
3722 return;
3723 }
3724
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003725 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003726 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3727 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003728 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003729
3730 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003731 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003732 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3733 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003734 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003735 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003736 target.globalScaleFactor = windowInfo->globalScaleFactor;
3737 }
3738 target.inputChannel = connection->inputChannel;
3739 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3740
hongzuo liu95785e22022-09-06 02:51:35 +00003741 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003742 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003743 switch (downEventEntry->type) {
3744 case EventEntry::Type::MOTION: {
3745 logOutboundMotionDetails("down - ",
3746 static_cast<const MotionEntry&>(*downEventEntry));
3747 break;
3748 }
3749
3750 case EventEntry::Type::KEY:
3751 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003752 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003753 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003754 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003755 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003756 case EventEntry::Type::SENSOR:
3757 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003758 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003759 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003760 break;
3761 }
3762 }
3763
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003764 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3765 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003766 }
3767
hongzuo liu95785e22022-09-06 02:51:35 +00003768 // If the outbound queue was previously empty, start the dispatch cycle going.
3769 if (wasEmpty && !connection->outboundQueue.empty()) {
3770 startDispatchCycleLocked(downTime, connection);
3771 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003772}
3773
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003774std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003775 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003776 ALOG_ASSERT(pointerIds.value != 0);
3777
3778 uint32_t splitPointerIndexMap[MAX_POINTERS];
3779 PointerProperties splitPointerProperties[MAX_POINTERS];
3780 PointerCoords splitPointerCoords[MAX_POINTERS];
3781
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003782 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783 uint32_t splitPointerCount = 0;
3784
3785 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003786 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003788 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789 uint32_t pointerId = uint32_t(pointerProperties.id);
3790 if (pointerIds.hasBit(pointerId)) {
3791 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3792 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3793 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003794 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795 splitPointerCount += 1;
3796 }
3797 }
3798
3799 if (splitPointerCount != pointerIds.count()) {
3800 // This is bad. We are missing some of the pointers that we expected to deliver.
3801 // Most likely this indicates that we received an ACTION_MOVE events that has
3802 // different pointer ids than we expected based on the previous ACTION_DOWN
3803 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3804 // in this way.
3805 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003806 "we expected there to be %d pointers. This probably means we received "
3807 "a broken sequence of pointer ids from the input device.",
3808 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003809 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810 }
3811
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003812 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003814 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3815 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003816 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3817 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003818 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819 uint32_t pointerId = uint32_t(pointerProperties.id);
3820 if (pointerIds.hasBit(pointerId)) {
3821 if (pointerIds.count() == 1) {
3822 // The first/last pointer went down/up.
3823 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003824 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003825 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3826 ? AMOTION_EVENT_ACTION_CANCEL
3827 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828 } else {
3829 // A secondary pointer went down/up.
3830 uint32_t splitPointerIndex = 0;
3831 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3832 splitPointerIndex += 1;
3833 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003834 action = maskedAction |
3835 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003836 }
3837 } else {
3838 // An unrelated pointer changed.
3839 action = AMOTION_EVENT_ACTION_MOVE;
3840 }
3841 }
3842
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003843 if (action == AMOTION_EVENT_ACTION_DOWN) {
3844 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3845 "Split motion event has mismatching downTime and eventTime for "
3846 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3847 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3848 }
3849
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003850 int32_t newId = mIdGenerator.nextId();
3851 if (ATRACE_ENABLED()) {
3852 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3853 ") to MotionEvent(id=0x%" PRIx32 ").",
3854 originalMotionEntry.id, newId);
3855 ATRACE_NAME(message.c_str());
3856 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003857 std::unique_ptr<MotionEntry> splitMotionEntry =
3858 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3859 originalMotionEntry.deviceId, originalMotionEntry.source,
3860 originalMotionEntry.displayId,
3861 originalMotionEntry.policyFlags, action,
3862 originalMotionEntry.actionButton,
3863 originalMotionEntry.flags, originalMotionEntry.metaState,
3864 originalMotionEntry.buttonState,
3865 originalMotionEntry.classification,
3866 originalMotionEntry.edgeFlags,
3867 originalMotionEntry.xPrecision,
3868 originalMotionEntry.yPrecision,
3869 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003870 originalMotionEntry.yCursorPosition, splitDownTime,
3871 splitPointerCount, splitPointerProperties,
3872 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003874 if (originalMotionEntry.injectionState) {
3875 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876 splitMotionEntry->injectionState->refCount += 1;
3877 }
3878
3879 return splitMotionEntry;
3880}
3881
3882void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003883 if (DEBUG_INBOUND_EVENT_DETAILS) {
3884 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3885 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003886
Antonio Kantekf16f2832021-09-28 04:39:20 +00003887 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003888 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003889 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003890
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003891 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3892 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3893 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894 } // release lock
3895
3896 if (needWake) {
3897 mLooper->wake();
3898 }
3899}
3900
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003901/**
3902 * If one of the meta shortcuts is detected, process them here:
3903 * Meta + Backspace -> generate BACK
3904 * Meta + Enter -> generate HOME
3905 * This will potentially overwrite keyCode and metaState.
3906 */
3907void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003908 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003909 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3910 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3911 if (keyCode == AKEYCODE_DEL) {
3912 newKeyCode = AKEYCODE_BACK;
3913 } else if (keyCode == AKEYCODE_ENTER) {
3914 newKeyCode = AKEYCODE_HOME;
3915 }
3916 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003917 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003918 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003919 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003920 keyCode = newKeyCode;
3921 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3922 }
3923 } else if (action == AKEY_EVENT_ACTION_UP) {
3924 // In order to maintain a consistent stream of up and down events, check to see if the key
3925 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3926 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003927 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003928 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003929 auto replacementIt = mReplacedKeys.find(replacement);
3930 if (replacementIt != mReplacedKeys.end()) {
3931 keyCode = replacementIt->second;
3932 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003933 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3934 }
3935 }
3936}
3937
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003939 if (DEBUG_INBOUND_EVENT_DETAILS) {
3940 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3941 "policyFlags=0x%x, action=0x%x, "
3942 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3943 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3944 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3945 args->downTime);
3946 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947 if (!validateKeyEvent(args->action)) {
3948 return;
3949 }
3950
3951 uint32_t policyFlags = args->policyFlags;
3952 int32_t flags = args->flags;
3953 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003954 // InputDispatcher tracks and generates key repeats on behalf of
3955 // whatever notifies it, so repeatCount should always be set to 0
3956 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3958 policyFlags |= POLICY_FLAG_VIRTUAL;
3959 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3960 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961 if (policyFlags & POLICY_FLAG_FUNCTION) {
3962 metaState |= AMETA_FUNCTION_ON;
3963 }
3964
3965 policyFlags |= POLICY_FLAG_TRUSTED;
3966
Michael Wright78f24442014-08-06 15:55:28 -07003967 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003968 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003969
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003971 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003972 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3973 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974
Michael Wright2b3c3302018-03-02 17:19:13 +00003975 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003977 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3978 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003979 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003980 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981
Antonio Kantekf16f2832021-09-28 04:39:20 +00003982 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983 { // acquire lock
3984 mLock.lock();
3985
3986 if (shouldSendKeyToInputFilterLocked(args)) {
3987 mLock.unlock();
3988
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003989 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3991 return; // event was consumed by the filter
3992 }
3993
3994 mLock.lock();
3995 }
3996
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003997 std::unique_ptr<KeyEntry> newEntry =
3998 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3999 args->displayId, policyFlags, args->action, flags,
4000 keyCode, args->scanCode, metaState, repeatCount,
4001 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004003 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004 mLock.unlock();
4005 } // release lock
4006
4007 if (needWake) {
4008 mLooper->wake();
4009 }
4010}
4011
4012bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4013 return mInputFilterEnabled;
4014}
4015
4016void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004017 if (DEBUG_INBOUND_EVENT_DETAILS) {
4018 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4019 "displayId=%" PRId32 ", policyFlags=0x%x, "
4020 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
4021 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4022 "yCursorPosition=%f, downTime=%" PRId64,
4023 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
4024 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
4025 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
4026 args->xCursorPosition, args->yCursorPosition, args->downTime);
4027 for (uint32_t i = 0; i < args->pointerCount; i++) {
4028 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4029 "x=%f, y=%f, pressure=%f, size=%f, "
4030 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4031 "orientation=%f",
4032 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4033 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4034 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4035 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4036 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4037 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4038 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4039 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4040 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4041 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004043 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004044 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4045 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046 return;
4047 }
4048
4049 uint32_t policyFlags = args->policyFlags;
4050 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004051
4052 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004053 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004054 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4055 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004056 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058
Antonio Kantekf16f2832021-09-28 04:39:20 +00004059 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060 { // acquire lock
4061 mLock.lock();
4062
4063 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004064 ui::Transform displayTransform;
4065 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4066 displayTransform = it->second.transform;
4067 }
4068
Michael Wrightd02c5b62014-02-10 15:10:22 -08004069 mLock.unlock();
4070
4071 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004072 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4073 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004074 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004075 displayTransform, args->xPrecision, args->yPrecision,
4076 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004077 args->downTime, args->eventTime, args->pointerCount,
4078 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079
4080 policyFlags |= POLICY_FLAG_FILTERED;
4081 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4082 return; // event was consumed by the filter
4083 }
4084
4085 mLock.lock();
4086 }
4087
4088 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004089 std::unique_ptr<MotionEntry> newEntry =
4090 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4091 args->source, args->displayId, policyFlags,
4092 args->action, args->actionButton, args->flags,
4093 args->metaState, args->buttonState,
4094 args->classification, args->edgeFlags,
4095 args->xPrecision, args->yPrecision,
4096 args->xCursorPosition, args->yCursorPosition,
4097 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004098 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004099
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004100 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4101 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4102 !mInputFilterEnabled) {
4103 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4104 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4105 }
4106
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004107 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004108 mLock.unlock();
4109 } // release lock
4110
4111 if (needWake) {
4112 mLooper->wake();
4113 }
4114}
4115
Chris Yef59a2f42020-10-16 12:55:26 -07004116void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004117 if (DEBUG_INBOUND_EVENT_DETAILS) {
4118 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4119 " sensorType=%s",
4120 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004121 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004122 }
Chris Yef59a2f42020-10-16 12:55:26 -07004123
Antonio Kantekf16f2832021-09-28 04:39:20 +00004124 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004125 { // acquire lock
4126 mLock.lock();
4127
4128 // Just enqueue a new sensor event.
4129 std::unique_ptr<SensorEntry> newEntry =
4130 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4131 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4132 args->sensorType, args->accuracy,
4133 args->accuracyChanged, args->values);
4134
4135 needWake = enqueueInboundEventLocked(std::move(newEntry));
4136 mLock.unlock();
4137 } // release lock
4138
4139 if (needWake) {
4140 mLooper->wake();
4141 }
4142}
4143
Chris Yefb552902021-02-03 17:18:37 -08004144void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004145 if (DEBUG_INBOUND_EVENT_DETAILS) {
4146 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4147 args->deviceId, args->isOn);
4148 }
Chris Yefb552902021-02-03 17:18:37 -08004149 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4150}
4151
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004153 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154}
4155
4156void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004157 if (DEBUG_INBOUND_EVENT_DETAILS) {
4158 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4159 "switchMask=0x%08x",
4160 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4161 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162
4163 uint32_t policyFlags = args->policyFlags;
4164 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004165 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166}
4167
4168void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004169 if (DEBUG_INBOUND_EVENT_DETAILS) {
4170 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4171 args->deviceId);
4172 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173
Antonio Kantekf16f2832021-09-28 04:39:20 +00004174 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004176 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004177
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004178 std::unique_ptr<DeviceResetEntry> newEntry =
4179 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4180 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181 } // release lock
4182
4183 if (needWake) {
4184 mLooper->wake();
4185 }
4186}
4187
Prabir Pradhan7e186182020-11-10 13:56:45 -08004188void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004189 if (DEBUG_INBOUND_EVENT_DETAILS) {
4190 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004191 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004192 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004193
Antonio Kantekf16f2832021-09-28 04:39:20 +00004194 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004195 { // acquire lock
4196 std::scoped_lock _l(mLock);
4197 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004198 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004199 needWake = enqueueInboundEventLocked(std::move(entry));
4200 } // release lock
4201
4202 if (needWake) {
4203 mLooper->wake();
4204 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004205}
4206
Prabir Pradhan5735a322022-04-11 17:23:34 +00004207InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4208 std::optional<int32_t> targetUid,
4209 InputEventInjectionSync syncMode,
4210 std::chrono::milliseconds timeout,
4211 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004212 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004213 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4214 "policyFlags=0x%08x",
4215 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4216 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004217 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004218 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219
Prabir Pradhan5735a322022-04-11 17:23:34 +00004220 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004222 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004223 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4224 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4225 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4226 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4227 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004228 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004229 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004230 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004231 }
4232
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004233 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004235 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004236 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4237 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004238 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004239 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004240 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004242 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004243 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4244 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4245 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004246 int32_t keyCode = incomingKey.getKeyCode();
4247 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004248 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004249 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004250 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004251 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004252 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4253 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4254 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004256 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4257 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004258 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004259
4260 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4261 android::base::Timer t;
4262 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4263 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4264 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4265 std::to_string(t.duration().count()).c_str());
4266 }
4267 }
4268
4269 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004270 std::unique_ptr<KeyEntry> injectedEntry =
4271 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004272 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004273 incomingKey.getDisplayId(), policyFlags, action,
4274 flags, keyCode, incomingKey.getScanCode(), metaState,
4275 incomingKey.getRepeatCount(),
4276 incomingKey.getDownTime());
4277 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004278 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279 }
4280
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004281 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004282 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004283 const int32_t action = motionEvent.getAction();
4284 const bool isPointerEvent =
4285 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4286 // If a pointer event has no displayId specified, inject it to the default display.
4287 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4288 ? ADISPLAY_ID_DEFAULT
4289 : event->getDisplayId();
4290 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004291 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004292 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004293 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004294 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004295 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004296 }
4297
4298 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004299 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004300 android::base::Timer t;
4301 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4302 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4303 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4304 std::to_string(t.duration().count()).c_str());
4305 }
4306 }
4307
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004308 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4309 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4310 }
4311
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004312 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004313 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4314 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004315 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004316 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4317 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004318 displayId, policyFlags, action, actionButton,
4319 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004320 motionEvent.getButtonState(),
4321 motionEvent.getClassification(),
4322 motionEvent.getEdgeFlags(),
4323 motionEvent.getXPrecision(),
4324 motionEvent.getYPrecision(),
4325 motionEvent.getRawXCursorPosition(),
4326 motionEvent.getRawYCursorPosition(),
4327 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004328 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004329 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004330 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004331 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004332 sampleEventTimes += 1;
4333 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004334 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004335 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4336 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004337 displayId, policyFlags, action, actionButton,
4338 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004339 motionEvent.getButtonState(),
4340 motionEvent.getClassification(),
4341 motionEvent.getEdgeFlags(),
4342 motionEvent.getXPrecision(),
4343 motionEvent.getYPrecision(),
4344 motionEvent.getRawXCursorPosition(),
4345 motionEvent.getRawYCursorPosition(),
4346 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004347 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004348 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004349 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4350 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004351 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004352 }
4353 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004356 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004357 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004358 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359 }
4360
Prabir Pradhan5735a322022-04-11 17:23:34 +00004361 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004362 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004363 injectionState->injectionIsAsync = true;
4364 }
4365
4366 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004367 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368
4369 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004370 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004371 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004372 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 }
4374
4375 mLock.unlock();
4376
4377 if (needWake) {
4378 mLooper->wake();
4379 }
4380
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004381 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004383 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004385 if (syncMode == InputEventInjectionSync::NONE) {
4386 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387 } else {
4388 for (;;) {
4389 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004390 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391 break;
4392 }
4393
4394 nsecs_t remainingTimeout = endTime - now();
4395 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004396 if (DEBUG_INJECTION) {
4397 ALOGD("injectInputEvent - Timed out waiting for injection result "
4398 "to become available.");
4399 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004400 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401 break;
4402 }
4403
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004404 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405 }
4406
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004407 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4408 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004409 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004410 if (DEBUG_INJECTION) {
4411 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4412 injectionState->pendingForegroundDispatches);
4413 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414 nsecs_t remainingTimeout = endTime - now();
4415 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004416 if (DEBUG_INJECTION) {
4417 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4418 "dispatches to finish.");
4419 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004420 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421 break;
4422 }
4423
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004424 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004425 }
4426 }
4427 }
4428
4429 injectionState->release();
4430 } // release lock
4431
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004432 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004433 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004435
4436 return injectionResult;
4437}
4438
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004439std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004440 std::array<uint8_t, 32> calculatedHmac;
4441 std::unique_ptr<VerifiedInputEvent> result;
4442 switch (event.getType()) {
4443 case AINPUT_EVENT_TYPE_KEY: {
4444 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4445 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4446 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004447 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004448 break;
4449 }
4450 case AINPUT_EVENT_TYPE_MOTION: {
4451 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4452 VerifiedMotionEvent verifiedMotionEvent =
4453 verifiedMotionEventFromMotionEvent(motionEvent);
4454 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004455 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004456 break;
4457 }
4458 default: {
4459 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4460 return nullptr;
4461 }
4462 }
4463 if (calculatedHmac == INVALID_HMAC) {
4464 return nullptr;
4465 }
4466 if (calculatedHmac != event.getHmac()) {
4467 return nullptr;
4468 }
4469 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004470}
4471
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004472void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004473 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004474 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004475 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004476 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004477 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004478 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004480 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004481 // Log the outcome since the injector did not wait for the injection result.
4482 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004483 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004484 ALOGV("Asynchronous input event injection succeeded.");
4485 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004486 case InputEventInjectionResult::TARGET_MISMATCH:
4487 ALOGV("Asynchronous input event injection target mismatch.");
4488 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004489 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004490 ALOGW("Asynchronous input event injection failed.");
4491 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004492 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004493 ALOGW("Asynchronous input event injection timed out.");
4494 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004495 case InputEventInjectionResult::PENDING:
4496 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4497 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004498 }
4499 }
4500
4501 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004502 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004503 }
4504}
4505
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004506void InputDispatcher::transformMotionEntryForInjectionLocked(
4507 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004508 // Input injection works in the logical display coordinate space, but the input pipeline works
4509 // display space, so we need to transform the injected events accordingly.
4510 const auto it = mDisplayInfos.find(entry.displayId);
4511 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004512 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004513
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004514 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4515 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4516 const vec2 cursor =
4517 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4518 {entry.xCursorPosition, entry.yCursorPosition});
4519 entry.xCursorPosition = cursor.x;
4520 entry.yCursorPosition = cursor.y;
4521 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004522 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004523 entry.pointerCoords[i] =
4524 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4525 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004526 }
4527}
4528
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004529void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4530 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004531 if (injectionState) {
4532 injectionState->pendingForegroundDispatches += 1;
4533 }
4534}
4535
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004536void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4537 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004538 if (injectionState) {
4539 injectionState->pendingForegroundDispatches -= 1;
4540
4541 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004542 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543 }
4544 }
4545}
4546
chaviw98318de2021-05-19 16:45:23 -05004547const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004548 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004549 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004550 auto it = mWindowHandlesByDisplay.find(displayId);
4551 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004552}
4553
chaviw98318de2021-05-19 16:45:23 -05004554sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004555 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004556 if (windowHandleToken == nullptr) {
4557 return nullptr;
4558 }
4559
Arthur Hungb92218b2018-08-14 12:00:21 +08004560 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004561 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4562 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004563 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004564 return windowHandle;
4565 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004566 }
4567 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004568 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004569}
4570
chaviw98318de2021-05-19 16:45:23 -05004571sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4572 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004573 if (windowHandleToken == nullptr) {
4574 return nullptr;
4575 }
4576
chaviw98318de2021-05-19 16:45:23 -05004577 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004578 if (windowHandle->getToken() == windowHandleToken) {
4579 return windowHandle;
4580 }
4581 }
4582 return nullptr;
4583}
4584
chaviw98318de2021-05-19 16:45:23 -05004585sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4586 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004587 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004588 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4589 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004590 if (handle->getId() == windowHandle->getId() &&
4591 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004592 if (windowHandle->getInfo()->displayId != it.first) {
4593 ALOGE("Found window %s in display %" PRId32
4594 ", but it should belong to display %" PRId32,
4595 windowHandle->getName().c_str(), it.first,
4596 windowHandle->getInfo()->displayId);
4597 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004598 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004600 }
4601 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004602 return nullptr;
4603}
4604
chaviw98318de2021-05-19 16:45:23 -05004605sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004606 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4607 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608}
4609
chaviw98318de2021-05-19 16:45:23 -05004610bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004611 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4612 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004613 windowHandle.getInfo()->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004614 if (connection != nullptr && noInputChannel) {
4615 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4616 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4617 return false;
4618 }
4619
4620 if (connection == nullptr) {
4621 if (!noInputChannel) {
4622 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4623 }
4624 return false;
4625 }
4626 if (!connection->responsive) {
4627 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4628 return false;
4629 }
4630 return true;
4631}
4632
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004633std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4634 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004635 auto connectionIt = mConnectionsByToken.find(token);
4636 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004637 return nullptr;
4638 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004639 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004640}
4641
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004642void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004643 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4644 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004645 // Remove all handles on a display if there are no windows left.
4646 mWindowHandlesByDisplay.erase(displayId);
4647 return;
4648 }
4649
4650 // Since we compare the pointer of input window handles across window updates, we need
4651 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004652 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4653 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4654 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004655 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004656 }
4657
chaviw98318de2021-05-19 16:45:23 -05004658 std::vector<sp<WindowInfoHandle>> newHandles;
4659 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004660 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004661 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004662 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004663 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004664 const bool canReceiveInput =
4665 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4666 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004667 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004668 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004669 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004670 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004671 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004672 }
4673
4674 if (info->displayId != displayId) {
4675 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4676 handle->getName().c_str(), displayId, info->displayId);
4677 continue;
4678 }
4679
Robert Carredd13602020-04-13 17:24:34 -07004680 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4681 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004682 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004683 oldHandle->updateFrom(handle);
4684 newHandles.push_back(oldHandle);
4685 } else {
4686 newHandles.push_back(handle);
4687 }
4688 }
4689
4690 // Insert or replace
4691 mWindowHandlesByDisplay[displayId] = newHandles;
4692}
4693
Arthur Hung72d8dc32020-03-28 00:48:39 +00004694void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004695 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004696 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004697 { // acquire lock
4698 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004699 for (const auto& [displayId, handles] : handlesPerDisplay) {
4700 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004701 }
4702 }
4703 // Wake up poll loop since it may need to make new input dispatching choices.
4704 mLooper->wake();
4705}
4706
Arthur Hungb92218b2018-08-14 12:00:21 +08004707/**
4708 * Called from InputManagerService, update window handle list by displayId that can receive input.
4709 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4710 * If set an empty list, remove all handles from the specific display.
4711 * For focused handle, check if need to change and send a cancel event to previous one.
4712 * For removed handle, check if need to send a cancel event if already in touch.
4713 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004714void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004715 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004716 if (DEBUG_FOCUS) {
4717 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004718 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004719 windowList += iwh->getName() + " ";
4720 }
4721 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4722 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723
Prabir Pradhand65552b2021-10-07 11:23:50 -07004724 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004725 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004726 const WindowInfo& info = *window->getInfo();
4727
4728 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004729 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004730 if (noInputWindow && window->getToken() != nullptr) {
4731 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4732 window->getName().c_str());
4733 window->releaseChannel();
4734 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004735
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004736 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004737 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4738 !info.inputConfig.test(
4739 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004740 "%s has feature SPY, but is not a trusted overlay.",
4741 window->getName().c_str());
4742
Prabir Pradhand65552b2021-10-07 11:23:50 -07004743 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004744 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4745 !info.inputConfig.test(
4746 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004747 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4748 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004749 }
4750
Arthur Hung72d8dc32020-03-28 00:48:39 +00004751 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004752 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004754 // Save the old windows' orientation by ID before it gets updated.
4755 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004756 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004757 oldWindowOrientations.emplace(handle->getId(),
4758 handle->getInfo()->transform.getOrientation());
4759 }
4760
chaviw98318de2021-05-19 16:45:23 -05004761 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004762
chaviw98318de2021-05-19 16:45:23 -05004763 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004764 if (mLastHoverWindowHandle &&
4765 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4766 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004767 mLastHoverWindowHandle = nullptr;
4768 }
4769
Vishnu Nairc519ff72021-01-21 08:23:08 -08004770 std::optional<FocusResolver::FocusChanges> changes =
4771 mFocusResolver.setInputWindows(displayId, windowHandles);
4772 if (changes) {
4773 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004775
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004776 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4777 mTouchStatesByDisplay.find(displayId);
4778 if (stateIt != mTouchStatesByDisplay.end()) {
4779 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004780 for (size_t i = 0; i < state.windows.size();) {
4781 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004782 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004783 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004784 ALOGD("Touched window was removed: %s in display %" PRId32,
4785 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004786 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004787 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004788 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4789 if (touchedInputChannel != nullptr) {
4790 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4791 "touched window was removed");
4792 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004793 // Since we are about to drop the touch, cancel the events for the wallpaper as
4794 // well.
4795 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004796 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4797 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004798 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4799 if (wallpaper != nullptr) {
4800 sp<Connection> wallpaperConnection =
4801 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004802 if (wallpaperConnection != nullptr) {
4803 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4804 options);
4805 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004806 }
4807 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004809 state.windows.erase(state.windows.begin() + i);
4810 } else {
4811 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004812 }
4813 }
arthurhungb89ccb02020-12-30 16:19:01 +08004814
arthurhung6d4bed92021-03-17 11:59:33 +08004815 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004816 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004817 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004818 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004819 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004820 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4821 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004822 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004823 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004824 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004825
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004826 // Determine if the orientation of any of the input windows have changed, and cancel all
4827 // pointer events if necessary.
4828 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4829 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4830 if (newWindowHandle != nullptr &&
4831 newWindowHandle->getInfo()->transform.getOrientation() !=
4832 oldWindowOrientations[oldWindowHandle->getId()]) {
4833 std::shared_ptr<InputChannel> inputChannel =
4834 getInputChannelLocked(newWindowHandle->getToken());
4835 if (inputChannel != nullptr) {
4836 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4837 "touched window's orientation changed");
4838 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004839 }
4840 }
4841 }
4842
Arthur Hung72d8dc32020-03-28 00:48:39 +00004843 // Release information for windows that are no longer present.
4844 // This ensures that unused input channels are released promptly.
4845 // Otherwise, they might stick around until the window handle is destroyed
4846 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004847 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004848 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004849 if (DEBUG_FOCUS) {
4850 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004851 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004852 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004853 }
chaviw291d88a2019-02-14 10:33:58 -08004854 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855}
4856
4857void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004858 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004859 if (DEBUG_FOCUS) {
4860 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4861 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4862 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004863 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004864 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004865 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866 } // release lock
4867
4868 // Wake up poll loop since it may need to make new input dispatching choices.
4869 mLooper->wake();
4870}
4871
Vishnu Nair599f1412021-06-21 10:39:58 -07004872void InputDispatcher::setFocusedApplicationLocked(
4873 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4874 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4875 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4876
4877 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4878 return; // This application is already focused. No need to wake up or change anything.
4879 }
4880
4881 // Set the new application handle.
4882 if (inputApplicationHandle != nullptr) {
4883 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4884 } else {
4885 mFocusedApplicationHandlesByDisplay.erase(displayId);
4886 }
4887
4888 // No matter what the old focused application was, stop waiting on it because it is
4889 // no longer focused.
4890 resetNoFocusedWindowTimeoutLocked();
4891}
4892
Tiger Huang721e26f2018-07-24 22:26:19 +08004893/**
4894 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4895 * the display not specified.
4896 *
4897 * We track any unreleased events for each window. If a window loses the ability to receive the
4898 * released event, we will send a cancel event to it. So when the focused display is changed, we
4899 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4900 * display. The display-specified events won't be affected.
4901 */
4902void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004903 if (DEBUG_FOCUS) {
4904 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4905 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004906 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004907 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004908
4909 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004910 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004911 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004912 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004913 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004914 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004915 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004916 CancelationOptions
4917 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4918 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004919 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004920 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4921 }
4922 }
4923 mFocusedDisplayId = displayId;
4924
Chris Ye3c2d6f52020-08-09 10:39:48 -07004925 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004926 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004927 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004928
Vishnu Nairad321cd2020-08-20 16:40:21 -07004929 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004930 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004931 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004932 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004933 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004934 }
4935 }
4936 }
4937
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004938 if (DEBUG_FOCUS) {
4939 logDispatchStateLocked();
4940 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004941 } // release lock
4942
4943 // Wake up poll loop since it may need to make new input dispatching choices.
4944 mLooper->wake();
4945}
4946
Michael Wrightd02c5b62014-02-10 15:10:22 -08004947void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004948 if (DEBUG_FOCUS) {
4949 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004951
4952 bool changed;
4953 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004954 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955
4956 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4957 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004958 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959 }
4960
4961 if (mDispatchEnabled && !enabled) {
4962 resetAndDropEverythingLocked("dispatcher is being disabled");
4963 }
4964
4965 mDispatchEnabled = enabled;
4966 mDispatchFrozen = frozen;
4967 changed = true;
4968 } else {
4969 changed = false;
4970 }
4971
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004972 if (DEBUG_FOCUS) {
4973 logDispatchStateLocked();
4974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004975 } // release lock
4976
4977 if (changed) {
4978 // Wake up poll loop since it may need to make new input dispatching choices.
4979 mLooper->wake();
4980 }
4981}
4982
4983void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004984 if (DEBUG_FOCUS) {
4985 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4986 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004987
4988 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004989 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990
4991 if (mInputFilterEnabled == enabled) {
4992 return;
4993 }
4994
4995 mInputFilterEnabled = enabled;
4996 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4997 } // release lock
4998
4999 // Wake up poll loop since there might be work to do to drop everything.
5000 mLooper->wake();
5001}
5002
Antonio Kanteka042c022022-07-06 16:51:07 -07005003bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5004 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005005 bool needWake = false;
5006 {
5007 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005008 ALOGD_IF(DEBUG_TOUCH_MODE,
5009 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5010 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5011 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5012 mTouchModePerDisplay.count(displayId) == 0
5013 ? "not set"
5014 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5015
5016 // TODO(b/198499018): Ensure that WM can guarantee that touch mode is properly set when
5017 // display is created.
5018 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5019 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005020 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005021 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005022 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005023 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5024 !recentWindowsAreOwnedByLocked(pid, uid)) {
5025 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5026 "window nor none of the previously interacted window",
5027 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005028 return false;
5029 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005030 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005031 mTouchModePerDisplay[displayId] = inTouchMode;
5032 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5033 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005034 needWake = enqueueInboundEventLocked(std::move(entry));
5035 } // release lock
5036
5037 if (needWake) {
5038 mLooper->wake();
5039 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005040 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005041}
5042
Antonio Kantek48710e42022-03-24 14:19:30 -07005043bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5044 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5045 if (focusedToken == nullptr) {
5046 return false;
5047 }
5048 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5049 return isWindowOwnedBy(windowHandle, pid, uid);
5050}
5051
5052bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5053 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5054 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5055 const sp<WindowInfoHandle> windowHandle =
5056 getWindowHandleLocked(connectionToken);
5057 return isWindowOwnedBy(windowHandle, pid, uid);
5058 }) != mInteractionConnectionTokens.end();
5059}
5060
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005061void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5062 if (opacity < 0 || opacity > 1) {
5063 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5064 return;
5065 }
5066
5067 std::scoped_lock lock(mLock);
5068 mMaximumObscuringOpacityForTouch = opacity;
5069}
5070
Arthur Hungabbb9d82021-09-01 14:52:30 +00005071std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
5072 const sp<IBinder>& token) {
5073 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5074 for (TouchedWindow& w : state.windows) {
5075 if (w.windowHandle->getToken() == token) {
5076 return std::make_pair(&state, &w);
5077 }
5078 }
5079 }
5080 return std::make_pair(nullptr, nullptr);
5081}
5082
arthurhungb89ccb02020-12-30 16:19:01 +08005083bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5084 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005085 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005086 if (DEBUG_FOCUS) {
5087 ALOGD("Trivial transfer to same window.");
5088 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005089 return true;
5090 }
5091
Michael Wrightd02c5b62014-02-10 15:10:22 -08005092 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005093 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005094
Arthur Hungabbb9d82021-09-01 14:52:30 +00005095 // Find the target touch state and touched window by fromToken.
5096 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5097 if (state == nullptr || touchedWindow == nullptr) {
5098 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005099 return false;
5100 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005101
5102 const int32_t displayId = state->displayId;
5103 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5104 if (toWindowHandle == nullptr) {
5105 ALOGW("Cannot transfer focus because to window not found.");
5106 return false;
5107 }
5108
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005109 if (DEBUG_FOCUS) {
5110 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005111 touchedWindow->windowHandle->getName().c_str(),
5112 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005113 }
5114
Arthur Hungabbb9d82021-09-01 14:52:30 +00005115 // Erase old window.
5116 int32_t oldTargetFlags = touchedWindow->targetFlags;
5117 BitSet32 pointerIds = touchedWindow->pointerIds;
5118 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005119
Arthur Hungabbb9d82021-09-01 14:52:30 +00005120 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005121 nsecs_t downTimeInTarget = now();
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005122 int32_t newTargetFlags =
5123 oldTargetFlags & (InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
5124 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
5125 newTargetFlags |= InputTarget::FLAG_FOREGROUND;
5126 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005127 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005128
Arthur Hungabbb9d82021-09-01 14:52:30 +00005129 // Store the dragging window.
5130 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005131 if (pointerIds.count() != 1) {
5132 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5133 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005134 return false;
5135 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005136 // Track the pointer id for drag window and generate the drag state.
5137 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005138 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005139 }
5140
Arthur Hungabbb9d82021-09-01 14:52:30 +00005141 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005142 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5143 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005144 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005145 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005146 CancelationOptions
5147 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5148 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005149 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005150 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005151 }
5152
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005153 if (DEBUG_FOCUS) {
5154 logDispatchStateLocked();
5155 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005156 } // release lock
5157
5158 // Wake up poll loop since it may need to make new input dispatching choices.
5159 mLooper->wake();
5160 return true;
5161}
5162
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005163/**
5164 * Get the touched foreground window on the given display.
5165 * Return null if there are no windows touched on that display, or if more than one foreground
5166 * window is being touched.
5167 */
5168sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5169 auto stateIt = mTouchStatesByDisplay.find(displayId);
5170 if (stateIt == mTouchStatesByDisplay.end()) {
5171 ALOGI("No touch state on display %" PRId32, displayId);
5172 return nullptr;
5173 }
5174
5175 const TouchState& state = stateIt->second;
5176 sp<WindowInfoHandle> touchedForegroundWindow;
5177 // If multiple foreground windows are touched, return nullptr
5178 for (const TouchedWindow& window : state.windows) {
5179 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5180 if (touchedForegroundWindow != nullptr) {
5181 ALOGI("Two or more foreground windows: %s and %s",
5182 touchedForegroundWindow->getName().c_str(),
5183 window.windowHandle->getName().c_str());
5184 return nullptr;
5185 }
5186 touchedForegroundWindow = window.windowHandle;
5187 }
5188 }
5189 return touchedForegroundWindow;
5190}
5191
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005192// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005193bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005194 sp<IBinder> fromToken;
5195 { // acquire lock
5196 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005197 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005198 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005199 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5200 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005201 return false;
5202 }
5203
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005204 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5205 if (from == nullptr) {
5206 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5207 return false;
5208 }
5209
5210 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005211 } // release lock
5212
5213 return transferTouchFocus(fromToken, destChannelToken);
5214}
5215
Michael Wrightd02c5b62014-02-10 15:10:22 -08005216void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005217 if (DEBUG_FOCUS) {
5218 ALOGD("Resetting and dropping all events (%s).", reason);
5219 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005220
5221 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5222 synthesizeCancelationEventsForAllConnectionsLocked(options);
5223
5224 resetKeyRepeatLocked();
5225 releasePendingEventLocked();
5226 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005227 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005228
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005229 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005230 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005232 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005233}
5234
5235void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005236 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005237 dumpDispatchStateLocked(dump);
5238
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005239 std::istringstream stream(dump);
5240 std::string line;
5241
5242 while (std::getline(stream, line, '\n')) {
5243 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005244 }
5245}
5246
Prabir Pradhan99987712020-11-10 18:43:05 -08005247std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5248 std::string dump;
5249
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005250 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5251 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005252
5253 std::string windowName = "None";
5254 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005255 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005256 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5257 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5258 : "token has capture without window";
5259 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005260 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005261
5262 return dump;
5263}
5264
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005265void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005266 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5267 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5268 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005269 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005270
Tiger Huang721e26f2018-07-24 22:26:19 +08005271 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5272 dump += StringPrintf(INDENT "FocusedApplications:\n");
5273 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5274 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005275 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005276 const std::chrono::duration timeout =
5277 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005278 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005279 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005280 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005281 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005282 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005283 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005284 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005285
Vishnu Nairc519ff72021-01-21 08:23:08 -08005286 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005287 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005288
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005289 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005290 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005291 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5292 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005293 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005294 state.displayId, toString(state.down), toString(state.split),
5295 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005296 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005297 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005298 for (size_t i = 0; i < state.windows.size(); i++) {
5299 const TouchedWindow& touchedWindow = state.windows[i];
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005300 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, "
5301 "targetFlags=0x%x, firstDownTimeInTarget=%" PRId64
5302 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005303 i, touchedWindow.windowHandle->getName().c_str(),
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005304 touchedWindow.pointerIds.value, touchedWindow.targetFlags,
5305 ns2ms(touchedWindow.firstDownTimeInTarget.value_or(0)));
Jeff Brownf086ddb2014-02-11 14:28:48 -08005306 }
5307 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005308 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005309 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005310 }
5311 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005312 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313 }
5314
arthurhung6d4bed92021-03-17 11:59:33 +08005315 if (mDragState) {
5316 dump += StringPrintf(INDENT "DragState:\n");
5317 mDragState->dump(dump, INDENT2);
5318 }
5319
Arthur Hungb92218b2018-08-14 12:00:21 +08005320 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005321 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5322 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5323 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5324 const auto& displayInfo = it->second;
5325 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5326 displayInfo.logicalHeight);
5327 displayInfo.transform.dump(dump, "transform", INDENT4);
5328 } else {
5329 dump += INDENT2 "No DisplayInfo found!\n";
5330 }
5331
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005332 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005333 dump += INDENT2 "Windows:\n";
5334 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005335 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5336 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005337
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005338 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005339 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005340 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005341 "applicationInfo.name=%s, "
5342 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005343 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005344 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005345 windowInfo->displayId,
5346 windowInfo->inputConfig.string().c_str(),
5347 windowInfo->alpha, windowInfo->frameLeft,
5348 windowInfo->frameTop, windowInfo->frameRight,
5349 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005350 windowInfo->applicationInfo.name.c_str(),
5351 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005352 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005353 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005354 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005355 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005356 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005357 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005358 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005359 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005360 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005361 }
5362 } else {
5363 dump += INDENT2 "Windows: <none>\n";
5364 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005365 }
5366 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005367 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005368 }
5369
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005370 if (!mGlobalMonitorsByDisplay.empty()) {
5371 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5372 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005373 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005374 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005375 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005376 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005377 }
5378
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005379 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005380
5381 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005382 if (!mRecentQueue.empty()) {
5383 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005384 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005385 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005386 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005387 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005388 }
5389 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005390 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005391 }
5392
5393 // Dump event currently being dispatched.
5394 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005395 dump += INDENT "PendingEvent:\n";
5396 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005397 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005398 dump += StringPrintf(", age=%" PRId64 "ms\n",
5399 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005400 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005401 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005402 }
5403
5404 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005405 if (!mInboundQueue.empty()) {
5406 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005407 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005408 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005409 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005410 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005411 }
5412 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005413 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005414 }
5415
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005416 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005417 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005418 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5419 const KeyReplacement& replacement = pair.first;
5420 int32_t newKeyCode = pair.second;
5421 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005422 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005423 }
5424 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005425 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005426 }
5427
Prabir Pradhancef936d2021-07-21 16:17:52 +00005428 if (!mCommandQueue.empty()) {
5429 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5430 } else {
5431 dump += INDENT "CommandQueue: <empty>\n";
5432 }
5433
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005434 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005435 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005436 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005437 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005438 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005439 connection->inputChannel->getFd().get(),
5440 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005441 connection->getWindowName().c_str(),
5442 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005443 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005444
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005445 if (!connection->outboundQueue.empty()) {
5446 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5447 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005448 dump += dumpQueue(connection->outboundQueue, currentTime);
5449
Michael Wrightd02c5b62014-02-10 15:10:22 -08005450 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005451 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005452 }
5453
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005454 if (!connection->waitQueue.empty()) {
5455 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5456 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005457 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005458 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005459 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460 }
5461 }
5462 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005463 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005464 }
5465
5466 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005467 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5468 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005469 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005470 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005471 }
5472
Antonio Kantek15beb512022-06-13 22:35:41 +00005473 if (!mTouchModePerDisplay.empty()) {
5474 dump += INDENT "TouchModePerDisplay:\n";
5475 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5476 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5477 std::to_string(touchMode).c_str());
5478 }
5479 } else {
5480 dump += INDENT "TouchModePerDisplay: <none>\n";
5481 }
5482
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005483 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005484 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5485 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5486 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005487 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005488 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005489}
5490
Michael Wright3dd60e22019-03-27 22:06:44 +00005491void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5492 const size_t numMonitors = monitors.size();
5493 for (size_t i = 0; i < numMonitors; i++) {
5494 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005495 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005496 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5497 dump += "\n";
5498 }
5499}
5500
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005501class LooperEventCallback : public LooperCallback {
5502public:
5503 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5504 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5505
5506private:
5507 std::function<int(int events)> mCallback;
5508};
5509
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005510Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005511 if (DEBUG_CHANNEL_CREATION) {
5512 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5513 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005514
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005515 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005516 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005517 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005518
5519 if (result) {
5520 return base::Error(result) << "Failed to open input channel pair with name " << name;
5521 }
5522
Michael Wrightd02c5b62014-02-10 15:10:22 -08005523 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005524 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005525 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005526 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005527 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005528 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005529
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005530 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5531 ALOGE("Created a new connection, but the token %p is already known", token.get());
5532 }
5533 mConnectionsByToken.emplace(token, connection);
5534
5535 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5536 this, std::placeholders::_1, token);
5537
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005538 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5539 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005540 } // release lock
5541
5542 // Wake the looper because some connections have changed.
5543 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005544 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005545}
5546
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005547Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005548 const std::string& name,
5549 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005550 std::shared_ptr<InputChannel> serverChannel;
5551 std::unique_ptr<InputChannel> clientChannel;
5552 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5553 if (result) {
5554 return base::Error(result) << "Failed to open input channel pair with name " << name;
5555 }
5556
Michael Wright3dd60e22019-03-27 22:06:44 +00005557 { // acquire lock
5558 std::scoped_lock _l(mLock);
5559
5560 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005561 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5562 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005563 }
5564
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005565 sp<Connection> connection =
5566 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005567 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005568 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005569
5570 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5571 ALOGE("Created a new connection, but the token %p is already known", token.get());
5572 }
5573 mConnectionsByToken.emplace(token, connection);
5574 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5575 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005576
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005577 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005578
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005579 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5580 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005581 }
Garfield Tan15601662020-09-22 15:32:38 -07005582
Michael Wright3dd60e22019-03-27 22:06:44 +00005583 // Wake the looper because some connections have changed.
5584 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005585 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005586}
5587
Garfield Tan15601662020-09-22 15:32:38 -07005588status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005589 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005590 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005591
Garfield Tan15601662020-09-22 15:32:38 -07005592 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005593 if (status) {
5594 return status;
5595 }
5596 } // release lock
5597
5598 // Wake the poll loop because removing the connection may have changed the current
5599 // synchronization state.
5600 mLooper->wake();
5601 return OK;
5602}
5603
Garfield Tan15601662020-09-22 15:32:38 -07005604status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5605 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005606 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005607 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005608 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005609 return BAD_VALUE;
5610 }
5611
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005612 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005613
Michael Wrightd02c5b62014-02-10 15:10:22 -08005614 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005615 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005616 }
5617
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005618 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005619
5620 nsecs_t currentTime = now();
5621 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5622
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005623 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005624 return OK;
5625}
5626
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005627void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005628 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5629 auto& [displayId, monitors] = *it;
5630 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5631 return monitor.inputChannel->getConnectionToken() == connectionToken;
5632 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005633
Michael Wright3dd60e22019-03-27 22:06:44 +00005634 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005635 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005636 } else {
5637 ++it;
5638 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005639 }
5640}
5641
Michael Wright3dd60e22019-03-27 22:06:44 +00005642status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005643 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005644 return pilferPointersLocked(token);
5645}
Michael Wright3dd60e22019-03-27 22:06:44 +00005646
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005647status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005648 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5649 if (!requestingChannel) {
5650 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5651 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005652 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005653
5654 auto [statePtr, windowPtr] = findTouchStateAndWindowLocked(token);
5655 if (statePtr == nullptr || windowPtr == nullptr || !statePtr->down) {
5656 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5657 " Ignoring.");
5658 return BAD_VALUE;
5659 }
5660
5661 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005662 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005663 // Send cancel events to all the input channels we're stealing from.
5664 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5665 "input channel stole pointer stream");
5666 options.deviceId = state.deviceId;
5667 options.displayId = state.displayId;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005668 if (state.split) {
5669 // If split pointers then selectively cancel pointers otherwise cancel all pointers
5670 options.pointerIds = window.pointerIds;
5671 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005672 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005673 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005674 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005675 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005676 if (channel != nullptr && channel->getConnectionToken() != token) {
5677 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5678 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5679 canceledWindows += channel->getName();
5680 }
5681 }
5682 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5683 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5684 canceledWindows.c_str());
5685
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005686 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005687 // This only blocks relevant pointers to be sent to other windows
5688 window.isPilferingPointers = true;
5689
5690 if (state.split) {
5691 state.cancelPointersForWindowsExcept(window.pointerIds, token);
5692 } else {
5693 state.filterWindowsExcept(token);
5694 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005695 return OK;
5696}
5697
Prabir Pradhan99987712020-11-10 18:43:05 -08005698void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5699 { // acquire lock
5700 std::scoped_lock _l(mLock);
5701 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005702 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005703 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5704 windowHandle != nullptr ? windowHandle->getName().c_str()
5705 : "token without window");
5706 }
5707
Vishnu Nairc519ff72021-01-21 08:23:08 -08005708 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005709 if (focusedToken != windowToken) {
5710 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5711 enabled ? "enable" : "disable");
5712 return;
5713 }
5714
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005715 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005716 ALOGW("Ignoring request to %s Pointer Capture: "
5717 "window has %s requested pointer capture.",
5718 enabled ? "enable" : "disable", enabled ? "already" : "not");
5719 return;
5720 }
5721
Christine Franksb768bb42021-11-29 12:11:31 -08005722 if (enabled) {
5723 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5724 mIneligibleDisplaysForPointerCapture.end(),
5725 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5726 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5727 return;
5728 }
5729 }
5730
Prabir Pradhan99987712020-11-10 18:43:05 -08005731 setPointerCaptureLocked(enabled);
5732 } // release lock
5733
5734 // Wake the thread to process command entries.
5735 mLooper->wake();
5736}
5737
Christine Franksb768bb42021-11-29 12:11:31 -08005738void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5739 { // acquire lock
5740 std::scoped_lock _l(mLock);
5741 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5742 if (!isEligible) {
5743 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5744 }
5745 } // release lock
5746}
5747
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005748std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5749 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005750 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005751 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005752 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005753 }
5754 }
5755 }
5756 return std::nullopt;
5757}
5758
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005759sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005760 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005761 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005762 }
5763
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005764 for (const auto& [token, connection] : mConnectionsByToken) {
5765 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005766 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005767 }
5768 }
Robert Carr4e670e52018-08-15 13:26:12 -07005769
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005770 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005771}
5772
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005773std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5774 sp<Connection> connection = getConnectionLocked(connectionToken);
5775 if (connection == nullptr) {
5776 return "<nullptr>";
5777 }
5778 return connection->getInputChannelName();
5779}
5780
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005781void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005782 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005783 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005784}
5785
Prabir Pradhancef936d2021-07-21 16:17:52 +00005786void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5787 const sp<Connection>& connection, uint32_t seq,
5788 bool handled, nsecs_t consumeTime) {
5789 // Handle post-event policy actions.
5790 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5791 if (dispatchEntryIt == connection->waitQueue.end()) {
5792 return;
5793 }
5794 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5795 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5796 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5797 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5798 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5799 }
5800 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5801 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5802 connection->inputChannel->getConnectionToken(),
5803 dispatchEntry->deliveryTime, consumeTime, finishTime);
5804 }
5805
5806 bool restartEvent;
5807 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5808 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5809 restartEvent =
5810 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5811 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5812 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5813 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5814 handled);
5815 } else {
5816 restartEvent = false;
5817 }
5818
5819 // Dequeue the event and start the next cycle.
5820 // Because the lock might have been released, it is possible that the
5821 // contents of the wait queue to have been drained, so we need to double-check
5822 // a few things.
5823 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5824 if (dispatchEntryIt != connection->waitQueue.end()) {
5825 dispatchEntry = *dispatchEntryIt;
5826 connection->waitQueue.erase(dispatchEntryIt);
5827 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5828 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5829 if (!connection->responsive) {
5830 connection->responsive = isConnectionResponsive(*connection);
5831 if (connection->responsive) {
5832 // The connection was unresponsive, and now it's responsive.
5833 processConnectionResponsiveLocked(*connection);
5834 }
5835 }
5836 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005837 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005838 connection->outboundQueue.push_front(dispatchEntry);
5839 traceOutboundQueueLength(*connection);
5840 } else {
5841 releaseDispatchEntry(dispatchEntry);
5842 }
5843 }
5844
5845 // Start the next dispatch cycle for this connection.
5846 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005847}
5848
Prabir Pradhancef936d2021-07-21 16:17:52 +00005849void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5850 const sp<IBinder>& newToken) {
5851 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5852 scoped_unlock unlock(mLock);
5853 mPolicy->notifyFocusChanged(oldToken, newToken);
5854 };
5855 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005856}
5857
Prabir Pradhancef936d2021-07-21 16:17:52 +00005858void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5859 auto command = [this, token, x, y]() REQUIRES(mLock) {
5860 scoped_unlock unlock(mLock);
5861 mPolicy->notifyDropWindow(token, x, y);
5862 };
5863 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005864}
5865
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005866void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5867 if (connection == nullptr) {
5868 LOG_ALWAYS_FATAL("Caller must check for nullness");
5869 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005870 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5871 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005872 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005873 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005874 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005875 return;
5876 }
5877 /**
5878 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5879 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5880 * has changed. This could cause newer entries to time out before the already dispatched
5881 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5882 * processes the events linearly. So providing information about the oldest entry seems to be
5883 * most useful.
5884 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005885 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005886 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5887 std::string reason =
5888 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005889 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005890 ns2ms(currentWait),
5891 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005892 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005893 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005894
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005895 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5896
5897 // Stop waking up for events on this connection, it is already unresponsive
5898 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005899}
5900
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005901void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5902 std::string reason =
5903 StringPrintf("%s does not have a focused window", application->getName().c_str());
5904 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005905
Prabir Pradhancef936d2021-07-21 16:17:52 +00005906 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5907 scoped_unlock unlock(mLock);
5908 mPolicy->notifyNoFocusedWindowAnr(application);
5909 };
5910 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005911}
5912
chaviw98318de2021-05-19 16:45:23 -05005913void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005914 const std::string& reason) {
5915 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5916 updateLastAnrStateLocked(windowLabel, reason);
5917}
5918
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005919void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5920 const std::string& reason) {
5921 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005922 updateLastAnrStateLocked(windowLabel, reason);
5923}
5924
5925void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5926 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005927 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005928 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005929 struct tm tm;
5930 localtime_r(&t, &tm);
5931 char timestr[64];
5932 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005933 mLastAnrState.clear();
5934 mLastAnrState += INDENT "ANR:\n";
5935 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005936 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5937 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005938 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005939}
5940
Prabir Pradhancef936d2021-07-21 16:17:52 +00005941void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5942 KeyEntry& entry) {
5943 const KeyEvent event = createKeyEvent(entry);
5944 nsecs_t delay = 0;
5945 { // release lock
5946 scoped_unlock unlock(mLock);
5947 android::base::Timer t;
5948 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5949 entry.policyFlags);
5950 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5951 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5952 std::to_string(t.duration().count()).c_str());
5953 }
5954 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005955
5956 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005957 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005958 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005959 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005960 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005961 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5962 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005963 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005964}
5965
Prabir Pradhancef936d2021-07-21 16:17:52 +00005966void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005967 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005968 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005969 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005970 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005971 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005972 };
5973 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005974}
5975
Prabir Pradhanedd96402022-02-15 01:46:16 -08005976void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5977 std::optional<int32_t> pid) {
5978 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005979 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005980 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005981 };
5982 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005983}
5984
5985/**
5986 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5987 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5988 * command entry to the command queue.
5989 */
5990void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5991 std::string reason) {
5992 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005993 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005994 if (connection.monitor) {
5995 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5996 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005997 pid = findMonitorPidByTokenLocked(connectionToken);
5998 } else {
5999 // The connection is a window
6000 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6001 reason.c_str());
6002 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6003 if (handle != nullptr) {
6004 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006005 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006006 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006007 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006008}
6009
6010/**
6011 * Tell the policy that a connection has become responsive so that it can stop ANR.
6012 */
6013void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6014 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006015 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006016 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006017 pid = findMonitorPidByTokenLocked(connectionToken);
6018 } else {
6019 // The connection is a window
6020 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6021 if (handle != nullptr) {
6022 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006023 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006024 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006025 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006026}
6027
Prabir Pradhancef936d2021-07-21 16:17:52 +00006028bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006029 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006030 KeyEntry& keyEntry, bool handled) {
6031 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006032 if (!handled) {
6033 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006034 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006035 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006036 return false;
6037 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006038
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006039 // Get the fallback key state.
6040 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006041 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006042 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006043 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006044 connection->inputState.removeFallbackKey(originalKeyCode);
6045 }
6046
6047 if (handled || !dispatchEntry->hasForegroundTarget()) {
6048 // If the application handles the original key for which we previously
6049 // generated a fallback or if the window is not a foreground window,
6050 // then cancel the associated fallback key, if any.
6051 if (fallbackKeyCode != -1) {
6052 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006053 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6054 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6055 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6056 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6057 keyEntry.policyFlags);
6058 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006059 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006060 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006061
6062 mLock.unlock();
6063
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006064 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006065 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006066
6067 mLock.lock();
6068
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006069 // Cancel the fallback key.
6070 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006071 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006072 "application handled the original non-fallback key "
6073 "or is no longer a foreground target, "
6074 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006075 options.keyCode = fallbackKeyCode;
6076 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006077 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006078 connection->inputState.removeFallbackKey(originalKeyCode);
6079 }
6080 } else {
6081 // If the application did not handle a non-fallback key, first check
6082 // that we are in a good state to perform unhandled key event processing
6083 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006084 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006085 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006086 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6087 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6088 "since this is not an initial down. "
6089 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6090 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6091 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006092 return false;
6093 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006094
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006095 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006096 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6097 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6098 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6099 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6100 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006101 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006102
6103 mLock.unlock();
6104
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006105 bool fallback =
6106 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006107 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006108
6109 mLock.lock();
6110
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006111 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006112 connection->inputState.removeFallbackKey(originalKeyCode);
6113 return false;
6114 }
6115
6116 // Latch the fallback keycode for this key on an initial down.
6117 // The fallback keycode cannot change at any other point in the lifecycle.
6118 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006119 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006120 fallbackKeyCode = event.getKeyCode();
6121 } else {
6122 fallbackKeyCode = AKEYCODE_UNKNOWN;
6123 }
6124 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6125 }
6126
6127 ALOG_ASSERT(fallbackKeyCode != -1);
6128
6129 // Cancel the fallback key if the policy decides not to send it anymore.
6130 // We will continue to dispatch the key to the policy but we will no
6131 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006132 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6133 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006134 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6135 if (fallback) {
6136 ALOGD("Unhandled key event: Policy requested to send key %d"
6137 "as a fallback for %d, but on the DOWN it had requested "
6138 "to send %d instead. Fallback canceled.",
6139 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6140 } else {
6141 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6142 "but on the DOWN it had requested to send %d. "
6143 "Fallback canceled.",
6144 originalKeyCode, fallbackKeyCode);
6145 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006146 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006147
6148 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6149 "canceling fallback, policy no longer desires it");
6150 options.keyCode = fallbackKeyCode;
6151 synthesizeCancelationEventsForConnectionLocked(connection, options);
6152
6153 fallback = false;
6154 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006155 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006156 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006157 }
6158 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006159
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006160 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6161 {
6162 std::string msg;
6163 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6164 connection->inputState.getFallbackKeys();
6165 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6166 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6167 }
6168 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6169 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006170 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006171 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006172
6173 if (fallback) {
6174 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006175 keyEntry.eventTime = event.getEventTime();
6176 keyEntry.deviceId = event.getDeviceId();
6177 keyEntry.source = event.getSource();
6178 keyEntry.displayId = event.getDisplayId();
6179 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6180 keyEntry.keyCode = fallbackKeyCode;
6181 keyEntry.scanCode = event.getScanCode();
6182 keyEntry.metaState = event.getMetaState();
6183 keyEntry.repeatCount = event.getRepeatCount();
6184 keyEntry.downTime = event.getDownTime();
6185 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006186
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006187 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6188 ALOGD("Unhandled key event: Dispatching fallback key. "
6189 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6190 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6191 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006192 return true; // restart the event
6193 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006194 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6195 ALOGD("Unhandled key event: No fallback key.");
6196 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006197
6198 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006199 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006200 }
6201 }
6202 return false;
6203}
6204
Prabir Pradhancef936d2021-07-21 16:17:52 +00006205bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006206 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006207 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006208 return false;
6209}
6210
Michael Wrightd02c5b62014-02-10 15:10:22 -08006211void InputDispatcher::traceInboundQueueLengthLocked() {
6212 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006213 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006214 }
6215}
6216
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006217void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006218 if (ATRACE_ENABLED()) {
6219 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006220 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6221 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006222 }
6223}
6224
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006225void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006226 if (ATRACE_ENABLED()) {
6227 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006228 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6229 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006230 }
6231}
6232
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006233void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006234 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006235
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006236 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006237 dumpDispatchStateLocked(dump);
6238
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006239 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006240 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006241 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006242 }
6243}
6244
6245void InputDispatcher::monitor() {
6246 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006247 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006248 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006249 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006250}
6251
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006252/**
6253 * Wake up the dispatcher and wait until it processes all events and commands.
6254 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6255 * this method can be safely called from any thread, as long as you've ensured that
6256 * the work you are interested in completing has already been queued.
6257 */
6258bool InputDispatcher::waitForIdle() {
6259 /**
6260 * Timeout should represent the longest possible time that a device might spend processing
6261 * events and commands.
6262 */
6263 constexpr std::chrono::duration TIMEOUT = 100ms;
6264 std::unique_lock lock(mLock);
6265 mLooper->wake();
6266 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6267 return result == std::cv_status::no_timeout;
6268}
6269
Vishnu Naire798b472020-07-23 13:52:21 -07006270/**
6271 * Sets focus to the window identified by the token. This must be called
6272 * after updating any input window handles.
6273 *
6274 * Params:
6275 * request.token - input channel token used to identify the window that should gain focus.
6276 * request.focusedToken - the token that the caller expects currently to be focused. If the
6277 * specified token does not match the currently focused window, this request will be dropped.
6278 * If the specified focused token matches the currently focused window, the call will succeed.
6279 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6280 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6281 * when requesting the focus change. This determines which request gets
6282 * precedence if there is a focus change request from another source such as pointer down.
6283 */
Vishnu Nair958da932020-08-21 17:12:37 -07006284void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6285 { // acquire lock
6286 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006287 std::optional<FocusResolver::FocusChanges> changes =
6288 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6289 if (changes) {
6290 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006291 }
6292 } // release lock
6293 // Wake up poll loop since it may need to make new input dispatching choices.
6294 mLooper->wake();
6295}
6296
Vishnu Nairc519ff72021-01-21 08:23:08 -08006297void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6298 if (changes.oldFocus) {
6299 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006300 if (focusedInputChannel) {
6301 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6302 "focus left window");
6303 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006304 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006305 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006306 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006307 if (changes.newFocus) {
6308 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006309 }
6310
Prabir Pradhan99987712020-11-10 18:43:05 -08006311 // If a window has pointer capture, then it must have focus. We need to ensure that this
6312 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6313 // If the window loses focus before it loses pointer capture, then the window can be in a state
6314 // where it has pointer capture but not focus, violating the contract. Therefore we must
6315 // dispatch the pointer capture event before the focus event. Since focus events are added to
6316 // the front of the queue (above), we add the pointer capture event to the front of the queue
6317 // after the focus events are added. This ensures the pointer capture event ends up at the
6318 // front.
6319 disablePointerCaptureForcedLocked();
6320
Vishnu Nairc519ff72021-01-21 08:23:08 -08006321 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006322 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006323 }
6324}
Vishnu Nair958da932020-08-21 17:12:37 -07006325
Prabir Pradhan99987712020-11-10 18:43:05 -08006326void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006327 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006328 return;
6329 }
6330
6331 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6332
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006333 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006334 setPointerCaptureLocked(false);
6335 }
6336
6337 if (!mWindowTokenWithPointerCapture) {
6338 // No need to send capture changes because no window has capture.
6339 return;
6340 }
6341
6342 if (mPendingEvent != nullptr) {
6343 // Move the pending event to the front of the queue. This will give the chance
6344 // for the pending event to be dropped if it is a captured event.
6345 mInboundQueue.push_front(mPendingEvent);
6346 mPendingEvent = nullptr;
6347 }
6348
6349 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006350 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006351 mInboundQueue.push_front(std::move(entry));
6352}
6353
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006354void InputDispatcher::setPointerCaptureLocked(bool enable) {
6355 mCurrentPointerCaptureRequest.enable = enable;
6356 mCurrentPointerCaptureRequest.seq++;
6357 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006358 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006359 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006360 };
6361 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006362}
6363
Vishnu Nair599f1412021-06-21 10:39:58 -07006364void InputDispatcher::displayRemoved(int32_t displayId) {
6365 { // acquire lock
6366 std::scoped_lock _l(mLock);
6367 // Set an empty list to remove all handles from the specific display.
6368 setInputWindowsLocked(/* window handles */ {}, displayId);
6369 setFocusedApplicationLocked(displayId, nullptr);
6370 // Call focus resolver to clean up stale requests. This must be called after input windows
6371 // have been removed for the removed display.
6372 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006373 // Reset pointer capture eligibility, regardless of previous state.
6374 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006375 // Remove the associated touch mode state.
6376 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006377 } // release lock
6378
6379 // Wake up poll loop since it may need to make new input dispatching choices.
6380 mLooper->wake();
6381}
6382
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006383void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6384 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006385 // The listener sends the windows as a flattened array. Separate the windows by display for
6386 // more convenient parsing.
6387 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006388 for (const auto& info : windowInfos) {
6389 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006390 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006391 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006392
6393 { // acquire lock
6394 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006395
6396 // Ensure that we have an entry created for all existing displays so that if a displayId has
6397 // no windows, we can tell that the windows were removed from the display.
6398 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6399 handlesPerDisplay[displayId];
6400 }
6401
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006402 mDisplayInfos.clear();
6403 for (const auto& displayInfo : displayInfos) {
6404 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6405 }
6406
6407 for (const auto& [displayId, handles] : handlesPerDisplay) {
6408 setInputWindowsLocked(handles, displayId);
6409 }
6410 }
6411 // Wake up poll loop since it may need to make new input dispatching choices.
6412 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006413}
6414
Vishnu Nair062a8672021-09-03 16:07:44 -07006415bool InputDispatcher::shouldDropInput(
6416 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006417 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6418 (windowHandle->getInfo()->inputConfig.test(
6419 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006420 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006421 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6422 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006423 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006424 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006425 windowHandle->getInfo()->displayId);
6426 return true;
6427 }
6428 return false;
6429}
6430
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006431void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6432 const std::vector<gui::WindowInfo>& windowInfos,
6433 const std::vector<DisplayInfo>& displayInfos) {
6434 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6435}
6436
Arthur Hungdfd528e2021-12-08 13:23:04 +00006437void InputDispatcher::cancelCurrentTouch() {
6438 {
6439 std::scoped_lock _l(mLock);
6440 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6441 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6442 "cancel current touch");
6443 synthesizeCancelationEventsForAllConnectionsLocked(options);
6444
6445 mTouchStatesByDisplay.clear();
6446 mLastHoverWindowHandle.clear();
6447 }
6448 // Wake up poll loop since there might be work to do.
6449 mLooper->wake();
6450}
6451
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006452void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6453 std::scoped_lock _l(mLock);
6454 mMonitorDispatchingTimeout = timeout;
6455}
6456
Garfield Tane84e6f92019-08-29 17:28:41 -07006457} // namespace android::inputdispatcher