blob: b52e3128db29049895aee384fd58ddec30071173 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080023#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080024#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050025#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070026#include <binder/Binder.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080027#include <ftl/enum.h>
chaviw15fab6f2021-06-07 14:15:52 -050028#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080029#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070030#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010031#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070032#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
Michael Wright44753b12020-07-08 13:48:11 +010034#include <cerrno>
35#include <cinttypes>
36#include <climits>
37#include <cstddef>
38#include <ctime>
39#include <queue>
40#include <sstream>
41
42#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000043#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070044#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010045
Michael Wrightd02c5b62014-02-10 15:10:22 -080046#define INDENT " "
47#define INDENT2 " "
48#define INDENT3 " "
49#define INDENT4 " "
50
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080051using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000052using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080053using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070054using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050055using android::gui::FocusRequest;
56using android::gui::TouchOcclusionMode;
57using android::gui::WindowInfo;
58using android::gui::WindowInfoHandle;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100059using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080060using android::os::InputEventInjectionResult;
61using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080062
Garfield Tane84e6f92019-08-29 17:28:41 -070063namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080064
Prabir Pradhancef936d2021-07-21 16:17:52 +000065namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000066// Temporarily releases a held mutex for the lifetime of the instance.
67// Named to match std::scoped_lock
68class scoped_unlock {
69public:
70 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
71 ~scoped_unlock() { mMutex.lock(); }
72
73private:
74 std::mutex& mMutex;
75};
76
Michael Wrightd02c5b62014-02-10 15:10:22 -080077// Default input dispatching timeout if there is no focused application or paused window
78// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080079const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
80 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
81 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080082
83// Amount of time to allow for all pending events to be processed when an app switch
84// key is on the way. This is used to preempt input dispatch and drop input events
85// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000086constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080087
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080088const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
Michael Wrightd02c5b62014-02-10 15:10:22 -080090// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000091constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
92
93// Log a warning when an interception call takes longer than this to process.
94constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080095
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -070096// Additional key latency in case a connection is still processing some motion events.
97// This will help with the case when a user touched a button that opens a new window,
98// and gives us the chance to dispatch the key to this new window.
99constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
100
Michael Wrightd02c5b62014-02-10 15:10:22 -0800101// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000102constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
103
Antonio Kantekea47acb2021-12-23 12:41:25 -0800104// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000105constexpr int LOGTAG_INPUT_INTERACTION = 62000;
106constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000107constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000108
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000109inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800110 return systemTime(SYSTEM_TIME_MONOTONIC);
111}
112
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000113inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800114 return value ? "true" : "false";
115}
116
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000117inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000118 if (binder == nullptr) {
119 return "<null>";
120 }
121 return StringPrintf("%p", binder.get());
122}
123
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000124inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700125 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
126 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800127}
128
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000129bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800130 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700131 case AKEY_EVENT_ACTION_DOWN:
132 case AKEY_EVENT_ACTION_UP:
133 return true;
134 default:
135 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800136 }
137}
138
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000139bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700140 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800141 ALOGE("Key event has invalid action code 0x%x", action);
142 return false;
143 }
144 return true;
145}
146
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000147bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800148 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700149 case AMOTION_EVENT_ACTION_DOWN:
150 case AMOTION_EVENT_ACTION_UP:
151 case AMOTION_EVENT_ACTION_CANCEL:
152 case AMOTION_EVENT_ACTION_MOVE:
153 case AMOTION_EVENT_ACTION_OUTSIDE:
154 case AMOTION_EVENT_ACTION_HOVER_ENTER:
155 case AMOTION_EVENT_ACTION_HOVER_MOVE:
156 case AMOTION_EVENT_ACTION_HOVER_EXIT:
157 case AMOTION_EVENT_ACTION_SCROLL:
158 return true;
159 case AMOTION_EVENT_ACTION_POINTER_DOWN:
160 case AMOTION_EVENT_ACTION_POINTER_UP: {
161 int32_t index = getMotionEventActionPointerIndex(action);
162 return index >= 0 && index < pointerCount;
163 }
164 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
165 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
166 return actionButton != 0;
167 default:
168 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800169 }
170}
171
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000172int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500173 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
174}
175
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000176bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
177 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700178 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800179 ALOGE("Motion event has invalid action code 0x%x", action);
180 return false;
181 }
182 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800183 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %zu.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700184 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 return false;
186 }
187 BitSet32 pointerIdBits;
188 for (size_t i = 0; i < pointerCount; i++) {
189 int32_t id = pointerProperties[i].id;
190 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700191 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
192 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800193 return false;
194 }
195 if (pointerIdBits.hasBit(id)) {
196 ALOGE("Motion event has duplicate pointer id %d", id);
197 return false;
198 }
199 pointerIdBits.markBit(id);
200 }
201 return true;
202}
203
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000204std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800205 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000206 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800207 }
208
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000209 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800210 bool first = true;
211 Region::const_iterator cur = region.begin();
212 Region::const_iterator const tail = region.end();
213 while (cur != tail) {
214 if (first) {
215 first = false;
216 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800217 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800219 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 cur++;
221 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000222 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223}
224
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000225std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500226 constexpr size_t maxEntries = 50; // max events to print
227 constexpr size_t skipBegin = maxEntries / 2;
228 const size_t skipEnd = queue.size() - maxEntries / 2;
229 // skip from maxEntries / 2 ... size() - maxEntries/2
230 // only print from 0 .. skipBegin and then from skipEnd .. size()
231
232 std::string dump;
233 for (size_t i = 0; i < queue.size(); i++) {
234 const DispatchEntry& entry = *queue[i];
235 if (i >= skipBegin && i < skipEnd) {
236 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
237 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
238 continue;
239 }
240 dump.append(INDENT4);
241 dump += entry.eventEntry->getDescription();
242 dump += StringPrintf(", seq=%" PRIu32
243 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
244 entry.seq, entry.targetFlags, entry.resolvedAction,
245 ns2ms(currentTime - entry.eventEntry->eventTime));
246 if (entry.deliveryTime != 0) {
247 // This entry was delivered, so add information on how long we've been waiting
248 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
249 }
250 dump.append("\n");
251 }
252 return dump;
253}
254
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700255/**
256 * Find the entry in std::unordered_map by key, and return it.
257 * If the entry is not found, return a default constructed entry.
258 *
259 * Useful when the entries are vectors, since an empty vector will be returned
260 * if the entry is not found.
261 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
262 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700263template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000264V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700265 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700266 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800267}
268
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000269bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700270 if (first == second) {
271 return true;
272 }
273
274 if (first == nullptr || second == nullptr) {
275 return false;
276 }
277
278 return first->getToken() == second->getToken();
279}
280
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000281bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000282 if (first == nullptr || second == nullptr) {
283 return false;
284 }
285 return first->applicationInfo.token != nullptr &&
286 first->applicationInfo.token == second->applicationInfo.token;
287}
288
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000289std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
290 std::shared_ptr<EventEntry> eventEntry,
291 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700292 if (inputTarget.useDefaultPointerTransform()) {
293 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700294 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700295 inputTarget.displayTransform,
296 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000297 }
298
299 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
300 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
301
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700302 std::vector<PointerCoords> pointerCoords;
303 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000304
305 // Use the first pointer information to normalize all other pointers. This could be any pointer
306 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700307 // uses the transform for the normalized pointer.
308 const ui::Transform& firstPointerTransform =
309 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
310 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000311
312 // Iterate through all pointers in the event to normalize against the first.
313 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
314 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
315 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700316 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000317
318 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700319 // First, apply the current pointer's transform to update the coordinates into
320 // window space.
321 pointerCoords[pointerIndex].transform(currTransform);
322 // Next, apply the inverse transform of the normalized coordinates so the
323 // current coordinates are transformed into the normalized coordinate space.
324 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000325 }
326
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700327 std::unique_ptr<MotionEntry> combinedMotionEntry =
328 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
329 motionEntry.deviceId, motionEntry.source,
330 motionEntry.displayId, motionEntry.policyFlags,
331 motionEntry.action, motionEntry.actionButton,
332 motionEntry.flags, motionEntry.metaState,
333 motionEntry.buttonState, motionEntry.classification,
334 motionEntry.edgeFlags, motionEntry.xPrecision,
335 motionEntry.yPrecision, motionEntry.xCursorPosition,
336 motionEntry.yCursorPosition, motionEntry.downTime,
337 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000338 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000339
340 if (motionEntry.injectionState) {
341 combinedMotionEntry->injectionState = motionEntry.injectionState;
342 combinedMotionEntry->injectionState->refCount += 1;
343 }
344
345 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700346 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700347 firstPointerTransform, inputTarget.displayTransform,
348 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000349 return dispatchEntry;
350}
351
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000352status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
353 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700354 std::unique_ptr<InputChannel> uniqueServerChannel;
355 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
356
357 serverChannel = std::move(uniqueServerChannel);
358 return result;
359}
360
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500361template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000362bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500363 if (lhs == nullptr && rhs == nullptr) {
364 return true;
365 }
366 if (lhs == nullptr || rhs == nullptr) {
367 return false;
368 }
369 return *lhs == *rhs;
370}
371
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000372KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000373 KeyEvent event;
374 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
375 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
376 entry.repeatCount, entry.downTime, entry.eventTime);
377 return event;
378}
379
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000380bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000381 // Do not keep track of gesture monitors. They receive every event and would disproportionately
382 // affect the statistics.
383 if (connection.monitor) {
384 return false;
385 }
386 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
387 if (!connection.responsive) {
388 return false;
389 }
390 return true;
391}
392
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000393bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000394 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
395 const int32_t& inputEventId = eventEntry.id;
396 if (inputEventId != dispatchEntry.resolvedEventId) {
397 // Event was transmuted
398 return false;
399 }
400 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
401 return false;
402 }
403 // Only track latency for events that originated from hardware
404 if (eventEntry.isSynthesized()) {
405 return false;
406 }
407 const EventEntry::Type& inputEventEntryType = eventEntry.type;
408 if (inputEventEntryType == EventEntry::Type::KEY) {
409 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
410 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
411 return false;
412 }
413 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
414 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
415 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
416 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
417 return false;
418 }
419 } else {
420 // Not a key or a motion
421 return false;
422 }
423 if (!shouldReportMetricsForConnection(connection)) {
424 return false;
425 }
426 return true;
427}
428
Prabir Pradhancef936d2021-07-21 16:17:52 +0000429/**
430 * Connection is responsive if it has no events in the waitQueue that are older than the
431 * current time.
432 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000433bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000434 const nsecs_t currentTime = now();
435 for (const DispatchEntry* entry : connection.waitQueue) {
436 if (entry->timeoutTime < currentTime) {
437 return false;
438 }
439 }
440 return true;
441}
442
Antonio Kantekf16f2832021-09-28 04:39:20 +0000443// Returns true if the event type passed as argument represents a user activity.
444bool isUserActivityEvent(const EventEntry& eventEntry) {
445 switch (eventEntry.type) {
446 case EventEntry::Type::FOCUS:
447 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
448 case EventEntry::Type::DRAG:
449 case EventEntry::Type::TOUCH_MODE_CHANGED:
450 case EventEntry::Type::SENSOR:
451 case EventEntry::Type::CONFIGURATION_CHANGED:
452 return false;
453 case EventEntry::Type::DEVICE_RESET:
454 case EventEntry::Type::KEY:
455 case EventEntry::Type::MOTION:
456 return true;
457 }
458}
459
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800460// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhand65552b2021-10-07 11:23:50 -0700461bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, int32_t x, int32_t y,
462 bool isStylus) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800463 const auto inputConfig = windowInfo.inputConfig;
464 if (windowInfo.displayId != displayId ||
465 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800466 return false;
467 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700468 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800469 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800470 return false;
471 }
Prabir Pradhan06349042022-02-04 09:19:17 -0800472 if (!windowInfo.touchableRegionContainsPoint(x, y)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800473 return false;
474 }
475 return true;
476}
477
Prabir Pradhand65552b2021-10-07 11:23:50 -0700478bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
479 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
480 (entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
481 entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_ERASER);
482}
483
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000484// Determines if the given window can be targeted as InputTarget::FLAG_FOREGROUND.
485// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
486// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
487// be sent to such a window, but it is not a foreground event and doesn't use
488// InputTarget::FLAG_FOREGROUND.
489bool canReceiveForegroundTouches(const WindowInfo& info) {
490 // A non-touchable window can still receive touch events (e.g. in the case of
491 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
492 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
493}
494
Antonio Kantek48710e42022-03-24 14:19:30 -0700495bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
496 if (windowHandle == nullptr) {
497 return false;
498 }
499 const WindowInfo* windowInfo = windowHandle->getInfo();
500 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
501 return true;
502 }
503 return false;
504}
505
Prabir Pradhan5735a322022-04-11 17:23:34 +0000506// Checks targeted injection using the window's owner's uid.
507// Returns an empty string if an entry can be sent to the given window, or an error message if the
508// entry is a targeted injection whose uid target doesn't match the window owner.
509std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
510 const EventEntry& entry) {
511 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
512 // The event was not injected, or the injected event does not target a window.
513 return {};
514 }
515 const int32_t uid = *entry.injectionState->targetUid;
516 if (window == nullptr) {
517 return StringPrintf("No valid window target for injection into uid %d.", uid);
518 }
519 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
520 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
521 "owned by uid %d.",
522 uid, window->getName().c_str(), window->getInfo()->ownerUid);
523 }
524 return {};
525}
526
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000527} // namespace
528
Michael Wrightd02c5b62014-02-10 15:10:22 -0800529// --- InputDispatcher ---
530
Garfield Tan00f511d2019-06-12 16:55:40 -0700531InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800532 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
533
534InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
535 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700536 : mPolicy(policy),
537 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700538 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800539 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700540 mAppSwitchSawKeyDown(false),
541 mAppSwitchDueTime(LONG_LONG_MAX),
542 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800543 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700544 mDispatchEnabled(false),
545 mDispatchFrozen(false),
546 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800547 // mInTouchMode will be initialized by the WindowManager to the default device config.
548 // To avoid leaking stack in case that call never comes, and for tests,
549 // initialize it here anyways.
Antonio Kantekf16f2832021-09-28 04:39:20 +0000550 mInTouchMode(kDefaultInTouchMode),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100551 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000552 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800553 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800554 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000555 mLatencyAggregator(),
Antonio Kanteka042c022022-07-06 16:51:07 -0700556 mLatencyTracker(&mLatencyAggregator),
557 kPerDisplayTouchModeEnabled(mPolicy->isPerDisplayTouchModeEnabled()) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700558 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800559 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800560
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700561 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700562 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
563
Yi Kong9b14ac62018-07-17 13:48:38 -0700564 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800565
566 policy->getDispatcherConfiguration(&mConfig);
567}
568
569InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000570 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800571
Prabir Pradhancef936d2021-07-21 16:17:52 +0000572 resetKeyRepeatLocked();
573 releasePendingEventLocked();
574 drainInboundQueueLocked();
575 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000577 while (!mConnectionsByToken.empty()) {
578 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000579 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
580 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800581 }
582}
583
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700584status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700585 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700586 return ALREADY_EXISTS;
587 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700588 mThread = std::make_unique<InputThread>(
589 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
590 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700591}
592
593status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700594 if (mThread && mThread->isCallingThread()) {
595 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700596 return INVALID_OPERATION;
597 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700598 mThread.reset();
599 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700600}
601
Michael Wrightd02c5b62014-02-10 15:10:22 -0800602void InputDispatcher::dispatchOnce() {
603 nsecs_t nextWakeupTime = LONG_LONG_MAX;
604 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800605 std::scoped_lock _l(mLock);
606 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800607
608 // Run a dispatch loop if there are no pending commands.
609 // The dispatch loop might enqueue commands to run afterwards.
610 if (!haveCommandsLocked()) {
611 dispatchOnceInnerLocked(&nextWakeupTime);
612 }
613
614 // Run all pending commands if there are any.
615 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000616 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617 nextWakeupTime = LONG_LONG_MIN;
618 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800619
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700620 // If we are still waiting for ack on some events,
621 // we might have to wake up earlier to check if an app is anr'ing.
622 const nsecs_t nextAnrCheck = processAnrsLocked();
623 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
624
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800625 // We are about to enter an infinitely long sleep, because we have no commands or
626 // pending or queued events
627 if (nextWakeupTime == LONG_LONG_MAX) {
628 mDispatcherEnteredIdle.notify_all();
629 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800630 } // release lock
631
632 // Wait for callback or timeout or wake. (make sure we round up, not down)
633 nsecs_t currentTime = now();
634 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
635 mLooper->pollOnce(timeoutMillis);
636}
637
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700638/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500639 * Raise ANR if there is no focused window.
640 * Before the ANR is raised, do a final state check:
641 * 1. The currently focused application must be the same one we are waiting for.
642 * 2. Ensure we still don't have a focused window.
643 */
644void InputDispatcher::processNoFocusedWindowAnrLocked() {
645 // Check if the application that we are waiting for is still focused.
646 std::shared_ptr<InputApplicationHandle> focusedApplication =
647 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
648 if (focusedApplication == nullptr ||
649 focusedApplication->getApplicationToken() !=
650 mAwaitedFocusedApplication->getApplicationToken()) {
651 // Unexpected because we should have reset the ANR timer when focused application changed
652 ALOGE("Waited for a focused window, but focused application has already changed to %s",
653 focusedApplication->getName().c_str());
654 return; // The focused application has changed.
655 }
656
chaviw98318de2021-05-19 16:45:23 -0500657 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500658 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
659 if (focusedWindowHandle != nullptr) {
660 return; // We now have a focused window. No need for ANR.
661 }
Vishnu Nair2f5bc8b2022-08-09 00:03:11 +0000662 std::optional<FocusRequest> pendingRequest =
663 mFocusResolver.getFocusRequest(mAwaitedApplicationDisplayId);
664 if (pendingRequest.has_value() && onAnrLocked(*pendingRequest)) {
665 // We don't have a focusable window but we know which window should have
666 // been focused. Blame that process in case it doesn't belong to the focused app.
667 return;
668 }
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500669 onAnrLocked(mAwaitedFocusedApplication);
670}
671
672/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700673 * Check if any of the connections' wait queues have events that are too old.
674 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
675 * Return the time at which we should wake up next.
676 */
677nsecs_t InputDispatcher::processAnrsLocked() {
678 const nsecs_t currentTime = now();
679 nsecs_t nextAnrCheck = LONG_LONG_MAX;
680 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
681 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
682 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500683 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700684 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500685 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700686 return LONG_LONG_MIN;
687 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500688 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700689 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
690 }
691 }
692
693 // Check if any connection ANRs are due
694 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
695 if (currentTime < nextAnrCheck) { // most likely scenario
696 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
697 }
698
699 // If we reached here, we have an unresponsive connection.
700 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
701 if (connection == nullptr) {
702 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
703 return nextAnrCheck;
704 }
705 connection->responsive = false;
706 // Stop waking up for this unresponsive connection
707 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000708 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700709 return LONG_LONG_MIN;
710}
711
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800712std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
713 const sp<Connection>& connection) {
714 if (connection->monitor) {
715 return mMonitorDispatchingTimeout;
716 }
717 const sp<WindowInfoHandle> window =
718 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700719 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500720 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700721 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500722 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700723}
724
Michael Wrightd02c5b62014-02-10 15:10:22 -0800725void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
726 nsecs_t currentTime = now();
727
Jeff Browndc5992e2014-04-11 01:27:26 -0700728 // Reset the key repeat timer whenever normal dispatch is suspended while the
729 // device is in a non-interactive state. This is to ensure that we abort a key
730 // repeat if the device is just coming out of sleep.
731 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800732 resetKeyRepeatLocked();
733 }
734
735 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
736 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100737 if (DEBUG_FOCUS) {
738 ALOGD("Dispatch frozen. Waiting some more.");
739 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800740 return;
741 }
742
743 // Optimize latency of app switches.
744 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
745 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
746 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
747 if (mAppSwitchDueTime < *nextWakeupTime) {
748 *nextWakeupTime = mAppSwitchDueTime;
749 }
750
751 // Ready to start a new event.
752 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700753 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700754 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755 if (isAppSwitchDue) {
756 // The inbound queue is empty so the app switch key we were waiting
757 // for will never arrive. Stop waiting for it.
758 resetPendingAppSwitchLocked(false);
759 isAppSwitchDue = false;
760 }
761
762 // Synthesize a key repeat if appropriate.
763 if (mKeyRepeatState.lastKeyEntry) {
764 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
765 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
766 } else {
767 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
768 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
769 }
770 }
771 }
772
773 // Nothing to do if there is no pending event.
774 if (!mPendingEvent) {
775 return;
776 }
777 } else {
778 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700779 mPendingEvent = mInboundQueue.front();
780 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781 traceInboundQueueLengthLocked();
782 }
783
784 // Poke user activity for this event.
785 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700786 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 }
789
790 // Now we have an event to dispatch.
791 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700792 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800793 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700794 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800795 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700796 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800797 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700798 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 }
800
801 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700802 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800803 }
804
805 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700806 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700807 const ConfigurationChangedEntry& typedEntry =
808 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700809 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700810 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700811 break;
812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700814 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700815 const DeviceResetEntry& typedEntry =
816 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700817 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700818 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700819 break;
820 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100822 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700823 std::shared_ptr<FocusEntry> typedEntry =
824 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100825 dispatchFocusLocked(currentTime, typedEntry);
826 done = true;
827 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
828 break;
829 }
830
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700831 case EventEntry::Type::TOUCH_MODE_CHANGED: {
832 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
833 dispatchTouchModeChangeLocked(currentTime, typedEntry);
834 done = true;
835 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
836 break;
837 }
838
Prabir Pradhan99987712020-11-10 18:43:05 -0800839 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
840 const auto typedEntry =
841 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
842 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
843 done = true;
844 break;
845 }
846
arthurhungb89ccb02020-12-30 16:19:01 +0800847 case EventEntry::Type::DRAG: {
848 std::shared_ptr<DragEntry> typedEntry =
849 std::static_pointer_cast<DragEntry>(mPendingEvent);
850 dispatchDragLocked(currentTime, typedEntry);
851 done = true;
852 break;
853 }
854
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700855 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700856 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700857 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700858 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700859 resetPendingAppSwitchLocked(true);
860 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700861 } else if (dropReason == DropReason::NOT_DROPPED) {
862 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700863 }
864 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700865 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700866 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700867 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700868 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
869 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700870 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700871 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700872 break;
873 }
874
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700875 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700876 std::shared_ptr<MotionEntry> motionEntry =
877 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700878 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
879 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700881 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700882 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700883 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700884 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
885 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700886 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700887 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700888 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889 }
Chris Yef59a2f42020-10-16 12:55:26 -0700890
891 case EventEntry::Type::SENSOR: {
892 std::shared_ptr<SensorEntry> sensorEntry =
893 std::static_pointer_cast<SensorEntry>(mPendingEvent);
894 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
895 dropReason = DropReason::APP_SWITCH;
896 }
897 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
898 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
899 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
900 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
901 dropReason = DropReason::STALE;
902 }
903 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
904 done = true;
905 break;
906 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907 }
908
909 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700910 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700911 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912 }
Michael Wright3a981722015-06-10 15:26:13 +0100913 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914
915 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700916 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800917 }
918}
919
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800920bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
921 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
922}
923
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700924/**
925 * Return true if the events preceding this incoming motion event should be dropped
926 * Return false otherwise (the default behaviour)
927 */
928bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700929 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700930 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700931
932 // Optimize case where the current application is unresponsive and the user
933 // decides to touch a window in a different application.
934 // If the application takes too long to catch up then we drop all events preceding
935 // the touch into the other window.
936 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700937 int32_t displayId = motionEntry.displayId;
938 int32_t x = static_cast<int32_t>(
939 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
940 int32_t y = static_cast<int32_t>(
941 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Prabir Pradhand65552b2021-10-07 11:23:50 -0700942
943 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -0500944 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700945 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700946 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700947 touchedWindowHandle->getApplicationToken() !=
948 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700949 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700950 ALOGI("Pruning input queue because user touched a different application while waiting "
951 "for %s",
952 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700953 return true;
954 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700955
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800956 // Alternatively, maybe there's a spy window that could handle this event.
957 const std::vector<sp<WindowInfoHandle>> touchedSpies =
958 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
959 for (const auto& windowHandle : touchedSpies) {
960 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000961 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800962 // This spy window could take more input. Drop all events preceding this
963 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700964 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800965 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700966 mAwaitedFocusedApplication->getName().c_str());
967 return true;
968 }
969 }
970 }
971
972 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
973 // yet been processed by some connections, the dispatcher will wait for these motion
974 // events to be processed before dispatching the key event. This is because these motion events
975 // may cause a new window to be launched, which the user might expect to receive focus.
976 // To prevent waiting forever for such events, just send the key to the currently focused window
977 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
978 ALOGD("Received a new pointer down event, stop waiting for events to process and "
979 "just send the pending key event to the focused window.");
980 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700981 }
982 return false;
983}
984
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700985bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700986 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700987 mInboundQueue.push_back(std::move(newEntry));
988 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 traceInboundQueueLengthLocked();
990
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700991 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700992 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +0000993 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
994 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700995 // Optimize app switch latency.
996 // If the application takes too long to catch up then we drop all events preceding
997 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700998 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700999 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001000 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001001 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001002 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001003 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001004 if (DEBUG_APP_SWITCH) {
1005 ALOGD("App switch is pending!");
1006 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001007 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001008 mAppSwitchSawKeyDown = false;
1009 needWake = true;
1010 }
1011 }
1012 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001013
1014 // If a new up event comes in, and the pending event with same key code has been asked
1015 // to try again later because of the policy. We have to reset the intercept key wake up
1016 // time for it may have been handled in the policy and could be dropped.
1017 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1018 mPendingEvent->type == EventEntry::Type::KEY) {
1019 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1020 if (pendingKey.keyCode == keyEntry.keyCode &&
1021 pendingKey.interceptKeyResult ==
1022 KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1023 pendingKey.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1024 pendingKey.interceptKeyWakeupTime = 0;
1025 needWake = true;
1026 }
1027 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001028 break;
1029 }
1030
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001031 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001032 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1033 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001034 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1035 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001036 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001038 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001040 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001041 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1042 break;
1043 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001044 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001045 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001046 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001047 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001048 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1049 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001050 // nothing to do
1051 break;
1052 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 }
1054
1055 return needWake;
1056}
1057
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001058void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001059 // Do not store sensor event in recent queue to avoid flooding the queue.
1060 if (entry->type != EventEntry::Type::SENSOR) {
1061 mRecentQueue.push_back(entry);
1062 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001063 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001064 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 }
1066}
1067
chaviw98318de2021-05-19 16:45:23 -05001068sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1069 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001070 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001071 bool addOutsideTargets,
1072 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001073 if (addOutsideTargets && touchState == nullptr) {
1074 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001075 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001077 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001078 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001079 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001080 continue;
1081 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001083 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001084 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001085 return windowHandle;
1086 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001087
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001088 if (addOutsideTargets &&
1089 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001090 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1091 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092 }
1093 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001094 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001095}
1096
Prabir Pradhand65552b2021-10-07 11:23:50 -07001097std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1098 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001099 // Traverse windows from front to back and gather the touched spy windows.
1100 std::vector<sp<WindowInfoHandle>> spyWindows;
1101 const auto& windowHandles = getWindowHandlesLocked(displayId);
1102 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1103 const WindowInfo& info = *windowHandle->getInfo();
1104
Prabir Pradhand65552b2021-10-07 11:23:50 -07001105 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001106 continue;
1107 }
1108 if (!info.isSpy()) {
1109 // The first touched non-spy window was found, so return the spy windows touched so far.
1110 return spyWindows;
1111 }
1112 spyWindows.push_back(windowHandle);
1113 }
1114 return spyWindows;
1115}
1116
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001117void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118 const char* reason;
1119 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001120 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001121 if (DEBUG_INBOUND_EVENT_DETAILS) {
1122 ALOGD("Dropped event because policy consumed it.");
1123 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001124 reason = "inbound event was dropped because the policy consumed it";
1125 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001126 case DropReason::DISABLED:
1127 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001128 ALOGI("Dropped event because input dispatch is disabled.");
1129 }
1130 reason = "inbound event was dropped because input dispatch is disabled";
1131 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001132 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001133 ALOGI("Dropped event because of pending overdue app switch.");
1134 reason = "inbound event was dropped because of pending overdue app switch";
1135 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001136 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001137 ALOGI("Dropped event because the current application is not responding and the user "
1138 "has started interacting with a different application.");
1139 reason = "inbound event was dropped because the current application is not responding "
1140 "and the user has started interacting with a different application";
1141 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001142 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001143 ALOGI("Dropped event because it is stale.");
1144 reason = "inbound event was dropped because it is stale";
1145 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001146 case DropReason::NO_POINTER_CAPTURE:
1147 ALOGI("Dropped event because there is no window with Pointer Capture.");
1148 reason = "inbound event was dropped because there is no window with Pointer Capture";
1149 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001150 case DropReason::NOT_DROPPED: {
1151 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001152 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001153 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154 }
1155
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001156 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001157 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001158 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1159 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001160 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001162 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001163 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1164 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001165 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1166 synthesizeCancelationEventsForAllConnectionsLocked(options);
1167 } else {
1168 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1169 synthesizeCancelationEventsForAllConnectionsLocked(options);
1170 }
1171 break;
1172 }
Chris Yef59a2f42020-10-16 12:55:26 -07001173 case EventEntry::Type::SENSOR: {
1174 break;
1175 }
arthurhungb89ccb02020-12-30 16:19:01 +08001176 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1177 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001178 break;
1179 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001180 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001181 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001182 case EventEntry::Type::CONFIGURATION_CHANGED:
1183 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001184 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001185 break;
1186 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187 }
1188}
1189
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001190static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001191 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1192 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193}
1194
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001195bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1196 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1197 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1198 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199}
1200
1201bool InputDispatcher::isAppSwitchPendingLocked() {
1202 return mAppSwitchDueTime != LONG_LONG_MAX;
1203}
1204
1205void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1206 mAppSwitchDueTime = LONG_LONG_MAX;
1207
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001208 if (DEBUG_APP_SWITCH) {
1209 if (handled) {
1210 ALOGD("App switch has arrived.");
1211 } else {
1212 ALOGD("App switch was abandoned.");
1213 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215}
1216
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001218 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219}
1220
Prabir Pradhancef936d2021-07-21 16:17:52 +00001221bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001222 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 return false;
1224 }
1225
1226 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001227 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001228 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001229 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1230 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001231 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 return true;
1233}
1234
Prabir Pradhancef936d2021-07-21 16:17:52 +00001235void InputDispatcher::postCommandLocked(Command&& command) {
1236 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237}
1238
1239void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001240 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001241 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001242 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 releaseInboundEventLocked(entry);
1244 }
1245 traceInboundQueueLengthLocked();
1246}
1247
1248void InputDispatcher::releasePendingEventLocked() {
1249 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001251 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 }
1253}
1254
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001255void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001257 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001258 if (DEBUG_DISPATCH_CYCLE) {
1259 ALOGD("Injected inbound event was dropped.");
1260 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001261 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 }
1263 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001264 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 }
1266 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267}
1268
1269void InputDispatcher::resetKeyRepeatLocked() {
1270 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001271 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272 }
1273}
1274
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001275std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1276 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277
Michael Wright2e732952014-09-24 13:26:59 -07001278 uint32_t policyFlags = entry->policyFlags &
1279 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001281 std::shared_ptr<KeyEntry> newEntry =
1282 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1283 entry->source, entry->displayId, policyFlags, entry->action,
1284 entry->flags, entry->keyCode, entry->scanCode,
1285 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001287 newEntry->syntheticRepeat = true;
1288 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001289 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001290 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291}
1292
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001293bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001294 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001295 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1296 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1297 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298
1299 // Reset key repeating in case a keyboard device was added or removed or something.
1300 resetKeyRepeatLocked();
1301
1302 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001303 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1304 scoped_unlock unlock(mLock);
1305 mPolicy->notifyConfigurationChanged(eventTime);
1306 };
1307 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308 return true;
1309}
1310
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001311bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1312 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001313 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1314 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1315 entry.deviceId);
1316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317
liushenxiang42232912021-05-21 20:24:09 +08001318 // Reset key repeating in case a keyboard device was disabled or enabled.
1319 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1320 resetKeyRepeatLocked();
1321 }
1322
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001323 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001324 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325 synthesizeCancelationEventsForAllConnectionsLocked(options);
1326 return true;
1327}
1328
Vishnu Nairad321cd2020-08-20 16:40:21 -07001329void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001330 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001331 if (mPendingEvent != nullptr) {
1332 // Move the pending event to the front of the queue. This will give the chance
1333 // for the pending event to get dispatched to the newly focused window
1334 mInboundQueue.push_front(mPendingEvent);
1335 mPendingEvent = nullptr;
1336 }
1337
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001338 std::unique_ptr<FocusEntry> focusEntry =
1339 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1340 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001341
1342 // This event should go to the front of the queue, but behind all other focus events
1343 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001344 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001345 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001346 [](const std::shared_ptr<EventEntry>& event) {
1347 return event->type == EventEntry::Type::FOCUS;
1348 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001349
1350 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001351 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001352}
1353
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001354void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001355 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001356 if (channel == nullptr) {
1357 return; // Window has gone away
1358 }
1359 InputTarget target;
1360 target.inputChannel = channel;
1361 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1362 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001363 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1364 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001365 std::string reason = std::string("reason=").append(entry->reason);
1366 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001367 dispatchEventLocked(currentTime, entry, {target});
1368}
1369
Prabir Pradhan99987712020-11-10 18:43:05 -08001370void InputDispatcher::dispatchPointerCaptureChangedLocked(
1371 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1372 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001373 dropReason = DropReason::NOT_DROPPED;
1374
Prabir Pradhan99987712020-11-10 18:43:05 -08001375 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001376 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001377
1378 if (entry->pointerCaptureRequest.enable) {
1379 // Enable Pointer Capture.
1380 if (haveWindowWithPointerCapture &&
1381 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001382 // This can happen if pointer capture is disabled and re-enabled before we notify the
1383 // app of the state change, so there is no need to notify the app.
1384 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1385 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001386 }
1387 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001388 // This can happen if a window requests capture and immediately releases capture.
1389 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001390 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001391 return;
1392 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001393 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1394 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1395 return;
1396 }
1397
Vishnu Nairc519ff72021-01-21 08:23:08 -08001398 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001399 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1400 mWindowTokenWithPointerCapture = token;
1401 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001402 // Disable Pointer Capture.
1403 // We do not check if the sequence number matches for requests to disable Pointer Capture
1404 // for two reasons:
1405 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1406 // to disable capture with the same sequence number: one generated by
1407 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1408 // Capture being disabled in InputReader.
1409 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1410 // actual Pointer Capture state that affects events being generated by input devices is
1411 // in InputReader.
1412 if (!haveWindowWithPointerCapture) {
1413 // Pointer capture was already forcefully disabled because of focus change.
1414 dropReason = DropReason::NOT_DROPPED;
1415 return;
1416 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001417 token = mWindowTokenWithPointerCapture;
1418 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001419 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001420 setPointerCaptureLocked(false);
1421 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001422 }
1423
1424 auto channel = getInputChannelLocked(token);
1425 if (channel == nullptr) {
1426 // Window has gone away, clean up Pointer Capture state.
1427 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001428 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001429 setPointerCaptureLocked(false);
1430 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001431 return;
1432 }
1433 InputTarget target;
1434 target.inputChannel = channel;
1435 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1436 entry->dispatchInProgress = true;
1437 dispatchEventLocked(currentTime, entry, {target});
1438
1439 dropReason = DropReason::NOT_DROPPED;
1440}
1441
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001442void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1443 const std::shared_ptr<TouchModeEntry>& entry) {
1444 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1445 getWindowHandlesLocked(mFocusedDisplayId);
1446 if (windowHandles.empty()) {
1447 return;
1448 }
1449 const std::vector<InputTarget> inputTargets =
1450 getInputTargetsFromWindowHandlesLocked(windowHandles);
1451 if (inputTargets.empty()) {
1452 return;
1453 }
1454 entry->dispatchInProgress = true;
1455 dispatchEventLocked(currentTime, entry, inputTargets);
1456}
1457
1458std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1459 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1460 std::vector<InputTarget> inputTargets;
1461 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1462 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1463 const sp<IBinder>& token = handle->getToken();
1464 if (token == nullptr) {
1465 continue;
1466 }
1467 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1468 if (channel == nullptr) {
1469 continue; // Window has gone away
1470 }
1471 InputTarget target;
1472 target.inputChannel = channel;
1473 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1474 inputTargets.push_back(target);
1475 }
1476 return inputTargets;
1477}
1478
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001479bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001480 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001482 if (!entry->dispatchInProgress) {
1483 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1484 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1485 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1486 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001487 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 // We have seen two identical key downs in a row which indicates that the device
1489 // driver is automatically generating key repeats itself. We take note of the
1490 // repeat here, but we disable our own next key repeat timer since it is clear that
1491 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001492 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1493 // Make sure we don't get key down from a different device. If a different
1494 // device Id has same key pressed down, the new device Id will replace the
1495 // current one to hold the key repeat with repeat count reset.
1496 // In the future when got a KEY_UP on the device id, drop it and do not
1497 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001498 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1499 resetKeyRepeatLocked();
1500 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1501 } else {
1502 // Not a repeat. Save key down state in case we do see a repeat later.
1503 resetKeyRepeatLocked();
1504 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1505 }
1506 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001507 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1508 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001509 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001510 if (DEBUG_INBOUND_EVENT_DETAILS) {
1511 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1512 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001513 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 resetKeyRepeatLocked();
1515 }
1516
1517 if (entry->repeatCount == 1) {
1518 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1519 } else {
1520 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1521 }
1522
1523 entry->dispatchInProgress = true;
1524
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001525 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 }
1527
1528 // Handle case where the policy asked us to try again later last time.
1529 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1530 if (currentTime < entry->interceptKeyWakeupTime) {
1531 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1532 *nextWakeupTime = entry->interceptKeyWakeupTime;
1533 }
1534 return false; // wait until next wakeup
1535 }
1536 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1537 entry->interceptKeyWakeupTime = 0;
1538 }
1539
1540 // Give the policy a chance to intercept the key.
1541 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1542 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001543 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001544 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001545
1546 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1547 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1548 };
1549 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 return false; // wait for the command to run
1551 } else {
1552 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1553 }
1554 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001555 if (*dropReason == DropReason::NOT_DROPPED) {
1556 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 }
1558 }
1559
1560 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001561 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001562 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001563 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1564 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001565 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001566 return true;
1567 }
1568
1569 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001570 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001571 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001572 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001573 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574 return false;
1575 }
1576
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001577 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001578 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579 return true;
1580 }
1581
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001582 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001583 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584
1585 // Dispatch the key.
1586 dispatchEventLocked(currentTime, entry, inputTargets);
1587 return true;
1588}
1589
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001590void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001591 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1592 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1593 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1594 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1595 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1596 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1597 entry.metaState, entry.repeatCount, entry.downTime);
1598 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599}
1600
Prabir Pradhancef936d2021-07-21 16:17:52 +00001601void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1602 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001603 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001604 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1605 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1606 "source=0x%x, sensorType=%s",
1607 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001608 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001609 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001610 auto command = [this, entry]() REQUIRES(mLock) {
1611 scoped_unlock unlock(mLock);
1612
1613 if (entry->accuracyChanged) {
1614 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1615 }
1616 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1617 entry->hwTimestamp, entry->values);
1618 };
1619 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001620}
1621
1622bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001623 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1624 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001625 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001626 }
Chris Yef59a2f42020-10-16 12:55:26 -07001627 { // acquire lock
1628 std::scoped_lock _l(mLock);
1629
1630 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1631 std::shared_ptr<EventEntry> entry = *it;
1632 if (entry->type == EventEntry::Type::SENSOR) {
1633 it = mInboundQueue.erase(it);
1634 releaseInboundEventLocked(entry);
1635 }
1636 }
1637 }
1638 return true;
1639}
1640
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001641bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001642 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001643 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001645 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001646 entry->dispatchInProgress = true;
1647
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001648 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 }
1650
1651 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001652 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001653 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001654 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1655 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656 return true;
1657 }
1658
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001659 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660
1661 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001662 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001663
1664 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001665 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 if (isPointerEvent) {
1667 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001668
1669 if (mDragState &&
1670 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1671 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1672 pilferPointersLocked(mDragState->dragWindow->getToken());
1673 }
1674
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001675 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001676 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001677 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 } else {
1679 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001680 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001681 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001683 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684 return false;
1685 }
1686
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001687 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001688 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001689 return true;
1690 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001691 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001692 CancelationOptions::Mode mode(isPointerEvent
1693 ? CancelationOptions::CANCEL_POINTER_EVENTS
1694 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1695 CancelationOptions options(mode, "input event injection failed");
1696 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697 return true;
1698 }
1699
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001700 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001701 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001702
1703 // Dispatch the motion.
1704 if (conflictingPointerActions) {
1705 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001706 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 synthesizeCancelationEventsForAllConnectionsLocked(options);
1708 }
1709 dispatchEventLocked(currentTime, entry, inputTargets);
1710 return true;
1711}
1712
chaviw98318de2021-05-19 16:45:23 -05001713void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001714 bool isExiting, const int32_t rawX,
1715 const int32_t rawY) {
1716 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001717 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001718 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1719 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001720
1721 enqueueInboundEventLocked(std::move(dragEntry));
1722}
1723
1724void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1725 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1726 if (channel == nullptr) {
1727 return; // Window has gone away
1728 }
1729 InputTarget target;
1730 target.inputChannel = channel;
1731 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1732 entry->dispatchInProgress = true;
1733 dispatchEventLocked(currentTime, entry, {target});
1734}
1735
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001736void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001737 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1738 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1739 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001740 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001741 "metaState=0x%x, buttonState=0x%x,"
1742 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1743 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001744 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1745 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1746 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001748 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1749 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1750 "x=%f, y=%f, pressure=%f, size=%f, "
1751 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1752 "orientation=%f",
1753 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1754 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1755 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1756 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1757 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1758 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1759 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1760 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1761 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1762 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1763 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001764 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765}
1766
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001767void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1768 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001769 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001770 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001771 if (DEBUG_DISPATCH_CYCLE) {
1772 ALOGD("dispatchEventToCurrentInputTargets");
1773 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001775 updateInteractionTokensLocked(*eventEntry, inputTargets);
1776
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1778
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001779 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001781 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001782 sp<Connection> connection =
1783 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001784 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001785 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001786 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001787 if (DEBUG_FOCUS) {
1788 ALOGD("Dropping event delivery to target with channel '%s' because it "
1789 "is no longer registered with the input dispatcher.",
1790 inputTarget.inputChannel->getName().c_str());
1791 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792 }
1793 }
1794}
1795
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001796void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1797 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1798 // If the policy decides to close the app, we will get a channel removal event via
1799 // unregisterInputChannel, and will clean up the connection that way. We are already not
1800 // sending new pointers to the connection when it blocked, but focused events will continue to
1801 // pile up.
1802 ALOGW("Canceling events for %s because it is unresponsive",
1803 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001804 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001805 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1806 "application not responding");
1807 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 }
1809}
1810
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001811void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001812 if (DEBUG_FOCUS) {
1813 ALOGD("Resetting ANR timeouts.");
1814 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001815
1816 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001817 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001818 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819}
1820
Tiger Huang721e26f2018-07-24 22:26:19 +08001821/**
1822 * Get the display id that the given event should go to. If this event specifies a valid display id,
1823 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1824 * Focused display is the display that the user most recently interacted with.
1825 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001826int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001827 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001828 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001829 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001830 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1831 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001832 break;
1833 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001834 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001835 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1836 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001837 break;
1838 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001839 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001840 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001841 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001842 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001843 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001844 case EventEntry::Type::SENSOR:
1845 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001846 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001847 return ADISPLAY_ID_NONE;
1848 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001849 }
1850 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1851}
1852
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001853bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1854 const char* focusedWindowName) {
1855 if (mAnrTracker.empty()) {
1856 // already processed all events that we waited for
1857 mKeyIsWaitingForEventsTimeout = std::nullopt;
1858 return false;
1859 }
1860
1861 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1862 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001863 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001864 mKeyIsWaitingForEventsTimeout = currentTime +
1865 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1866 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001867 return true;
1868 }
1869
1870 // We still have pending events, and already started the timer
1871 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1872 return true; // Still waiting
1873 }
1874
1875 // Waited too long, and some connection still hasn't processed all motions
1876 // Just send the key to the focused window
1877 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1878 focusedWindowName);
1879 mKeyIsWaitingForEventsTimeout = std::nullopt;
1880 return false;
1881}
1882
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001883static std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
1884 if (eventEntry.type == EventEntry::Type::KEY) {
1885 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
1886 return keyEntry.downTime;
1887 } else if (eventEntry.type == EventEntry::Type::MOTION) {
1888 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
1889 return motionEntry.downTime;
1890 }
1891 return std::nullopt;
1892}
1893
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001894InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1895 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1896 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001897 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898
Tiger Huang721e26f2018-07-24 22:26:19 +08001899 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001900 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001901 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001902 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1903
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 // If there is no currently focused window and no focused application
1905 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001906 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1907 ALOGI("Dropping %s event because there is no focused window or focused application in "
1908 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001909 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001910 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911 }
1912
Vishnu Nair062a8672021-09-03 16:07:44 -07001913 // Drop key events if requested by input feature
1914 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1915 return InputEventInjectionResult::FAILED;
1916 }
1917
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001918 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1919 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1920 // start interacting with another application via touch (app switch). This code can be removed
1921 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1922 // an app is expected to have a focused window.
1923 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1924 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1925 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001926 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1927 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1928 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001929 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001930 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001931 ALOGW("Waiting because no window has focus but %s may eventually add a "
1932 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001933 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001934 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001935 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001936 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1937 // Already raised ANR. Drop the event
1938 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001939 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001940 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001941 } else {
1942 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001943 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001944 }
1945 }
1946
1947 // we have a valid, non-null focused window
1948 resetNoFocusedWindowTimeoutLocked();
1949
Prabir Pradhan5735a322022-04-11 17:23:34 +00001950 // Verify targeted injection.
1951 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
1952 ALOGW("Dropping injected event: %s", (*err).c_str());
1953 return InputEventInjectionResult::TARGET_MISMATCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954 }
1955
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001956 if (focusedWindowHandle->getInfo()->inputConfig.test(
1957 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001958 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001959 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001960 }
1961
1962 // If the event is a key event, then we must wait for all previous events to
1963 // complete before delivering it because previous events may have the
1964 // side-effect of transferring focus to a different window and we want to
1965 // ensure that the following keys are sent to the new window.
1966 //
1967 // Suppose the user touches a button in a window then immediately presses "A".
1968 // If the button causes a pop-up window to appear then we want to ensure that
1969 // the "A" key is delivered to the new pop-up window. This is because users
1970 // often anticipate pending UI changes when typing on a keyboard.
1971 // To obtain this behavior, we must serialize key events with respect to all
1972 // prior input events.
1973 if (entry.type == EventEntry::Type::KEY) {
1974 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1975 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001976 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978 }
1979
1980 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001981 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001982 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001983 BitSet32(0), getDownTime(entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001984
1985 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001986 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987}
1988
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001989/**
1990 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1991 * that are currently unresponsive.
1992 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001993std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1994 const std::vector<Monitor>& monitors) const {
1995 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001996 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001997 [this](const Monitor& monitor) REQUIRES(mLock) {
1998 sp<Connection> connection =
1999 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002000 if (connection == nullptr) {
2001 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002002 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002003 return false;
2004 }
2005 if (!connection->responsive) {
2006 ALOGW("Unresponsive monitor %s will not get the new gesture",
2007 connection->inputChannel->getName().c_str());
2008 return false;
2009 }
2010 return true;
2011 });
2012 return responsiveMonitors;
2013}
2014
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002015InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
2016 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
2017 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002018 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 // For security reasons, we defer updating the touch state until we are sure that
2021 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002022 const int32_t displayId = entry.displayId;
2023 const int32_t action = entry.action;
2024 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025
2026 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002027 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
chaviw98318de2021-05-19 16:45:23 -05002028 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2029 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002031 // Copy current touch state into tempTouchState.
2032 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2033 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002034 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002035 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002036 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2037 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002038 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002039 }
2040
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002041 bool isSplit = tempTouchState.split;
2042 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2043 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2044 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002045
2046 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2047 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2048 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2049 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2050 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002051 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002052 bool wrongDevice = false;
2053 if (newGesture) {
2054 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002055 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002056 ALOGI("Dropping event because a pointer for a different device is already down "
2057 "in display %" PRId32,
2058 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002059 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002060 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061 switchedDevice = false;
2062 wrongDevice = true;
2063 goto Failed;
2064 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002065 tempTouchState.reset();
2066 tempTouchState.down = down;
2067 tempTouchState.deviceId = entry.deviceId;
2068 tempTouchState.source = entry.source;
2069 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002071 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002072 ALOGI("Dropping move event because a pointer for a different device is already active "
2073 "in display %" PRId32,
2074 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002075 // TODO: test multiple simultaneous input streams.
Prabir Pradhan5735a322022-04-11 17:23:34 +00002076 injectionResult = InputEventInjectionResult::FAILED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002077 switchedDevice = false;
2078 wrongDevice = true;
2079 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 }
2081
2082 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2083 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2084
Garfield Tan00f511d2019-06-12 16:55:40 -07002085 int32_t x;
2086 int32_t y;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002087 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002088 // Always dispatch mouse events to cursor position.
2089 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002090 x = int32_t(entry.xCursorPosition);
2091 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002092 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002093 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2094 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002095 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002096 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002097 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002098 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002099 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002100
Michael Wrightd02c5b62014-02-10 15:10:22 -08002101 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002102 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002103 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2104 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002106 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002107 }
2108
Prabir Pradhan5735a322022-04-11 17:23:34 +00002109 // Verify targeted injection.
2110 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2111 ALOGW("Dropping injected touch event: %s", (*err).c_str());
2112 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2113 newTouchedWindowHandle = nullptr;
2114 goto Failed;
2115 }
2116
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002117 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002118 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002119 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2120 // New window supports splitting, but we should never split mouse events.
2121 isSplit = !isFromMouse;
2122 } else if (isSplit) {
2123 // New window does not support splitting but we have already split events.
2124 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002125 newTouchedWindowHandle = nullptr;
2126 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002127 } else {
2128 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002129 // be delivered to a new window which supports split touch. Pointers from a mouse device
2130 // should never be split.
2131 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002132 }
2133
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002134 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002135 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002136 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2137 newHoverWindowHandle = nullptr;
2138 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002139 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002140 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002141 }
2142
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002143 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002144 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002145 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002146 // Process the foreground window first so that it is the first to receive the event.
2147 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002148 }
2149
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002150 if (newTouchedWindows.empty()) {
2151 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2152 x, y, displayId);
2153 injectionResult = InputEventInjectionResult::FAILED;
2154 goto Failed;
2155 }
2156
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002157 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2158 const WindowInfo& info = *windowHandle->getInfo();
2159
Prabir Pradhan5735a322022-04-11 17:23:34 +00002160 // Skip spy window targets that are not valid for targeted injection.
2161 if (const auto err = verifyTargetedInjection(windowHandle, entry); err) {
2162 continue;
2163 }
2164
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002165 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002166 ALOGI("Not sending touch event to %s because it is paused",
2167 windowHandle->getName().c_str());
2168 continue;
2169 }
2170
2171 // Ensure the window has a connection and the connection is responsive
2172 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2173 if (!isResponsive) {
2174 ALOGW("Not sending touch gesture to %s because it is not responsive",
2175 windowHandle->getName().c_str());
2176 continue;
2177 }
2178
2179 // Drop events that can't be trusted due to occlusion
Hani Kazmi3ce9c3a2022-04-25 09:40:23 +00002180 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(windowHandle, x, y);
2181 if (!isTouchTrustedLocked(occlusionInfo)) {
2182 if (DEBUG_TOUCH_OCCLUSION) {
2183 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2184 for (const auto& log : occlusionInfo.debugInfo) {
2185 ALOGD("%s", log.c_str());
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002186 }
2187 }
Hani Kazmi3ce9c3a2022-04-25 09:40:23 +00002188 ALOGW("Dropping untrusted touch event due to %s/%d",
2189 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2190 continue;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002191 }
2192
2193 // Drop touch events if requested by input feature
2194 if (shouldDropInput(entry, windowHandle)) {
2195 continue;
2196 }
2197
2198 // Set target flags.
2199 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2200
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002201 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2202 // There should only be one touched window that can be "foreground" for the pointer.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002203 targetFlags |= InputTarget::FLAG_FOREGROUND;
2204 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002205
2206 if (isSplit) {
2207 targetFlags |= InputTarget::FLAG_SPLIT;
2208 }
2209 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2210 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2211 } else if (isWindowObscuredLocked(windowHandle)) {
2212 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2213 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002214
2215 // Update the temporary touch state.
2216 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002217 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002218
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002219 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
2220 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002222
2223 // If any existing window is pilfering pointers from newly added window, remove it
2224 BitSet32 canceledPointers = BitSet32(0);
2225 for (const TouchedWindow& window : tempTouchState.windows) {
2226 if (window.isPilferingPointers) {
2227 canceledPointers |= window.pointerIds;
2228 }
2229 }
2230 tempTouchState.cancelPointersForNonPilferingWindows(canceledPointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231 } else {
2232 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2233
2234 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002235 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002236 if (DEBUG_FOCUS) {
2237 ALOGD("Dropping event because the pointer is not down or we previously "
2238 "dropped the pointer down event in display %" PRId32,
2239 displayId);
2240 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002241 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 goto Failed;
2243 }
2244
arthurhung6d4bed92021-03-17 11:59:33 +08002245 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002246
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002248 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002249 tempTouchState.isSlippery()) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002250 const int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2251 const int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252
Prabir Pradhand65552b2021-10-07 11:23:50 -07002253 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002254 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002255 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002256 newTouchedWindowHandle =
2257 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002258
Prabir Pradhan5735a322022-04-11 17:23:34 +00002259 // Verify targeted injection.
2260 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2261 ALOGW("Dropping injected event: %s", (*err).c_str());
2262 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2263 newTouchedWindowHandle = nullptr;
2264 goto Failed;
2265 }
2266
Vishnu Nair062a8672021-09-03 16:07:44 -07002267 // Drop touch events if requested by input feature
2268 if (newTouchedWindowHandle != nullptr &&
2269 shouldDropInput(entry, newTouchedWindowHandle)) {
2270 newTouchedWindowHandle = nullptr;
2271 }
2272
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002273 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2274 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002275 if (DEBUG_FOCUS) {
2276 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2277 oldTouchedWindowHandle->getName().c_str(),
2278 newTouchedWindowHandle->getName().c_str(), displayId);
2279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002281 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2282 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2283 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284
2285 // Make a slippery entrance into the new window.
2286 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002287 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 }
2289
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002290 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
2291 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
2292 targetFlags |= InputTarget::FLAG_FOREGROUND;
2293 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 if (isSplit) {
2295 targetFlags |= InputTarget::FLAG_SPLIT;
2296 }
2297 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2298 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002299 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2300 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 }
2302
2303 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002304 pointerIds.markBit(entry.pointerProperties[0].id);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002305 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2306 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002307 }
2308 }
2309 }
2310
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002311 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002313 // Let the previous window know that the hover sequence is over, unless we already did
2314 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002315 if (mLastHoverWindowHandle != nullptr &&
2316 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2317 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002318 if (DEBUG_HOVER) {
2319 ALOGD("Sending hover exit event to window %s.",
2320 mLastHoverWindowHandle->getName().c_str());
2321 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002322 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2323 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002324 }
2325
Garfield Tandf26e862020-07-01 20:18:19 -07002326 // Let the new window know that the hover sequence is starting, unless we already did it
2327 // when dispatching it as is to newTouchedWindowHandle.
2328 if (newHoverWindowHandle != nullptr &&
2329 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2330 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002331 if (DEBUG_HOVER) {
2332 ALOGD("Sending hover enter event to window %s.",
2333 newHoverWindowHandle->getName().c_str());
2334 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002335 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2336 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2337 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338 }
2339 }
2340
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002341 // Ensure that we have at least one foreground window or at least one window that cannot be a
2342 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2343 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2344 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002345 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2346 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002347 return !canReceiveForegroundTouches(
2348 *touchedWindow.windowHandle->getInfo()) ||
2349 (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002350 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002351 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2352 displayId, entry.getDescription().c_str());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002353 injectionResult = InputEventInjectionResult::FAILED;
2354 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 }
2356
Prabir Pradhan5735a322022-04-11 17:23:34 +00002357 // Ensure that all touched windows are valid for injection.
2358 if (entry.injectionState != nullptr) {
2359 std::string errs;
2360 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
2361 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2362 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2363 // dispatched to any uid, since the coords will be zeroed out later.
2364 continue;
2365 }
2366 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2367 if (err) errs += "\n - " + *err;
2368 }
2369 if (!errs.empty()) {
2370 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2371 "%d:%s",
2372 *entry.injectionState->targetUid, errs.c_str());
2373 injectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2374 goto Failed;
2375 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002376 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002377
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378 // Check whether windows listening for outside touches are owned by the same UID. If it is
2379 // set the policy flag that we will not reveal coordinate information to this window.
2380 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002381 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002382 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002383 if (foregroundWindowHandle) {
2384 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002385 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002386 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002387 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2388 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2389 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002390 InputTarget::FLAG_ZERO_COORDS,
2391 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393 }
2394 }
2395 }
2396 }
2397
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398 // If this is the first pointer going down and the touched window has a wallpaper
2399 // then also add the touched wallpaper windows so they are locked in for the duration
2400 // of the touch gesture.
2401 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2402 // engine only supports touch events. We would need to add a mechanism similar
2403 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2404 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002405 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002406 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002407 if (foregroundWindowHandle &&
2408 foregroundWindowHandle->getInfo()->inputConfig.test(
2409 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002410 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002411 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002412 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2413 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002414 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002415 windowHandle->getInfo()->inputConfig.test(
2416 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002417 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002418 .addOrUpdateWindow(windowHandle,
2419 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2420 InputTarget::
2421 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2422 InputTarget::FLAG_DISPATCH_AS_IS,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002423 BitSet32(0), entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424 }
2425 }
2426 }
2427 }
2428
2429 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002430 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002431
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002432 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002434 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2435 inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436 }
2437
2438 // Drop the outside or hover touch windows since we will not care about them
2439 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002440 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441
2442Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002443 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002444 if (!wrongDevice) {
2445 if (switchedDevice) {
2446 if (DEBUG_FOCUS) {
2447 ALOGD("Conflicting pointer actions: Switched to a different device.");
2448 }
2449 *outConflictingPointerActions = true;
2450 }
2451
2452 if (isHoverAction) {
2453 // Started hovering, therefore no longer down.
2454 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002455 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002456 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2457 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002458 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002459 *outConflictingPointerActions = true;
2460 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002461 tempTouchState.reset();
2462 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2463 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2464 tempTouchState.deviceId = entry.deviceId;
2465 tempTouchState.source = entry.source;
2466 tempTouchState.displayId = displayId;
2467 }
2468 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2469 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2470 // All pointers up or canceled.
2471 tempTouchState.reset();
2472 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2473 // First pointer went down.
2474 if (oldState && oldState->down) {
2475 if (DEBUG_FOCUS) {
2476 ALOGD("Conflicting pointer actions: Down received while already down.");
2477 }
2478 *outConflictingPointerActions = true;
2479 }
2480 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2481 // One pointer went up.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002482 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2483 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002485 for (size_t i = 0; i < tempTouchState.windows.size();) {
2486 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2487 touchedWindow.pointerIds.clearBit(pointerId);
2488 if (touchedWindow.pointerIds.isEmpty()) {
2489 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2490 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002492 i += 1;
2493 }
2494 } else if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2495 // If no split, we suppose all touched windows should receive pointer down.
2496 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2497 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2498 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2499 // Ignore drag window for it should just track one pointer.
2500 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2501 continue;
2502 }
2503 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Jeff Brownf086ddb2014-02-11 14:28:48 -08002504 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002505 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002506
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002507 // Save changes unless the action was scroll in which case the temporary touch
2508 // state was only valid for this one action.
2509 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2510 if (tempTouchState.displayId >= 0) {
2511 mTouchStatesByDisplay[displayId] = tempTouchState;
2512 } else {
2513 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002514 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002515 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002517 // Update hover state.
2518 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002519 }
2520
Michael Wrightd02c5b62014-02-10 15:10:22 -08002521 return injectionResult;
2522}
2523
arthurhung6d4bed92021-03-17 11:59:33 +08002524void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002525 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2526 // have an explicit reason to support it.
2527 constexpr bool isStylus = false;
2528
chaviw98318de2021-05-19 16:45:23 -05002529 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002530 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002531 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002532 if (dropWindow) {
2533 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002534 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002535 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002536 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002537 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002538 }
2539 mDragState.reset();
2540}
2541
2542void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002543 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002544 return;
2545 }
2546
arthurhung6d4bed92021-03-17 11:59:33 +08002547 if (!mDragState->isStartDrag) {
2548 mDragState->isStartDrag = true;
2549 mDragState->isStylusButtonDownAtStart =
2550 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2551 }
2552
Arthur Hung54745652022-04-20 07:17:41 +00002553 // Find the pointer index by id.
2554 int32_t pointerIndex = 0;
2555 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2556 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2557 if (pointerProperties.id == mDragState->pointerId) {
2558 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002559 }
Arthur Hung54745652022-04-20 07:17:41 +00002560 }
arthurhung6d4bed92021-03-17 11:59:33 +08002561
Arthur Hung54745652022-04-20 07:17:41 +00002562 if (uint32_t(pointerIndex) == entry.pointerCount) {
2563 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002564 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002565 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002566 return;
2567 }
2568
2569 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2570 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2571 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2572
2573 switch (maskedAction) {
2574 case AMOTION_EVENT_ACTION_MOVE: {
2575 // Handle the special case : stylus button no longer pressed.
2576 bool isStylusButtonDown =
2577 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2578 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2579 finishDragAndDrop(entry.displayId, x, y);
2580 return;
2581 }
2582
2583 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2584 // until we have an explicit reason to support it.
2585 constexpr bool isStylus = false;
2586
2587 const sp<WindowInfoHandle> hoverWindowHandle =
2588 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2589 isStylus, false /*addOutsideTargets*/,
2590 true /*ignoreDragWindow*/);
2591 // enqueue drag exit if needed.
2592 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2593 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2594 if (mDragState->dragHoverWindowHandle != nullptr) {
2595 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2596 y);
2597 }
2598 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2599 }
2600 // enqueue drag location if needed.
2601 if (hoverWindowHandle != nullptr) {
2602 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2603 }
2604 break;
2605 }
2606
2607 case AMOTION_EVENT_ACTION_POINTER_UP:
2608 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2609 break;
2610 }
2611 // The drag pointer is up.
2612 [[fallthrough]];
2613 case AMOTION_EVENT_ACTION_UP:
2614 finishDragAndDrop(entry.displayId, x, y);
2615 break;
2616 case AMOTION_EVENT_ACTION_CANCEL: {
2617 ALOGD("Receiving cancel when drag and drop.");
2618 sendDropWindowCommandLocked(nullptr, 0, 0);
2619 mDragState.reset();
2620 break;
2621 }
arthurhungb89ccb02020-12-30 16:19:01 +08002622 }
2623}
2624
chaviw98318de2021-05-19 16:45:23 -05002625void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002626 int32_t targetFlags, BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002627 std::optional<nsecs_t> firstDownTimeInTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002628 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002629 std::vector<InputTarget>::iterator it =
2630 std::find_if(inputTargets.begin(), inputTargets.end(),
2631 [&windowHandle](const InputTarget& inputTarget) {
2632 return inputTarget.inputChannel->getConnectionToken() ==
2633 windowHandle->getToken();
2634 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002635
chaviw98318de2021-05-19 16:45:23 -05002636 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002637
2638 if (it == inputTargets.end()) {
2639 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002640 std::shared_ptr<InputChannel> inputChannel =
2641 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002642 if (inputChannel == nullptr) {
2643 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2644 return;
2645 }
2646 inputTarget.inputChannel = inputChannel;
2647 inputTarget.flags = targetFlags;
2648 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002649 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002650 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2651 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002652 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002653 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002654 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002655 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002656 inputTargets.push_back(inputTarget);
2657 it = inputTargets.end() - 1;
2658 }
2659
2660 ALOG_ASSERT(it->flags == targetFlags);
2661 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2662
chaviw1ff3d1e2020-07-01 15:53:47 -07002663 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002664}
2665
Michael Wright3dd60e22019-03-27 22:06:44 +00002666void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002667 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002668 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2669 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002670
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002671 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2672 InputTarget target;
2673 target.inputChannel = monitor.inputChannel;
2674 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002675 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2676 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002677 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2678 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002679 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002680 target.setDefaultPointerTransform(target.displayTransform);
2681 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682 }
2683}
2684
Robert Carrc9bf1d32020-04-13 17:21:08 -07002685/**
2686 * Indicate whether one window handle should be considered as obscuring
2687 * another window handle. We only check a few preconditions. Actually
2688 * checking the bounds is left to the caller.
2689 */
chaviw98318de2021-05-19 16:45:23 -05002690static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2691 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002692 // Compare by token so cloned layers aren't counted
2693 if (haveSameToken(windowHandle, otherHandle)) {
2694 return false;
2695 }
2696 auto info = windowHandle->getInfo();
2697 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002698 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002699 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002700 } else if (otherInfo->alpha == 0 &&
2701 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002702 // Those act as if they were invisible, so we don't need to flag them.
2703 // We do want to potentially flag touchable windows even if they have 0
2704 // opacity, since they can consume touches and alter the effects of the
2705 // user interaction (eg. apps that rely on
2706 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2707 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2708 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002709 } else if (info->ownerUid == otherInfo->ownerUid) {
2710 // If ownerUid is the same we don't generate occlusion events as there
2711 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002712 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002713 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002714 return false;
2715 } else if (otherInfo->displayId != info->displayId) {
2716 return false;
2717 }
2718 return true;
2719}
2720
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002721/**
2722 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2723 * untrusted, one should check:
2724 *
2725 * 1. If result.hasBlockingOcclusion is true.
2726 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2727 * BLOCK_UNTRUSTED.
2728 *
2729 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2730 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2731 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2732 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2733 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2734 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2735 *
2736 * If neither of those is true, then it means the touch can be allowed.
2737 */
2738InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002739 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2740 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002741 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002742 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002743 TouchOcclusionInfo info;
2744 info.hasBlockingOcclusion = false;
2745 info.obscuringOpacity = 0;
2746 info.obscuringUid = -1;
2747 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002748 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002749 if (windowHandle == otherHandle) {
2750 break; // All future windows are below us. Exit early.
2751 }
chaviw98318de2021-05-19 16:45:23 -05002752 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002753 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2754 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002755 if (DEBUG_TOUCH_OCCLUSION) {
2756 info.debugInfo.push_back(
2757 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2758 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002759 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2760 // we perform the checks below to see if the touch can be propagated or not based on the
2761 // window's touch occlusion mode
2762 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2763 info.hasBlockingOcclusion = true;
2764 info.obscuringUid = otherInfo->ownerUid;
2765 info.obscuringPackage = otherInfo->packageName;
2766 break;
2767 }
2768 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2769 uint32_t uid = otherInfo->ownerUid;
2770 float opacity =
2771 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2772 // Given windows A and B:
2773 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2774 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2775 opacityByUid[uid] = opacity;
2776 if (opacity > info.obscuringOpacity) {
2777 info.obscuringOpacity = opacity;
2778 info.obscuringUid = uid;
2779 info.obscuringPackage = otherInfo->packageName;
2780 }
2781 }
2782 }
2783 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002784 if (DEBUG_TOUCH_OCCLUSION) {
2785 info.debugInfo.push_back(
2786 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2787 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002788 return info;
2789}
2790
chaviw98318de2021-05-19 16:45:23 -05002791std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002792 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002793 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2794 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2795 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2796 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002797 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2798 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2799 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2800 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2801 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002802 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002803 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002804}
2805
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002806bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2807 if (occlusionInfo.hasBlockingOcclusion) {
2808 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2809 occlusionInfo.obscuringUid);
2810 return false;
2811 }
2812 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2813 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2814 "%.2f, maximum allowed = %.2f)",
2815 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2816 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2817 return false;
2818 }
2819 return true;
2820}
2821
chaviw98318de2021-05-19 16:45:23 -05002822bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002823 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002825 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2826 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002827 if (windowHandle == otherHandle) {
2828 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002829 }
chaviw98318de2021-05-19 16:45:23 -05002830 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002831 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002832 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002833 return true;
2834 }
2835 }
2836 return false;
2837}
2838
chaviw98318de2021-05-19 16:45:23 -05002839bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002840 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002841 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2842 const WindowInfo* windowInfo = windowHandle->getInfo();
2843 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002844 if (windowHandle == otherHandle) {
2845 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002846 }
chaviw98318de2021-05-19 16:45:23 -05002847 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002848 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002849 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002850 return true;
2851 }
2852 }
2853 return false;
2854}
2855
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002856std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002857 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002858 if (applicationHandle != nullptr) {
2859 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002860 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002861 } else {
2862 return applicationHandle->getName();
2863 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002864 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002865 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002867 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868 }
2869}
2870
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002871void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002872 if (!isUserActivityEvent(eventEntry)) {
2873 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002874 return;
2875 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002876 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002877 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002878 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002879 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002880 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002881 if (DEBUG_DISPATCH_CYCLE) {
2882 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2883 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002884 return;
2885 }
2886 }
2887
2888 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002889 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002890 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002891 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2892 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002893 return;
2894 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002895
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002896 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002897 eventType = USER_ACTIVITY_EVENT_TOUCH;
2898 }
2899 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002900 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002901 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002902 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2903 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002904 return;
2905 }
2906 eventType = USER_ACTIVITY_EVENT_BUTTON;
2907 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002908 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002909 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002910 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002911 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002912 break;
2913 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914 }
2915
Prabir Pradhancef936d2021-07-21 16:17:52 +00002916 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2917 REQUIRES(mLock) {
2918 scoped_unlock unlock(mLock);
2919 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2920 };
2921 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922}
2923
2924void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002925 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002926 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002927 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002928 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002929 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002930 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002931 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002932 ATRACE_NAME(message.c_str());
2933 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002934 if (DEBUG_DISPATCH_CYCLE) {
2935 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2936 "globalScaleFactor=%f, pointerIds=0x%x %s",
2937 connection->getInputChannelName().c_str(), inputTarget.flags,
2938 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2939 inputTarget.getPointerInfoString().c_str());
2940 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002941
2942 // Skip this event if the connection status is not normal.
2943 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002944 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002945 if (DEBUG_DISPATCH_CYCLE) {
2946 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002947 connection->getInputChannelName().c_str(),
2948 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002950 return;
2951 }
2952
2953 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002954 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2955 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2956 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002957 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002958
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002959 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002960 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002961 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
2962 "Splitting motion events requires a down time to be set for the "
2963 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002964 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002965 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
2966 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002967 if (!splitMotionEntry) {
2968 return; // split event was dropped
2969 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002970 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2971 std::string reason = std::string("reason=pointer cancel on split window");
2972 android_log_event_list(LOGTAG_INPUT_CANCEL)
2973 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2974 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002975 if (DEBUG_FOCUS) {
2976 ALOGD("channel '%s' ~ Split motion event.",
2977 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002978 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002979 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002980 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2981 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002982 return;
2983 }
2984 }
2985
2986 // Not splitting. Enqueue dispatch entries for the event as is.
2987 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2988}
2989
2990void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002991 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002992 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002993 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002994 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002995 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002996 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002997 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002998 ATRACE_NAME(message.c_str());
2999 }
3000
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003001 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003002
3003 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003004 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003005 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003006 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003007 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003008 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003009 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003010 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003011 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003012 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003013 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003014 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003015 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003016
3017 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003018 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003019 startDispatchCycleLocked(currentTime, connection);
3020 }
3021}
3022
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003023void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003024 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003025 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003026 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003027 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003028 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3029 connection->getInputChannelName().c_str(),
3030 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003031 ATRACE_NAME(message.c_str());
3032 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003033 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003034 if (!(inputTargetFlags & dispatchMode)) {
3035 return;
3036 }
3037 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
3038
3039 // This is a new event.
3040 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003041 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003042 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003043
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003044 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3045 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003046 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003048 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003049 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003050 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003051 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003052 dispatchEntry->resolvedAction = keyEntry.action;
3053 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003055 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3056 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003057 if (DEBUG_DISPATCH_CYCLE) {
3058 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3059 "event",
3060 connection->getInputChannelName().c_str());
3061 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003062 return; // skip the inconsistent event
3063 }
3064 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003065 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003067 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003068 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003069 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3070 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3071 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3072 static_cast<int32_t>(IdGenerator::Source::OTHER);
3073 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003074 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3075 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3076 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3077 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3078 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3079 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3080 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3081 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3082 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3083 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3084 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003085 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003086 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003087 }
3088 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003089 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3090 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003091 if (DEBUG_DISPATCH_CYCLE) {
3092 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3093 "enter event",
3094 connection->getInputChannelName().c_str());
3095 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003096 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3097 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003098 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3099 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003101 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003102 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3103 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3104 }
3105 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3106 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3107 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003108
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003109 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3110 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003111 if (DEBUG_DISPATCH_CYCLE) {
3112 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3113 "event",
3114 connection->getInputChannelName().c_str());
3115 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003116 return; // skip the inconsistent event
3117 }
3118
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003119 dispatchEntry->resolvedEventId =
3120 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3121 ? mIdGenerator.nextId()
3122 : motionEntry.id;
3123 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3124 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3125 ") to MotionEvent(id=0x%" PRIx32 ").",
3126 motionEntry.id, dispatchEntry->resolvedEventId);
3127 ATRACE_NAME(message.c_str());
3128 }
3129
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003130 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3131 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3132 // Skip reporting pointer down outside focus to the policy.
3133 break;
3134 }
3135
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003136 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003137 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003138
3139 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003140 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003141 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003142 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003143 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3144 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003145 break;
3146 }
Chris Yef59a2f42020-10-16 12:55:26 -07003147 case EventEntry::Type::SENSOR: {
3148 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3149 break;
3150 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003151 case EventEntry::Type::CONFIGURATION_CHANGED:
3152 case EventEntry::Type::DEVICE_RESET: {
3153 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003154 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003155 break;
3156 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 }
3158
3159 // Remember that we are waiting for this dispatch to complete.
3160 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003161 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162 }
3163
3164 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003165 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003166 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003167}
3168
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003169/**
3170 * This function is purely for debugging. It helps us understand where the user interaction
3171 * was taking place. For example, if user is touching launcher, we will see a log that user
3172 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3173 * We will see both launcher and wallpaper in that list.
3174 * Once the interaction with a particular set of connections starts, no new logs will be printed
3175 * until the set of interacted connections changes.
3176 *
3177 * The following items are skipped, to reduce the logspam:
3178 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3179 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3180 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3181 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3182 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003183 */
3184void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3185 const std::vector<InputTarget>& targets) {
3186 // Skip ACTION_UP events, and all events other than keys and motions
3187 if (entry.type == EventEntry::Type::KEY) {
3188 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3189 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3190 return;
3191 }
3192 } else if (entry.type == EventEntry::Type::MOTION) {
3193 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3194 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3195 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3196 return;
3197 }
3198 } else {
3199 return; // Not a key or a motion
3200 }
3201
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003202 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003203 std::vector<sp<Connection>> newConnections;
3204 for (const InputTarget& target : targets) {
3205 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3206 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3207 continue; // Skip windows that receive ACTION_OUTSIDE
3208 }
3209
3210 sp<IBinder> token = target.inputChannel->getConnectionToken();
3211 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003212 if (connection == nullptr) {
3213 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003214 }
3215 newConnectionTokens.insert(std::move(token));
3216 newConnections.emplace_back(connection);
3217 }
3218 if (newConnectionTokens == mInteractionConnectionTokens) {
3219 return; // no change
3220 }
3221 mInteractionConnectionTokens = newConnectionTokens;
3222
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003223 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003224 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003225 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003226 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003227 std::string message = "Interaction with: " + targetList;
3228 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003229 message += "<none>";
3230 }
3231 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3232}
3233
chaviwfd6d3512019-03-25 13:23:49 -07003234void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003235 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003236 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003237 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3238 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003239 return;
3240 }
3241
Vishnu Nairc519ff72021-01-21 08:23:08 -08003242 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003243 if (focusedToken == token) {
3244 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003245 return;
3246 }
3247
Prabir Pradhancef936d2021-07-21 16:17:52 +00003248 auto command = [this, token]() REQUIRES(mLock) {
3249 scoped_unlock unlock(mLock);
3250 mPolicy->onPointerDownOutsideFocus(token);
3251 };
3252 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253}
3254
3255void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003256 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003257 if (ATRACE_ENABLED()) {
3258 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003259 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003260 ATRACE_NAME(message.c_str());
3261 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003262 if (DEBUG_DISPATCH_CYCLE) {
3263 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3264 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003266 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003267 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003268 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003269 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003270 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271
3272 // Publish the event.
3273 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003274 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3275 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003276 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003277 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3278 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003279
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003280 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003281 status = connection->inputPublisher
3282 .publishKeyEvent(dispatchEntry->seq,
3283 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3284 keyEntry.source, keyEntry.displayId,
3285 std::move(hmac), dispatchEntry->resolvedAction,
3286 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3287 keyEntry.scanCode, keyEntry.metaState,
3288 keyEntry.repeatCount, keyEntry.downTime,
3289 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003290 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291 }
3292
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003293 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003294 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003296 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003297 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003298
chaviw82357092020-01-28 13:13:06 -08003299 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003300 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003301 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3302 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003303 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003304 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3305 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003306 // Don't apply window scale here since we don't want scale to affect raw
3307 // coordinates. The scale will be sent back to the client and applied
3308 // later when requesting relative coordinates.
3309 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3310 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003311 }
3312 usingCoords = scaledCoords;
3313 }
3314 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003315 // We don't want the dispatch target to know.
3316 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003317 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 scaledCoords[i].clear();
3319 }
3320 usingCoords = scaledCoords;
3321 }
3322 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003323
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003324 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003325
3326 // Publish the motion event.
3327 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003328 .publishMotionEvent(dispatchEntry->seq,
3329 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003330 motionEntry.deviceId, motionEntry.source,
3331 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003332 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003333 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003334 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003335 motionEntry.edgeFlags, motionEntry.metaState,
3336 motionEntry.buttonState,
3337 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003338 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003339 motionEntry.xPrecision, motionEntry.yPrecision,
3340 motionEntry.xCursorPosition,
3341 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003342 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003343 motionEntry.downTime, motionEntry.eventTime,
3344 motionEntry.pointerCount,
3345 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003346 break;
3347 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003348
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003349 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003350 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003351 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003352 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003353 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003354 break;
3355 }
3356
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003357 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3358 const TouchModeEntry& touchModeEntry =
3359 static_cast<const TouchModeEntry&>(eventEntry);
3360 status = connection->inputPublisher
3361 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3362 touchModeEntry.inTouchMode);
3363
3364 break;
3365 }
3366
Prabir Pradhan99987712020-11-10 18:43:05 -08003367 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3368 const auto& captureEntry =
3369 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3370 status = connection->inputPublisher
3371 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003372 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003373 break;
3374 }
3375
arthurhungb89ccb02020-12-30 16:19:01 +08003376 case EventEntry::Type::DRAG: {
3377 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3378 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3379 dragEntry.id, dragEntry.x,
3380 dragEntry.y,
3381 dragEntry.isExiting);
3382 break;
3383 }
3384
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003385 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003386 case EventEntry::Type::DEVICE_RESET:
3387 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003388 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003389 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003390 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392 }
3393
3394 // Check the result.
3395 if (status) {
3396 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003397 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003398 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003399 "This is unexpected because the wait queue is empty, so the pipe "
3400 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003401 "event to it, status=%s(%d)",
3402 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3403 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3405 } else {
3406 // Pipe is full and we are waiting for the app to finish process some events
3407 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003408 if (DEBUG_DISPATCH_CYCLE) {
3409 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3410 "waiting for the application to catch up",
3411 connection->getInputChannelName().c_str());
3412 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413 }
3414 } else {
3415 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003416 "status=%s(%d)",
3417 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3418 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3420 }
3421 return;
3422 }
3423
3424 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003425 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3426 connection->outboundQueue.end(),
3427 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003428 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003429 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003430 if (connection->responsive) {
3431 mAnrTracker.insert(dispatchEntry->timeoutTime,
3432 connection->inputChannel->getConnectionToken());
3433 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003434 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435 }
3436}
3437
chaviw09c8d2d2020-08-24 15:48:26 -07003438std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3439 size_t size;
3440 switch (event.type) {
3441 case VerifiedInputEvent::Type::KEY: {
3442 size = sizeof(VerifiedKeyEvent);
3443 break;
3444 }
3445 case VerifiedInputEvent::Type::MOTION: {
3446 size = sizeof(VerifiedMotionEvent);
3447 break;
3448 }
3449 }
3450 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3451 return mHmacKeyManager.sign(start, size);
3452}
3453
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003454const std::array<uint8_t, 32> InputDispatcher::getSignature(
3455 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003456 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3457 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003458 // Only sign events up and down events as the purely move events
3459 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003460 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003461 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003462
3463 VerifiedMotionEvent verifiedEvent =
3464 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3465 verifiedEvent.actionMasked = actionMasked;
3466 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3467 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003468}
3469
3470const std::array<uint8_t, 32> InputDispatcher::getSignature(
3471 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3472 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3473 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3474 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003475 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003476}
3477
Michael Wrightd02c5b62014-02-10 15:10:22 -08003478void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003479 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003480 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003481 if (DEBUG_DISPATCH_CYCLE) {
3482 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3483 connection->getInputChannelName().c_str(), seq, toString(handled));
3484 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003485
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003486 if (connection->status == Connection::Status::BROKEN ||
3487 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003488 return;
3489 }
3490
3491 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003492 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3493 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3494 };
3495 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496}
3497
3498void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003499 const sp<Connection>& connection,
3500 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003501 if (DEBUG_DISPATCH_CYCLE) {
3502 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3503 connection->getInputChannelName().c_str(), toString(notify));
3504 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505
3506 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003507 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003508 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003509 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003510 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511
3512 // The connection appears to be unrecoverably broken.
3513 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003514 if (connection->status == Connection::Status::NORMAL) {
3515 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516
3517 if (notify) {
3518 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003519 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3520 connection->getInputChannelName().c_str());
3521
3522 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003523 scoped_unlock unlock(mLock);
3524 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3525 };
3526 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 }
3528 }
3529}
3530
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003531void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3532 while (!queue.empty()) {
3533 DispatchEntry* dispatchEntry = queue.front();
3534 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003535 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003536 }
3537}
3538
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003539void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003541 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542 }
3543 delete dispatchEntry;
3544}
3545
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003546int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3547 std::scoped_lock _l(mLock);
3548 sp<Connection> connection = getConnectionLocked(connectionToken);
3549 if (connection == nullptr) {
3550 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3551 connectionToken.get(), events);
3552 return 0; // remove the callback
3553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003554
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003555 bool notify;
3556 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3557 if (!(events & ALOOPER_EVENT_INPUT)) {
3558 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3559 "events=0x%x",
3560 connection->getInputChannelName().c_str(), events);
3561 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003562 }
3563
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003564 nsecs_t currentTime = now();
3565 bool gotOne = false;
3566 status_t status = OK;
3567 for (;;) {
3568 Result<InputPublisher::ConsumerResponse> result =
3569 connection->inputPublisher.receiveConsumerResponse();
3570 if (!result.ok()) {
3571 status = result.error().code();
3572 break;
3573 }
3574
3575 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3576 const InputPublisher::Finished& finish =
3577 std::get<InputPublisher::Finished>(*result);
3578 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3579 finish.consumeTime);
3580 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003581 if (shouldReportMetricsForConnection(*connection)) {
3582 const InputPublisher::Timeline& timeline =
3583 std::get<InputPublisher::Timeline>(*result);
3584 mLatencyTracker
3585 .trackGraphicsLatency(timeline.inputEventId,
3586 connection->inputChannel->getConnectionToken(),
3587 std::move(timeline.graphicsTimeline));
3588 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003589 }
3590 gotOne = true;
3591 }
3592 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003593 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003594 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595 return 1;
3596 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 }
3598
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003599 notify = status != DEAD_OBJECT || !connection->monitor;
3600 if (notify) {
3601 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3602 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3603 status);
3604 }
3605 } else {
3606 // Monitor channels are never explicitly unregistered.
3607 // We do it automatically when the remote endpoint is closed so don't warn about them.
3608 const bool stillHaveWindowHandle =
3609 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3610 notify = !connection->monitor && stillHaveWindowHandle;
3611 if (notify) {
3612 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3613 connection->getInputChannelName().c_str(), events);
3614 }
3615 }
3616
3617 // Remove the channel.
3618 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3619 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620}
3621
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003622void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003624 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003625 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 }
3627}
3628
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003629void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003630 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003631 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003632 for (const Monitor& monitor : monitors) {
3633 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003634 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003635 }
3636}
3637
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003639 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003640 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003641 if (connection == nullptr) {
3642 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003644
3645 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646}
3647
3648void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3649 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003650 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003651 return;
3652 }
3653
3654 nsecs_t currentTime = now();
3655
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003656 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003657 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003659 if (cancelationEvents.empty()) {
3660 return;
3661 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003662 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3663 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3664 "with reality: %s, mode=%d.",
3665 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3666 options.mode);
3667 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003668
Arthur Hungb3307ee2021-10-14 10:57:37 +00003669 std::string reason = std::string("reason=").append(options.reason);
3670 android_log_event_list(LOGTAG_INPUT_CANCEL)
3671 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3672
Svet Ganov5d3bc372020-01-26 23:11:07 -08003673 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003674 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003675 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3676 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003677 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003678 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003679 target.globalScaleFactor = windowInfo->globalScaleFactor;
3680 }
3681 target.inputChannel = connection->inputChannel;
3682 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3683
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003684 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003685 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003686 switch (cancelationEventEntry->type) {
3687 case EventEntry::Type::KEY: {
3688 logOutboundKeyDetails("cancel - ",
3689 static_cast<const KeyEntry&>(*cancelationEventEntry));
3690 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003692 case EventEntry::Type::MOTION: {
3693 logOutboundMotionDetails("cancel - ",
3694 static_cast<const MotionEntry&>(*cancelationEventEntry));
3695 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003696 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003697 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003698 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003699 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3700 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003701 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003702 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003703 break;
3704 }
3705 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003706 case EventEntry::Type::DEVICE_RESET:
3707 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003708 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003709 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003710 break;
3711 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003712 }
3713
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003714 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3715 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003717
3718 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003719}
3720
Svet Ganov5d3bc372020-01-26 23:11:07 -08003721void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003722 const nsecs_t downTime, const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003723 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003724 return;
3725 }
3726
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003727 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003728 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003729
3730 if (downEvents.empty()) {
3731 return;
3732 }
3733
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003734 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003735 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3736 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003737 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003738
3739 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003740 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003741 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3742 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003743 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003744 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003745 target.globalScaleFactor = windowInfo->globalScaleFactor;
3746 }
3747 target.inputChannel = connection->inputChannel;
3748 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3749
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003750 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003751 switch (downEventEntry->type) {
3752 case EventEntry::Type::MOTION: {
3753 logOutboundMotionDetails("down - ",
3754 static_cast<const MotionEntry&>(*downEventEntry));
3755 break;
3756 }
3757
3758 case EventEntry::Type::KEY:
3759 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003760 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003761 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003762 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003763 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003764 case EventEntry::Type::SENSOR:
3765 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003766 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003767 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003768 break;
3769 }
3770 }
3771
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003772 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3773 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003774 }
3775
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003776 startDispatchCycleLocked(downTime, connection);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003777}
3778
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003779std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003780 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781 ALOG_ASSERT(pointerIds.value != 0);
3782
3783 uint32_t splitPointerIndexMap[MAX_POINTERS];
3784 PointerProperties splitPointerProperties[MAX_POINTERS];
3785 PointerCoords splitPointerCoords[MAX_POINTERS];
3786
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003787 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788 uint32_t splitPointerCount = 0;
3789
3790 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003791 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003793 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794 uint32_t pointerId = uint32_t(pointerProperties.id);
3795 if (pointerIds.hasBit(pointerId)) {
3796 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3797 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3798 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003799 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003800 splitPointerCount += 1;
3801 }
3802 }
3803
3804 if (splitPointerCount != pointerIds.count()) {
3805 // This is bad. We are missing some of the pointers that we expected to deliver.
3806 // Most likely this indicates that we received an ACTION_MOVE events that has
3807 // different pointer ids than we expected based on the previous ACTION_DOWN
3808 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3809 // in this way.
3810 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003811 "we expected there to be %d pointers. This probably means we received "
3812 "a broken sequence of pointer ids from the input device.",
3813 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003814 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 }
3816
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003817 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003819 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3820 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003821 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3822 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003823 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824 uint32_t pointerId = uint32_t(pointerProperties.id);
3825 if (pointerIds.hasBit(pointerId)) {
3826 if (pointerIds.count() == 1) {
3827 // The first/last pointer went down/up.
3828 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003829 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003830 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3831 ? AMOTION_EVENT_ACTION_CANCEL
3832 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833 } else {
3834 // A secondary pointer went down/up.
3835 uint32_t splitPointerIndex = 0;
3836 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3837 splitPointerIndex += 1;
3838 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003839 action = maskedAction |
3840 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003841 }
3842 } else {
3843 // An unrelated pointer changed.
3844 action = AMOTION_EVENT_ACTION_MOVE;
3845 }
3846 }
3847
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003848 if (action == AMOTION_EVENT_ACTION_DOWN) {
3849 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3850 "Split motion event has mismatching downTime and eventTime for "
3851 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3852 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3853 }
3854
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003855 int32_t newId = mIdGenerator.nextId();
3856 if (ATRACE_ENABLED()) {
3857 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3858 ") to MotionEvent(id=0x%" PRIx32 ").",
3859 originalMotionEntry.id, newId);
3860 ATRACE_NAME(message.c_str());
3861 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003862 std::unique_ptr<MotionEntry> splitMotionEntry =
3863 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3864 originalMotionEntry.deviceId, originalMotionEntry.source,
3865 originalMotionEntry.displayId,
3866 originalMotionEntry.policyFlags, action,
3867 originalMotionEntry.actionButton,
3868 originalMotionEntry.flags, originalMotionEntry.metaState,
3869 originalMotionEntry.buttonState,
3870 originalMotionEntry.classification,
3871 originalMotionEntry.edgeFlags,
3872 originalMotionEntry.xPrecision,
3873 originalMotionEntry.yPrecision,
3874 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003875 originalMotionEntry.yCursorPosition, splitDownTime,
3876 splitPointerCount, splitPointerProperties,
3877 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003879 if (originalMotionEntry.injectionState) {
3880 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881 splitMotionEntry->injectionState->refCount += 1;
3882 }
3883
3884 return splitMotionEntry;
3885}
3886
3887void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003888 if (DEBUG_INBOUND_EVENT_DETAILS) {
3889 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891
Antonio Kantekf16f2832021-09-28 04:39:20 +00003892 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003894 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003895
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003896 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3897 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3898 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899 } // release lock
3900
3901 if (needWake) {
3902 mLooper->wake();
3903 }
3904}
3905
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003906/**
3907 * If one of the meta shortcuts is detected, process them here:
3908 * Meta + Backspace -> generate BACK
3909 * Meta + Enter -> generate HOME
3910 * This will potentially overwrite keyCode and metaState.
3911 */
3912void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003913 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003914 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3915 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3916 if (keyCode == AKEYCODE_DEL) {
3917 newKeyCode = AKEYCODE_BACK;
3918 } else if (keyCode == AKEYCODE_ENTER) {
3919 newKeyCode = AKEYCODE_HOME;
3920 }
3921 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003922 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003923 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003924 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003925 keyCode = newKeyCode;
3926 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3927 }
3928 } else if (action == AKEY_EVENT_ACTION_UP) {
3929 // In order to maintain a consistent stream of up and down events, check to see if the key
3930 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3931 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003932 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003933 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003934 auto replacementIt = mReplacedKeys.find(replacement);
3935 if (replacementIt != mReplacedKeys.end()) {
3936 keyCode = replacementIt->second;
3937 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003938 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3939 }
3940 }
3941}
3942
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003944 if (DEBUG_INBOUND_EVENT_DETAILS) {
3945 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3946 "policyFlags=0x%x, action=0x%x, "
3947 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3948 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3949 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3950 args->downTime);
3951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952 if (!validateKeyEvent(args->action)) {
3953 return;
3954 }
3955
3956 uint32_t policyFlags = args->policyFlags;
3957 int32_t flags = args->flags;
3958 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003959 // InputDispatcher tracks and generates key repeats on behalf of
3960 // whatever notifies it, so repeatCount should always be set to 0
3961 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3963 policyFlags |= POLICY_FLAG_VIRTUAL;
3964 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3965 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966 if (policyFlags & POLICY_FLAG_FUNCTION) {
3967 metaState |= AMETA_FUNCTION_ON;
3968 }
3969
3970 policyFlags |= POLICY_FLAG_TRUSTED;
3971
Michael Wright78f24442014-08-06 15:55:28 -07003972 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003973 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003974
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003976 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003977 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3978 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003979
Michael Wright2b3c3302018-03-02 17:19:13 +00003980 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003982 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3983 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003984 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003985 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986
Antonio Kantekf16f2832021-09-28 04:39:20 +00003987 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988 { // acquire lock
3989 mLock.lock();
3990
3991 if (shouldSendKeyToInputFilterLocked(args)) {
3992 mLock.unlock();
3993
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003994 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3996 return; // event was consumed by the filter
3997 }
3998
3999 mLock.lock();
4000 }
4001
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004002 std::unique_ptr<KeyEntry> newEntry =
4003 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4004 args->displayId, policyFlags, args->action, flags,
4005 keyCode, args->scanCode, metaState, repeatCount,
4006 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004007
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004008 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009 mLock.unlock();
4010 } // release lock
4011
4012 if (needWake) {
4013 mLooper->wake();
4014 }
4015}
4016
4017bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4018 return mInputFilterEnabled;
4019}
4020
4021void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004022 if (DEBUG_INBOUND_EVENT_DETAILS) {
4023 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4024 "displayId=%" PRId32 ", policyFlags=0x%x, "
4025 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
4026 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4027 "yCursorPosition=%f, downTime=%" PRId64,
4028 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
4029 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
4030 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
4031 args->xCursorPosition, args->yCursorPosition, args->downTime);
4032 for (uint32_t i = 0; i < args->pointerCount; i++) {
4033 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4034 "x=%f, y=%f, pressure=%f, size=%f, "
4035 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4036 "orientation=%f",
4037 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4038 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4039 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4040 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4041 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4042 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4043 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4044 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4045 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4046 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4047 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004048 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004049 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4050 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051 return;
4052 }
4053
4054 uint32_t policyFlags = args->policyFlags;
4055 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004056
4057 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004058 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004059 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4060 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004061 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063
Antonio Kantekf16f2832021-09-28 04:39:20 +00004064 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065 { // acquire lock
4066 mLock.lock();
4067
4068 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004069 ui::Transform displayTransform;
4070 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4071 displayTransform = it->second.transform;
4072 }
4073
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074 mLock.unlock();
4075
4076 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004077 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4078 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004079 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004080 displayTransform, args->xPrecision, args->yPrecision,
4081 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004082 args->downTime, args->eventTime, args->pointerCount,
4083 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004084
4085 policyFlags |= POLICY_FLAG_FILTERED;
4086 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4087 return; // event was consumed by the filter
4088 }
4089
4090 mLock.lock();
4091 }
4092
4093 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004094 std::unique_ptr<MotionEntry> newEntry =
4095 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4096 args->source, args->displayId, policyFlags,
4097 args->action, args->actionButton, args->flags,
4098 args->metaState, args->buttonState,
4099 args->classification, args->edgeFlags,
4100 args->xPrecision, args->yPrecision,
4101 args->xCursorPosition, args->yCursorPosition,
4102 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004103 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004104
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004105 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4106 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4107 !mInputFilterEnabled) {
4108 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4109 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4110 }
4111
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004112 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113 mLock.unlock();
4114 } // release lock
4115
4116 if (needWake) {
4117 mLooper->wake();
4118 }
4119}
4120
Chris Yef59a2f42020-10-16 12:55:26 -07004121void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004122 if (DEBUG_INBOUND_EVENT_DETAILS) {
4123 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4124 " sensorType=%s",
4125 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004126 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004127 }
Chris Yef59a2f42020-10-16 12:55:26 -07004128
Antonio Kantekf16f2832021-09-28 04:39:20 +00004129 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004130 { // acquire lock
4131 mLock.lock();
4132
4133 // Just enqueue a new sensor event.
4134 std::unique_ptr<SensorEntry> newEntry =
4135 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4136 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4137 args->sensorType, args->accuracy,
4138 args->accuracyChanged, args->values);
4139
4140 needWake = enqueueInboundEventLocked(std::move(newEntry));
4141 mLock.unlock();
4142 } // release lock
4143
4144 if (needWake) {
4145 mLooper->wake();
4146 }
4147}
4148
Chris Yefb552902021-02-03 17:18:37 -08004149void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004150 if (DEBUG_INBOUND_EVENT_DETAILS) {
4151 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4152 args->deviceId, args->isOn);
4153 }
Chris Yefb552902021-02-03 17:18:37 -08004154 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4155}
4156
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004158 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159}
4160
4161void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004162 if (DEBUG_INBOUND_EVENT_DETAILS) {
4163 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4164 "switchMask=0x%08x",
4165 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4166 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167
4168 uint32_t policyFlags = args->policyFlags;
4169 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004170 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171}
4172
4173void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004174 if (DEBUG_INBOUND_EVENT_DETAILS) {
4175 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4176 args->deviceId);
4177 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178
Antonio Kantekf16f2832021-09-28 04:39:20 +00004179 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004181 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004183 std::unique_ptr<DeviceResetEntry> newEntry =
4184 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4185 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 } // release lock
4187
4188 if (needWake) {
4189 mLooper->wake();
4190 }
4191}
4192
Prabir Pradhan7e186182020-11-10 13:56:45 -08004193void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004194 if (DEBUG_INBOUND_EVENT_DETAILS) {
4195 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004196 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004197 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004198
Antonio Kantekf16f2832021-09-28 04:39:20 +00004199 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004200 { // acquire lock
4201 std::scoped_lock _l(mLock);
4202 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004203 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004204 needWake = enqueueInboundEventLocked(std::move(entry));
4205 } // release lock
4206
4207 if (needWake) {
4208 mLooper->wake();
4209 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004210}
4211
Prabir Pradhan5735a322022-04-11 17:23:34 +00004212InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4213 std::optional<int32_t> targetUid,
4214 InputEventInjectionSync syncMode,
4215 std::chrono::milliseconds timeout,
4216 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004217 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004218 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4219 "policyFlags=0x%08x",
4220 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4221 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004222 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004223 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224
Prabir Pradhan5735a322022-04-11 17:23:34 +00004225 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004227 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004228 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4229 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4230 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4231 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4232 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004233 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004234 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004235 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004236 }
4237
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004238 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004239 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004240 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004241 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4242 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004243 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004244 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004245 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004246
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004247 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004248 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4249 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4250 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004251 int32_t keyCode = incomingKey.getKeyCode();
4252 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004253 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004254 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004255 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004256 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004257 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4258 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4259 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004261 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4262 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004263 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004264
4265 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4266 android::base::Timer t;
4267 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4268 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4269 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4270 std::to_string(t.duration().count()).c_str());
4271 }
4272 }
4273
4274 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004275 std::unique_ptr<KeyEntry> injectedEntry =
4276 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004277 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004278 incomingKey.getDisplayId(), policyFlags, action,
4279 flags, keyCode, incomingKey.getScanCode(), metaState,
4280 incomingKey.getRepeatCount(),
4281 incomingKey.getDownTime());
4282 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004283 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284 }
4285
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004286 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004287 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004288 const int32_t action = motionEvent.getAction();
4289 const bool isPointerEvent =
4290 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4291 // If a pointer event has no displayId specified, inject it to the default display.
4292 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4293 ? ADISPLAY_ID_DEFAULT
4294 : event->getDisplayId();
4295 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004296 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004297 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004298 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004299 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004300 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004301 }
4302
4303 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004304 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004305 android::base::Timer t;
4306 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4307 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4308 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4309 std::to_string(t.duration().count()).c_str());
4310 }
4311 }
4312
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004313 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4314 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4315 }
4316
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004317 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004318 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4319 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004320 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004321 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4322 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004323 displayId, policyFlags, action, actionButton,
4324 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004325 motionEvent.getButtonState(),
4326 motionEvent.getClassification(),
4327 motionEvent.getEdgeFlags(),
4328 motionEvent.getXPrecision(),
4329 motionEvent.getYPrecision(),
4330 motionEvent.getRawXCursorPosition(),
4331 motionEvent.getRawYCursorPosition(),
4332 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004333 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004334 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004335 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004336 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004337 sampleEventTimes += 1;
4338 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004339 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004340 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4341 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004342 displayId, policyFlags, action, actionButton,
4343 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004344 motionEvent.getButtonState(),
4345 motionEvent.getClassification(),
4346 motionEvent.getEdgeFlags(),
4347 motionEvent.getXPrecision(),
4348 motionEvent.getYPrecision(),
4349 motionEvent.getRawXCursorPosition(),
4350 motionEvent.getRawYCursorPosition(),
4351 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004352 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004353 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004354 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4355 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004356 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004357 }
4358 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004361 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004362 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004363 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364 }
4365
Prabir Pradhan5735a322022-04-11 17:23:34 +00004366 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004367 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368 injectionState->injectionIsAsync = true;
4369 }
4370
4371 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004372 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373
4374 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004375 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004376 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004377 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378 }
4379
4380 mLock.unlock();
4381
4382 if (needWake) {
4383 mLooper->wake();
4384 }
4385
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004386 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004388 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004390 if (syncMode == InputEventInjectionSync::NONE) {
4391 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392 } else {
4393 for (;;) {
4394 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004395 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396 break;
4397 }
4398
4399 nsecs_t remainingTimeout = endTime - now();
4400 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004401 if (DEBUG_INJECTION) {
4402 ALOGD("injectInputEvent - Timed out waiting for injection result "
4403 "to become available.");
4404 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004405 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004406 break;
4407 }
4408
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004409 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004410 }
4411
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004412 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4413 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004415 if (DEBUG_INJECTION) {
4416 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4417 injectionState->pendingForegroundDispatches);
4418 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004419 nsecs_t remainingTimeout = endTime - now();
4420 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004421 if (DEBUG_INJECTION) {
4422 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4423 "dispatches to finish.");
4424 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004425 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004426 break;
4427 }
4428
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004429 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004430 }
4431 }
4432 }
4433
4434 injectionState->release();
4435 } // release lock
4436
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004437 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004438 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004439 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004440
4441 return injectionResult;
4442}
4443
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004444std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004445 std::array<uint8_t, 32> calculatedHmac;
4446 std::unique_ptr<VerifiedInputEvent> result;
4447 switch (event.getType()) {
4448 case AINPUT_EVENT_TYPE_KEY: {
4449 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4450 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4451 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004452 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004453 break;
4454 }
4455 case AINPUT_EVENT_TYPE_MOTION: {
4456 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4457 VerifiedMotionEvent verifiedMotionEvent =
4458 verifiedMotionEventFromMotionEvent(motionEvent);
4459 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004460 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004461 break;
4462 }
4463 default: {
4464 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4465 return nullptr;
4466 }
4467 }
4468 if (calculatedHmac == INVALID_HMAC) {
4469 return nullptr;
4470 }
4471 if (calculatedHmac != event.getHmac()) {
4472 return nullptr;
4473 }
4474 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004475}
4476
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004477void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004478 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004479 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004480 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004481 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004482 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004485 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004486 // Log the outcome since the injector did not wait for the injection result.
4487 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004488 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004489 ALOGV("Asynchronous input event injection succeeded.");
4490 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004491 case InputEventInjectionResult::TARGET_MISMATCH:
4492 ALOGV("Asynchronous input event injection target mismatch.");
4493 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004494 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004495 ALOGW("Asynchronous input event injection failed.");
4496 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004497 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004498 ALOGW("Asynchronous input event injection timed out.");
4499 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004500 case InputEventInjectionResult::PENDING:
4501 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4502 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004503 }
4504 }
4505
4506 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004507 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508 }
4509}
4510
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004511void InputDispatcher::transformMotionEntryForInjectionLocked(
4512 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004513 // Input injection works in the logical display coordinate space, but the input pipeline works
4514 // display space, so we need to transform the injected events accordingly.
4515 const auto it = mDisplayInfos.find(entry.displayId);
4516 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004517 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004518
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004519 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4520 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4521 const vec2 cursor =
4522 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4523 {entry.xCursorPosition, entry.yCursorPosition});
4524 entry.xCursorPosition = cursor.x;
4525 entry.yCursorPosition = cursor.y;
4526 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004527 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004528 entry.pointerCoords[i] =
4529 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4530 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004531 }
4532}
4533
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004534void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4535 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004536 if (injectionState) {
4537 injectionState->pendingForegroundDispatches += 1;
4538 }
4539}
4540
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004541void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4542 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543 if (injectionState) {
4544 injectionState->pendingForegroundDispatches -= 1;
4545
4546 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004547 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004548 }
4549 }
4550}
4551
chaviw98318de2021-05-19 16:45:23 -05004552const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004553 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004554 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004555 auto it = mWindowHandlesByDisplay.find(displayId);
4556 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004557}
4558
chaviw98318de2021-05-19 16:45:23 -05004559sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004560 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004561 if (windowHandleToken == nullptr) {
4562 return nullptr;
4563 }
4564
Arthur Hungb92218b2018-08-14 12:00:21 +08004565 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004566 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4567 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004568 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004569 return windowHandle;
4570 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004571 }
4572 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004573 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004574}
4575
chaviw98318de2021-05-19 16:45:23 -05004576sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4577 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004578 if (windowHandleToken == nullptr) {
4579 return nullptr;
4580 }
4581
chaviw98318de2021-05-19 16:45:23 -05004582 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004583 if (windowHandle->getToken() == windowHandleToken) {
4584 return windowHandle;
4585 }
4586 }
4587 return nullptr;
4588}
4589
chaviw98318de2021-05-19 16:45:23 -05004590sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4591 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004592 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004593 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4594 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004595 if (handle->getId() == windowHandle->getId() &&
4596 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004597 if (windowHandle->getInfo()->displayId != it.first) {
4598 ALOGE("Found window %s in display %" PRId32
4599 ", but it should belong to display %" PRId32,
4600 windowHandle->getName().c_str(), it.first,
4601 windowHandle->getInfo()->displayId);
4602 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004603 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004604 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605 }
4606 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004607 return nullptr;
4608}
4609
chaviw98318de2021-05-19 16:45:23 -05004610sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004611 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4612 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004613}
4614
chaviw98318de2021-05-19 16:45:23 -05004615bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004616 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4617 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004618 windowHandle.getInfo()->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004619 if (connection != nullptr && noInputChannel) {
4620 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4621 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4622 return false;
4623 }
4624
4625 if (connection == nullptr) {
4626 if (!noInputChannel) {
4627 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4628 }
4629 return false;
4630 }
4631 if (!connection->responsive) {
4632 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4633 return false;
4634 }
4635 return true;
4636}
4637
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004638std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4639 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004640 auto connectionIt = mConnectionsByToken.find(token);
4641 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004642 return nullptr;
4643 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004644 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004645}
4646
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004647void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004648 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4649 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004650 // Remove all handles on a display if there are no windows left.
4651 mWindowHandlesByDisplay.erase(displayId);
4652 return;
4653 }
4654
4655 // Since we compare the pointer of input window handles across window updates, we need
4656 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004657 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4658 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4659 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004660 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004661 }
4662
chaviw98318de2021-05-19 16:45:23 -05004663 std::vector<sp<WindowInfoHandle>> newHandles;
4664 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004665 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004666 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004667 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004668 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004669 const bool canReceiveInput =
4670 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4671 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004672 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004673 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004674 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004675 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004676 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004677 }
4678
4679 if (info->displayId != displayId) {
4680 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4681 handle->getName().c_str(), displayId, info->displayId);
4682 continue;
4683 }
4684
Robert Carredd13602020-04-13 17:24:34 -07004685 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4686 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004687 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004688 oldHandle->updateFrom(handle);
4689 newHandles.push_back(oldHandle);
4690 } else {
4691 newHandles.push_back(handle);
4692 }
4693 }
4694
4695 // Insert or replace
4696 mWindowHandlesByDisplay[displayId] = newHandles;
4697}
4698
Arthur Hung72d8dc32020-03-28 00:48:39 +00004699void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004700 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004701 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004702 { // acquire lock
4703 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004704 for (const auto& [displayId, handles] : handlesPerDisplay) {
4705 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004706 }
4707 }
4708 // Wake up poll loop since it may need to make new input dispatching choices.
4709 mLooper->wake();
4710}
4711
Arthur Hungb92218b2018-08-14 12:00:21 +08004712/**
4713 * Called from InputManagerService, update window handle list by displayId that can receive input.
4714 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4715 * If set an empty list, remove all handles from the specific display.
4716 * For focused handle, check if need to change and send a cancel event to previous one.
4717 * For removed handle, check if need to send a cancel event if already in touch.
4718 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004719void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004720 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004721 if (DEBUG_FOCUS) {
4722 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004723 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004724 windowList += iwh->getName() + " ";
4725 }
4726 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4727 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728
Prabir Pradhand65552b2021-10-07 11:23:50 -07004729 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004730 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004731 const WindowInfo& info = *window->getInfo();
4732
4733 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004734 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004735 if (noInputWindow && window->getToken() != nullptr) {
4736 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4737 window->getName().c_str());
4738 window->releaseChannel();
4739 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004740
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004741 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004742 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4743 !info.inputConfig.test(
4744 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004745 "%s has feature SPY, but is not a trusted overlay.",
4746 window->getName().c_str());
4747
Prabir Pradhand65552b2021-10-07 11:23:50 -07004748 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004749 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4750 !info.inputConfig.test(
4751 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004752 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4753 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004754 }
4755
Arthur Hung72d8dc32020-03-28 00:48:39 +00004756 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004757 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004759 // Save the old windows' orientation by ID before it gets updated.
4760 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004761 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004762 oldWindowOrientations.emplace(handle->getId(),
4763 handle->getInfo()->transform.getOrientation());
4764 }
4765
chaviw98318de2021-05-19 16:45:23 -05004766 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004767
chaviw98318de2021-05-19 16:45:23 -05004768 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004769 if (mLastHoverWindowHandle &&
4770 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4771 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004772 mLastHoverWindowHandle = nullptr;
4773 }
4774
Vishnu Nairc519ff72021-01-21 08:23:08 -08004775 std::optional<FocusResolver::FocusChanges> changes =
4776 mFocusResolver.setInputWindows(displayId, windowHandles);
4777 if (changes) {
4778 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004779 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004780
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004781 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4782 mTouchStatesByDisplay.find(displayId);
4783 if (stateIt != mTouchStatesByDisplay.end()) {
4784 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004785 for (size_t i = 0; i < state.windows.size();) {
4786 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004787 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004788 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004789 ALOGD("Touched window was removed: %s in display %" PRId32,
4790 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004791 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004792 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004793 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4794 if (touchedInputChannel != nullptr) {
4795 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4796 "touched window was removed");
4797 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004798 // Since we are about to drop the touch, cancel the events for the wallpaper as
4799 // well.
4800 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004801 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4802 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004803 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4804 if (wallpaper != nullptr) {
4805 sp<Connection> wallpaperConnection =
4806 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004807 if (wallpaperConnection != nullptr) {
4808 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4809 options);
4810 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004811 }
4812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004813 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004814 state.windows.erase(state.windows.begin() + i);
4815 } else {
4816 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004817 }
4818 }
arthurhungb89ccb02020-12-30 16:19:01 +08004819
arthurhung6d4bed92021-03-17 11:59:33 +08004820 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004821 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004822 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004823 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004824 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004825 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4826 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004827 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004828 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004829 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004830
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004831 // Determine if the orientation of any of the input windows have changed, and cancel all
4832 // pointer events if necessary.
4833 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4834 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4835 if (newWindowHandle != nullptr &&
4836 newWindowHandle->getInfo()->transform.getOrientation() !=
4837 oldWindowOrientations[oldWindowHandle->getId()]) {
4838 std::shared_ptr<InputChannel> inputChannel =
4839 getInputChannelLocked(newWindowHandle->getToken());
4840 if (inputChannel != nullptr) {
4841 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4842 "touched window's orientation changed");
4843 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004844 }
4845 }
4846 }
4847
Arthur Hung72d8dc32020-03-28 00:48:39 +00004848 // Release information for windows that are no longer present.
4849 // This ensures that unused input channels are released promptly.
4850 // Otherwise, they might stick around until the window handle is destroyed
4851 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004852 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004853 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004854 if (DEBUG_FOCUS) {
4855 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004856 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004857 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004858 }
chaviw291d88a2019-02-14 10:33:58 -08004859 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860}
4861
4862void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004863 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004864 if (DEBUG_FOCUS) {
4865 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4866 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4867 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004868 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004869 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004870 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871 } // release lock
4872
4873 // Wake up poll loop since it may need to make new input dispatching choices.
4874 mLooper->wake();
4875}
4876
Vishnu Nair599f1412021-06-21 10:39:58 -07004877void InputDispatcher::setFocusedApplicationLocked(
4878 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4879 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4880 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4881
4882 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4883 return; // This application is already focused. No need to wake up or change anything.
4884 }
4885
4886 // Set the new application handle.
4887 if (inputApplicationHandle != nullptr) {
4888 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4889 } else {
4890 mFocusedApplicationHandlesByDisplay.erase(displayId);
4891 }
4892
4893 // No matter what the old focused application was, stop waiting on it because it is
4894 // no longer focused.
4895 resetNoFocusedWindowTimeoutLocked();
4896}
4897
Tiger Huang721e26f2018-07-24 22:26:19 +08004898/**
4899 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4900 * the display not specified.
4901 *
4902 * We track any unreleased events for each window. If a window loses the ability to receive the
4903 * released event, we will send a cancel event to it. So when the focused display is changed, we
4904 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4905 * display. The display-specified events won't be affected.
4906 */
4907void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004908 if (DEBUG_FOCUS) {
4909 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4910 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004911 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004912 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004913
4914 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004915 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004916 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004917 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004918 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004919 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004920 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004921 CancelationOptions
4922 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4923 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004924 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004925 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4926 }
4927 }
4928 mFocusedDisplayId = displayId;
4929
Chris Ye3c2d6f52020-08-09 10:39:48 -07004930 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004931 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004932 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004933
Vishnu Nairad321cd2020-08-20 16:40:21 -07004934 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004935 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004936 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004937 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004938 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004939 }
4940 }
4941 }
4942
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004943 if (DEBUG_FOCUS) {
4944 logDispatchStateLocked();
4945 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004946 } // release lock
4947
4948 // Wake up poll loop since it may need to make new input dispatching choices.
4949 mLooper->wake();
4950}
4951
Michael Wrightd02c5b62014-02-10 15:10:22 -08004952void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004953 if (DEBUG_FOCUS) {
4954 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004956
4957 bool changed;
4958 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004959 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004960
4961 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4962 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004963 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004964 }
4965
4966 if (mDispatchEnabled && !enabled) {
4967 resetAndDropEverythingLocked("dispatcher is being disabled");
4968 }
4969
4970 mDispatchEnabled = enabled;
4971 mDispatchFrozen = frozen;
4972 changed = true;
4973 } else {
4974 changed = false;
4975 }
4976
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004977 if (DEBUG_FOCUS) {
4978 logDispatchStateLocked();
4979 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004980 } // release lock
4981
4982 if (changed) {
4983 // Wake up poll loop since it may need to make new input dispatching choices.
4984 mLooper->wake();
4985 }
4986}
4987
4988void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004989 if (DEBUG_FOCUS) {
4990 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4991 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004992
4993 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004994 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004995
4996 if (mInputFilterEnabled == enabled) {
4997 return;
4998 }
4999
5000 mInputFilterEnabled = enabled;
5001 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5002 } // release lock
5003
5004 // Wake up poll loop since there might be work to do to drop everything.
5005 mLooper->wake();
5006}
5007
Antonio Kanteka042c022022-07-06 16:51:07 -07005008bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5009 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005010 bool needWake = false;
5011 {
5012 std::scoped_lock lock(mLock);
5013 if (mInTouchMode == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005014 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005015 }
5016 if (DEBUG_TOUCH_MODE) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005017 ALOGD("Request to change touch mode from %s to %s (calling pid=%d, uid=%d, "
Antonio Kanteka042c022022-07-06 16:51:07 -07005018 "hasPermission=%s, target displayId=%d, perDisplayTouchModeEnabled=%s)",
5019 toString(mInTouchMode), toString(inTouchMode), pid, uid, toString(hasPermission),
5020 displayId, toString(kPerDisplayTouchModeEnabled));
Antonio Kantekea47acb2021-12-23 12:41:25 -08005021 }
5022 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 }
5031
Antonio Kanteka042c022022-07-06 16:51:07 -07005032 // TODO(b/198499018): Store touch mode per display (kPerDisplayTouchModeEnabled)
Antonio Kantekf16f2832021-09-28 04:39:20 +00005033 mInTouchMode = inTouchMode;
5034
Antonio Kantekf16f2832021-09-28 04:39:20 +00005035 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
5036 needWake = enqueueInboundEventLocked(std::move(entry));
5037 } // release lock
5038
5039 if (needWake) {
5040 mLooper->wake();
5041 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005042 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005043}
5044
Antonio Kantek48710e42022-03-24 14:19:30 -07005045bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5046 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5047 if (focusedToken == nullptr) {
5048 return false;
5049 }
5050 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5051 return isWindowOwnedBy(windowHandle, pid, uid);
5052}
5053
5054bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5055 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5056 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5057 const sp<WindowInfoHandle> windowHandle =
5058 getWindowHandleLocked(connectionToken);
5059 return isWindowOwnedBy(windowHandle, pid, uid);
5060 }) != mInteractionConnectionTokens.end();
5061}
5062
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005063void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5064 if (opacity < 0 || opacity > 1) {
5065 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5066 return;
5067 }
5068
5069 std::scoped_lock lock(mLock);
5070 mMaximumObscuringOpacityForTouch = opacity;
5071}
5072
Arthur Hungabbb9d82021-09-01 14:52:30 +00005073std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
5074 const sp<IBinder>& token) {
5075 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5076 for (TouchedWindow& w : state.windows) {
5077 if (w.windowHandle->getToken() == token) {
5078 return std::make_pair(&state, &w);
5079 }
5080 }
5081 }
5082 return std::make_pair(nullptr, nullptr);
5083}
5084
arthurhungb89ccb02020-12-30 16:19:01 +08005085bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5086 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005087 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005088 if (DEBUG_FOCUS) {
5089 ALOGD("Trivial transfer to same window.");
5090 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005091 return true;
5092 }
5093
Michael Wrightd02c5b62014-02-10 15:10:22 -08005094 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005095 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005096
Arthur Hungabbb9d82021-09-01 14:52:30 +00005097 // Find the target touch state and touched window by fromToken.
5098 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5099 if (state == nullptr || touchedWindow == nullptr) {
5100 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005101 return false;
5102 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005103
5104 const int32_t displayId = state->displayId;
5105 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5106 if (toWindowHandle == nullptr) {
5107 ALOGW("Cannot transfer focus because to window not found.");
5108 return false;
5109 }
5110
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005111 if (DEBUG_FOCUS) {
5112 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005113 touchedWindow->windowHandle->getName().c_str(),
5114 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005115 }
5116
Arthur Hungabbb9d82021-09-01 14:52:30 +00005117 // Erase old window.
5118 int32_t oldTargetFlags = touchedWindow->targetFlags;
5119 BitSet32 pointerIds = touchedWindow->pointerIds;
5120 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005121
Arthur Hungabbb9d82021-09-01 14:52:30 +00005122 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005123 nsecs_t downTimeInTarget = now();
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005124 int32_t newTargetFlags =
5125 oldTargetFlags & (InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
5126 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
5127 newTargetFlags |= InputTarget::FLAG_FOREGROUND;
5128 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005129 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005130
Arthur Hungabbb9d82021-09-01 14:52:30 +00005131 // Store the dragging window.
5132 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005133 if (pointerIds.count() != 1) {
5134 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5135 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005136 return false;
5137 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005138 // Track the pointer id for drag window and generate the drag state.
5139 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005140 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141 }
5142
Arthur Hungabbb9d82021-09-01 14:52:30 +00005143 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005144 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5145 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005146 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005147 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005148 CancelationOptions
5149 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5150 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005151 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005152 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153 }
5154
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005155 if (DEBUG_FOCUS) {
5156 logDispatchStateLocked();
5157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005158 } // release lock
5159
5160 // Wake up poll loop since it may need to make new input dispatching choices.
5161 mLooper->wake();
5162 return true;
5163}
5164
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005165/**
5166 * Get the touched foreground window on the given display.
5167 * Return null if there are no windows touched on that display, or if more than one foreground
5168 * window is being touched.
5169 */
5170sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5171 auto stateIt = mTouchStatesByDisplay.find(displayId);
5172 if (stateIt == mTouchStatesByDisplay.end()) {
5173 ALOGI("No touch state on display %" PRId32, displayId);
5174 return nullptr;
5175 }
5176
5177 const TouchState& state = stateIt->second;
5178 sp<WindowInfoHandle> touchedForegroundWindow;
5179 // If multiple foreground windows are touched, return nullptr
5180 for (const TouchedWindow& window : state.windows) {
5181 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5182 if (touchedForegroundWindow != nullptr) {
5183 ALOGI("Two or more foreground windows: %s and %s",
5184 touchedForegroundWindow->getName().c_str(),
5185 window.windowHandle->getName().c_str());
5186 return nullptr;
5187 }
5188 touchedForegroundWindow = window.windowHandle;
5189 }
5190 }
5191 return touchedForegroundWindow;
5192}
5193
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005194// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005195bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005196 sp<IBinder> fromToken;
5197 { // acquire lock
5198 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005199 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005200 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005201 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5202 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005203 return false;
5204 }
5205
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005206 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5207 if (from == nullptr) {
5208 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5209 return false;
5210 }
5211
5212 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005213 } // release lock
5214
5215 return transferTouchFocus(fromToken, destChannelToken);
5216}
5217
Michael Wrightd02c5b62014-02-10 15:10:22 -08005218void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005219 if (DEBUG_FOCUS) {
5220 ALOGD("Resetting and dropping all events (%s).", reason);
5221 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005222
5223 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5224 synthesizeCancelationEventsForAllConnectionsLocked(options);
5225
5226 resetKeyRepeatLocked();
5227 releasePendingEventLocked();
5228 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005229 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005230
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005231 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005232 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005233 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005234 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005235}
5236
5237void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005238 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005239 dumpDispatchStateLocked(dump);
5240
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005241 std::istringstream stream(dump);
5242 std::string line;
5243
5244 while (std::getline(stream, line, '\n')) {
5245 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005246 }
5247}
5248
Prabir Pradhan99987712020-11-10 18:43:05 -08005249std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5250 std::string dump;
5251
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005252 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5253 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005254
5255 std::string windowName = "None";
5256 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005257 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005258 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5259 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5260 : "token has capture without window";
5261 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005262 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005263
5264 return dump;
5265}
5266
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005267void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005268 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5269 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5270 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005271 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272
Tiger Huang721e26f2018-07-24 22:26:19 +08005273 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5274 dump += StringPrintf(INDENT "FocusedApplications:\n");
5275 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5276 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005277 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005278 const std::chrono::duration timeout =
5279 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005280 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005281 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005282 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005283 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005284 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005285 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005286 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005287
Vishnu Nairc519ff72021-01-21 08:23:08 -08005288 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005289 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005290
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005291 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005292 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005293 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5294 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005295 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005296 state.displayId, toString(state.down), toString(state.split),
5297 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005298 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005299 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005300 for (size_t i = 0; i < state.windows.size(); i++) {
5301 const TouchedWindow& touchedWindow = state.windows[i];
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005302 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, "
5303 "targetFlags=0x%x, firstDownTimeInTarget=%" PRId64
5304 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005305 i, touchedWindow.windowHandle->getName().c_str(),
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005306 touchedWindow.pointerIds.value, touchedWindow.targetFlags,
5307 ns2ms(touchedWindow.firstDownTimeInTarget.value_or(0)));
Jeff Brownf086ddb2014-02-11 14:28:48 -08005308 }
5309 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005310 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005312 }
5313 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005314 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005315 }
5316
arthurhung6d4bed92021-03-17 11:59:33 +08005317 if (mDragState) {
5318 dump += StringPrintf(INDENT "DragState:\n");
5319 mDragState->dump(dump, INDENT2);
5320 }
5321
Arthur Hungb92218b2018-08-14 12:00:21 +08005322 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005323 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5324 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5325 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5326 const auto& displayInfo = it->second;
5327 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5328 displayInfo.logicalHeight);
5329 displayInfo.transform.dump(dump, "transform", INDENT4);
5330 } else {
5331 dump += INDENT2 "No DisplayInfo found!\n";
5332 }
5333
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005334 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005335 dump += INDENT2 "Windows:\n";
5336 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005337 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5338 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005339
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005340 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005341 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005342 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005343 "applicationInfo.name=%s, "
5344 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005345 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005346 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005347 windowInfo->displayId,
5348 windowInfo->inputConfig.string().c_str(),
5349 windowInfo->alpha, windowInfo->frameLeft,
5350 windowInfo->frameTop, windowInfo->frameRight,
5351 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005352 windowInfo->applicationInfo.name.c_str(),
5353 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005354 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005355 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005356 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005357 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005358 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005359 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005360 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005361 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005362 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005363 }
5364 } else {
5365 dump += INDENT2 "Windows: <none>\n";
5366 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005367 }
5368 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005369 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005370 }
5371
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005372 if (!mGlobalMonitorsByDisplay.empty()) {
5373 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5374 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005375 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005376 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005377 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005378 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005379 }
5380
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005381 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005382
5383 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005384 if (!mRecentQueue.empty()) {
5385 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005386 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005387 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005388 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005389 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005390 }
5391 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005392 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005393 }
5394
5395 // Dump event currently being dispatched.
5396 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005397 dump += INDENT "PendingEvent:\n";
5398 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005399 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005400 dump += StringPrintf(", age=%" PRId64 "ms\n",
5401 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005402 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005403 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005404 }
5405
5406 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005407 if (!mInboundQueue.empty()) {
5408 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005409 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005410 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005411 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005412 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005413 }
5414 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005415 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005416 }
5417
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005418 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005419 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005420 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5421 const KeyReplacement& replacement = pair.first;
5422 int32_t newKeyCode = pair.second;
5423 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005424 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005425 }
5426 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005427 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005428 }
5429
Prabir Pradhancef936d2021-07-21 16:17:52 +00005430 if (!mCommandQueue.empty()) {
5431 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5432 } else {
5433 dump += INDENT "CommandQueue: <empty>\n";
5434 }
5435
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005436 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005437 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005438 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005439 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005440 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005441 connection->inputChannel->getFd().get(),
5442 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005443 connection->getWindowName().c_str(),
5444 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005445 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005446
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005447 if (!connection->outboundQueue.empty()) {
5448 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5449 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005450 dump += dumpQueue(connection->outboundQueue, currentTime);
5451
Michael Wrightd02c5b62014-02-10 15:10:22 -08005452 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005453 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005454 }
5455
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005456 if (!connection->waitQueue.empty()) {
5457 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5458 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005459 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005461 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005462 }
5463 }
5464 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005465 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005466 }
5467
5468 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005469 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5470 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005471 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005472 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005473 }
5474
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005475 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005476 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5477 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5478 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005479 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005480 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005481}
5482
Michael Wright3dd60e22019-03-27 22:06:44 +00005483void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5484 const size_t numMonitors = monitors.size();
5485 for (size_t i = 0; i < numMonitors; i++) {
5486 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005487 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005488 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5489 dump += "\n";
5490 }
5491}
5492
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005493class LooperEventCallback : public LooperCallback {
5494public:
5495 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5496 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5497
5498private:
5499 std::function<int(int events)> mCallback;
5500};
5501
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005502Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005503 if (DEBUG_CHANNEL_CREATION) {
5504 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5505 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005506
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005507 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005508 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005509 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005510
5511 if (result) {
5512 return base::Error(result) << "Failed to open input channel pair with name " << name;
5513 }
5514
Michael Wrightd02c5b62014-02-10 15:10:22 -08005515 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005516 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005517 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005518 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005519 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005520 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005521
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005522 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5523 ALOGE("Created a new connection, but the token %p is already known", token.get());
5524 }
5525 mConnectionsByToken.emplace(token, connection);
5526
5527 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5528 this, std::placeholders::_1, token);
5529
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005530 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5531 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005532 } // release lock
5533
5534 // Wake the looper because some connections have changed.
5535 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005536 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005537}
5538
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005539Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005540 const std::string& name,
5541 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005542 std::shared_ptr<InputChannel> serverChannel;
5543 std::unique_ptr<InputChannel> clientChannel;
5544 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5545 if (result) {
5546 return base::Error(result) << "Failed to open input channel pair with name " << name;
5547 }
5548
Michael Wright3dd60e22019-03-27 22:06:44 +00005549 { // acquire lock
5550 std::scoped_lock _l(mLock);
5551
5552 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005553 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5554 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005555 }
5556
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005557 sp<Connection> connection =
5558 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005559 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005560 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005561
5562 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5563 ALOGE("Created a new connection, but the token %p is already known", token.get());
5564 }
5565 mConnectionsByToken.emplace(token, connection);
5566 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5567 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005568
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005569 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005570
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005571 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5572 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005573 }
Garfield Tan15601662020-09-22 15:32:38 -07005574
Michael Wright3dd60e22019-03-27 22:06:44 +00005575 // Wake the looper because some connections have changed.
5576 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005577 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005578}
5579
Garfield Tan15601662020-09-22 15:32:38 -07005580status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005581 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005582 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005583
Garfield Tan15601662020-09-22 15:32:38 -07005584 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005585 if (status) {
5586 return status;
5587 }
5588 } // release lock
5589
5590 // Wake the poll loop because removing the connection may have changed the current
5591 // synchronization state.
5592 mLooper->wake();
5593 return OK;
5594}
5595
Garfield Tan15601662020-09-22 15:32:38 -07005596status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5597 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005598 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005599 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005600 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005601 return BAD_VALUE;
5602 }
5603
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005604 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005605
Michael Wrightd02c5b62014-02-10 15:10:22 -08005606 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005607 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005608 }
5609
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005610 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005611
5612 nsecs_t currentTime = now();
5613 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5614
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005615 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005616 return OK;
5617}
5618
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005619void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005620 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5621 auto& [displayId, monitors] = *it;
5622 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5623 return monitor.inputChannel->getConnectionToken() == connectionToken;
5624 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005625
Michael Wright3dd60e22019-03-27 22:06:44 +00005626 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005627 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005628 } else {
5629 ++it;
5630 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005631 }
5632}
5633
Michael Wright3dd60e22019-03-27 22:06:44 +00005634status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005635 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005636 return pilferPointersLocked(token);
5637}
Michael Wright3dd60e22019-03-27 22:06:44 +00005638
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005639status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005640 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5641 if (!requestingChannel) {
5642 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5643 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005644 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005645
5646 auto [statePtr, windowPtr] = findTouchStateAndWindowLocked(token);
5647 if (statePtr == nullptr || windowPtr == nullptr || !statePtr->down) {
5648 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5649 " Ignoring.");
5650 return BAD_VALUE;
5651 }
5652
5653 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005654 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005655 // Send cancel events to all the input channels we're stealing from.
5656 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5657 "input channel stole pointer stream");
5658 options.deviceId = state.deviceId;
5659 options.displayId = state.displayId;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005660 if (state.split) {
5661 // If split pointers then selectively cancel pointers otherwise cancel all pointers
5662 options.pointerIds = window.pointerIds;
5663 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005664 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005665 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005666 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005667 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005668 if (channel != nullptr && channel->getConnectionToken() != token) {
5669 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5670 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5671 canceledWindows += channel->getName();
5672 }
5673 }
5674 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5675 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5676 canceledWindows.c_str());
5677
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005678 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005679 // This only blocks relevant pointers to be sent to other windows
5680 window.isPilferingPointers = true;
5681
5682 if (state.split) {
5683 state.cancelPointersForWindowsExcept(window.pointerIds, token);
5684 } else {
5685 state.filterWindowsExcept(token);
5686 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005687 return OK;
5688}
5689
Prabir Pradhan99987712020-11-10 18:43:05 -08005690void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5691 { // acquire lock
5692 std::scoped_lock _l(mLock);
5693 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005694 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005695 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5696 windowHandle != nullptr ? windowHandle->getName().c_str()
5697 : "token without window");
5698 }
5699
Vishnu Nairc519ff72021-01-21 08:23:08 -08005700 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005701 if (focusedToken != windowToken) {
5702 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5703 enabled ? "enable" : "disable");
5704 return;
5705 }
5706
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005707 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005708 ALOGW("Ignoring request to %s Pointer Capture: "
5709 "window has %s requested pointer capture.",
5710 enabled ? "enable" : "disable", enabled ? "already" : "not");
5711 return;
5712 }
5713
Christine Franksb768bb42021-11-29 12:11:31 -08005714 if (enabled) {
5715 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5716 mIneligibleDisplaysForPointerCapture.end(),
5717 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5718 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5719 return;
5720 }
5721 }
5722
Prabir Pradhan99987712020-11-10 18:43:05 -08005723 setPointerCaptureLocked(enabled);
5724 } // release lock
5725
5726 // Wake the thread to process command entries.
5727 mLooper->wake();
5728}
5729
Christine Franksb768bb42021-11-29 12:11:31 -08005730void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5731 { // acquire lock
5732 std::scoped_lock _l(mLock);
5733 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5734 if (!isEligible) {
5735 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5736 }
5737 } // release lock
5738}
5739
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005740std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5741 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005742 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005743 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005744 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005745 }
5746 }
5747 }
5748 return std::nullopt;
5749}
5750
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005751sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005752 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005753 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005754 }
5755
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005756 for (const auto& [token, connection] : mConnectionsByToken) {
5757 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005758 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005759 }
5760 }
Robert Carr4e670e52018-08-15 13:26:12 -07005761
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005762 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005763}
5764
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005765std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5766 sp<Connection> connection = getConnectionLocked(connectionToken);
5767 if (connection == nullptr) {
5768 return "<nullptr>";
5769 }
5770 return connection->getInputChannelName();
5771}
5772
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005773void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005774 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005775 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005776}
5777
Prabir Pradhancef936d2021-07-21 16:17:52 +00005778void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5779 const sp<Connection>& connection, uint32_t seq,
5780 bool handled, nsecs_t consumeTime) {
5781 // Handle post-event policy actions.
5782 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5783 if (dispatchEntryIt == connection->waitQueue.end()) {
5784 return;
5785 }
5786 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5787 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5788 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5789 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5790 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5791 }
5792 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5793 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5794 connection->inputChannel->getConnectionToken(),
5795 dispatchEntry->deliveryTime, consumeTime, finishTime);
5796 }
5797
5798 bool restartEvent;
5799 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5800 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5801 restartEvent =
5802 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5803 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5804 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5805 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5806 handled);
5807 } else {
5808 restartEvent = false;
5809 }
5810
5811 // Dequeue the event and start the next cycle.
5812 // Because the lock might have been released, it is possible that the
5813 // contents of the wait queue to have been drained, so we need to double-check
5814 // a few things.
5815 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5816 if (dispatchEntryIt != connection->waitQueue.end()) {
5817 dispatchEntry = *dispatchEntryIt;
5818 connection->waitQueue.erase(dispatchEntryIt);
5819 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5820 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5821 if (!connection->responsive) {
5822 connection->responsive = isConnectionResponsive(*connection);
5823 if (connection->responsive) {
5824 // The connection was unresponsive, and now it's responsive.
5825 processConnectionResponsiveLocked(*connection);
5826 }
5827 }
5828 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005829 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005830 connection->outboundQueue.push_front(dispatchEntry);
5831 traceOutboundQueueLength(*connection);
5832 } else {
5833 releaseDispatchEntry(dispatchEntry);
5834 }
5835 }
5836
5837 // Start the next dispatch cycle for this connection.
5838 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005839}
5840
Prabir Pradhancef936d2021-07-21 16:17:52 +00005841void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5842 const sp<IBinder>& newToken) {
5843 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5844 scoped_unlock unlock(mLock);
5845 mPolicy->notifyFocusChanged(oldToken, newToken);
5846 };
5847 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005848}
5849
Prabir Pradhancef936d2021-07-21 16:17:52 +00005850void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5851 auto command = [this, token, x, y]() REQUIRES(mLock) {
5852 scoped_unlock unlock(mLock);
5853 mPolicy->notifyDropWindow(token, x, y);
5854 };
5855 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005856}
5857
Vishnu Nair2f5bc8b2022-08-09 00:03:11 +00005858bool InputDispatcher::onAnrLocked(const android::gui::FocusRequest& pendingFocusRequest) {
5859 if (pendingFocusRequest.token == nullptr) {
5860 return false;
5861 }
5862
5863 const std::string reason = android::base::StringPrintf("%s is not focusable.",
5864 pendingFocusRequest.windowName.c_str());
5865 updateLastAnrStateLocked(pendingFocusRequest.windowName, reason);
5866 sp<Connection> connection = getConnectionLocked(pendingFocusRequest.token);
5867 if (connection != nullptr) {
5868 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5869 // Stop waking up for events on this connection, it is already unresponsive
5870 cancelEventsForAnrLocked(connection);
5871 } else {
5872 sendWindowUnresponsiveCommandLocked(pendingFocusRequest.token, std::nullopt, reason);
5873 }
5874 return true;
5875}
5876
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005877void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5878 if (connection == nullptr) {
5879 LOG_ALWAYS_FATAL("Caller must check for nullness");
5880 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005881 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5882 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005883 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005884 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005885 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005886 return;
5887 }
5888 /**
5889 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5890 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5891 * has changed. This could cause newer entries to time out before the already dispatched
5892 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5893 * processes the events linearly. So providing information about the oldest entry seems to be
5894 * most useful.
5895 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005896 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005897 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5898 std::string reason =
5899 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005900 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005901 ns2ms(currentWait),
5902 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005903 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005904 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005905
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005906 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5907
5908 // Stop waking up for events on this connection, it is already unresponsive
5909 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005910}
5911
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005912void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5913 std::string reason =
5914 StringPrintf("%s does not have a focused window", application->getName().c_str());
5915 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005916
Prabir Pradhancef936d2021-07-21 16:17:52 +00005917 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5918 scoped_unlock unlock(mLock);
5919 mPolicy->notifyNoFocusedWindowAnr(application);
5920 };
5921 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005922}
5923
chaviw98318de2021-05-19 16:45:23 -05005924void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005925 const std::string& reason) {
5926 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5927 updateLastAnrStateLocked(windowLabel, reason);
5928}
5929
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005930void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5931 const std::string& reason) {
5932 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005933 updateLastAnrStateLocked(windowLabel, reason);
5934}
5935
5936void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5937 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005938 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005939 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005940 struct tm tm;
5941 localtime_r(&t, &tm);
5942 char timestr[64];
5943 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005944 mLastAnrState.clear();
5945 mLastAnrState += INDENT "ANR:\n";
5946 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005947 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5948 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005949 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005950}
5951
Prabir Pradhancef936d2021-07-21 16:17:52 +00005952void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5953 KeyEntry& entry) {
5954 const KeyEvent event = createKeyEvent(entry);
5955 nsecs_t delay = 0;
5956 { // release lock
5957 scoped_unlock unlock(mLock);
5958 android::base::Timer t;
5959 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5960 entry.policyFlags);
5961 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5962 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5963 std::to_string(t.duration().count()).c_str());
5964 }
5965 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005966
5967 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005968 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005969 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005970 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005971 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005972 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5973 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005975}
5976
Prabir Pradhancef936d2021-07-21 16:17:52 +00005977void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005978 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005979 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005980 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005981 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005982 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005983 };
5984 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005985}
5986
Prabir Pradhanedd96402022-02-15 01:46:16 -08005987void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5988 std::optional<int32_t> pid) {
5989 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005990 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005991 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005992 };
5993 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005994}
5995
5996/**
5997 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5998 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5999 * command entry to the command queue.
6000 */
6001void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6002 std::string reason) {
6003 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006004 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006005 if (connection.monitor) {
6006 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6007 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006008 pid = findMonitorPidByTokenLocked(connectionToken);
6009 } else {
6010 // The connection is a window
6011 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6012 reason.c_str());
6013 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6014 if (handle != nullptr) {
6015 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006016 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006017 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006018 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006019}
6020
6021/**
6022 * Tell the policy that a connection has become responsive so that it can stop ANR.
6023 */
6024void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6025 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006026 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006027 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006028 pid = findMonitorPidByTokenLocked(connectionToken);
6029 } else {
6030 // The connection is a window
6031 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6032 if (handle != nullptr) {
6033 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006034 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006035 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006036 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006037}
6038
Prabir Pradhancef936d2021-07-21 16:17:52 +00006039bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006040 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006041 KeyEntry& keyEntry, bool handled) {
6042 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006043 if (!handled) {
6044 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006045 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006046 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006047 return false;
6048 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006049
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006050 // Get the fallback key state.
6051 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006052 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006053 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006054 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006055 connection->inputState.removeFallbackKey(originalKeyCode);
6056 }
6057
6058 if (handled || !dispatchEntry->hasForegroundTarget()) {
6059 // If the application handles the original key for which we previously
6060 // generated a fallback or if the window is not a foreground window,
6061 // then cancel the associated fallback key, if any.
6062 if (fallbackKeyCode != -1) {
6063 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006064 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6065 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6066 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6067 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6068 keyEntry.policyFlags);
6069 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006070 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006071 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006072
6073 mLock.unlock();
6074
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006075 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006076 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006077
6078 mLock.lock();
6079
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006080 // Cancel the fallback key.
6081 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006082 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006083 "application handled the original non-fallback key "
6084 "or is no longer a foreground target, "
6085 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006086 options.keyCode = fallbackKeyCode;
6087 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006088 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006089 connection->inputState.removeFallbackKey(originalKeyCode);
6090 }
6091 } else {
6092 // If the application did not handle a non-fallback key, first check
6093 // that we are in a good state to perform unhandled key event processing
6094 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006095 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006096 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006097 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6098 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6099 "since this is not an initial down. "
6100 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6101 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6102 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006103 return false;
6104 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006105
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006106 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006107 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6108 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6109 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6110 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6111 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006112 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006113
6114 mLock.unlock();
6115
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006116 bool fallback =
6117 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006118 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006119
6120 mLock.lock();
6121
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006122 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006123 connection->inputState.removeFallbackKey(originalKeyCode);
6124 return false;
6125 }
6126
6127 // Latch the fallback keycode for this key on an initial down.
6128 // The fallback keycode cannot change at any other point in the lifecycle.
6129 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006130 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006131 fallbackKeyCode = event.getKeyCode();
6132 } else {
6133 fallbackKeyCode = AKEYCODE_UNKNOWN;
6134 }
6135 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6136 }
6137
6138 ALOG_ASSERT(fallbackKeyCode != -1);
6139
6140 // Cancel the fallback key if the policy decides not to send it anymore.
6141 // We will continue to dispatch the key to the policy but we will no
6142 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006143 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6144 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006145 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6146 if (fallback) {
6147 ALOGD("Unhandled key event: Policy requested to send key %d"
6148 "as a fallback for %d, but on the DOWN it had requested "
6149 "to send %d instead. Fallback canceled.",
6150 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6151 } else {
6152 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6153 "but on the DOWN it had requested to send %d. "
6154 "Fallback canceled.",
6155 originalKeyCode, fallbackKeyCode);
6156 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006157 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006158
6159 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6160 "canceling fallback, policy no longer desires it");
6161 options.keyCode = fallbackKeyCode;
6162 synthesizeCancelationEventsForConnectionLocked(connection, options);
6163
6164 fallback = false;
6165 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006166 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006167 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006168 }
6169 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006170
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006171 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6172 {
6173 std::string msg;
6174 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6175 connection->inputState.getFallbackKeys();
6176 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6177 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6178 }
6179 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6180 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006181 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006182 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006183
6184 if (fallback) {
6185 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006186 keyEntry.eventTime = event.getEventTime();
6187 keyEntry.deviceId = event.getDeviceId();
6188 keyEntry.source = event.getSource();
6189 keyEntry.displayId = event.getDisplayId();
6190 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6191 keyEntry.keyCode = fallbackKeyCode;
6192 keyEntry.scanCode = event.getScanCode();
6193 keyEntry.metaState = event.getMetaState();
6194 keyEntry.repeatCount = event.getRepeatCount();
6195 keyEntry.downTime = event.getDownTime();
6196 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006197
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006198 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6199 ALOGD("Unhandled key event: Dispatching fallback key. "
6200 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6201 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6202 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006203 return true; // restart the event
6204 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006205 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6206 ALOGD("Unhandled key event: No fallback key.");
6207 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006208
6209 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006210 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006211 }
6212 }
6213 return false;
6214}
6215
Prabir Pradhancef936d2021-07-21 16:17:52 +00006216bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006217 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006218 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006219 return false;
6220}
6221
Michael Wrightd02c5b62014-02-10 15:10:22 -08006222void InputDispatcher::traceInboundQueueLengthLocked() {
6223 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006224 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006225 }
6226}
6227
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006228void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006229 if (ATRACE_ENABLED()) {
6230 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006231 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6232 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006233 }
6234}
6235
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006236void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006237 if (ATRACE_ENABLED()) {
6238 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006239 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6240 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006241 }
6242}
6243
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006244void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006245 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006246
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006247 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006248 dumpDispatchStateLocked(dump);
6249
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006250 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006251 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006252 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006253 }
6254}
6255
6256void InputDispatcher::monitor() {
6257 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006258 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006259 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006260 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006261}
6262
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006263/**
6264 * Wake up the dispatcher and wait until it processes all events and commands.
6265 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6266 * this method can be safely called from any thread, as long as you've ensured that
6267 * the work you are interested in completing has already been queued.
6268 */
6269bool InputDispatcher::waitForIdle() {
6270 /**
6271 * Timeout should represent the longest possible time that a device might spend processing
6272 * events and commands.
6273 */
6274 constexpr std::chrono::duration TIMEOUT = 100ms;
6275 std::unique_lock lock(mLock);
6276 mLooper->wake();
6277 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6278 return result == std::cv_status::no_timeout;
6279}
6280
Vishnu Naire798b472020-07-23 13:52:21 -07006281/**
6282 * Sets focus to the window identified by the token. This must be called
6283 * after updating any input window handles.
6284 *
6285 * Params:
6286 * request.token - input channel token used to identify the window that should gain focus.
6287 * request.focusedToken - the token that the caller expects currently to be focused. If the
6288 * specified token does not match the currently focused window, this request will be dropped.
6289 * If the specified focused token matches the currently focused window, the call will succeed.
6290 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6291 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6292 * when requesting the focus change. This determines which request gets
6293 * precedence if there is a focus change request from another source such as pointer down.
6294 */
Vishnu Nair958da932020-08-21 17:12:37 -07006295void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6296 { // acquire lock
6297 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006298 std::optional<FocusResolver::FocusChanges> changes =
6299 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6300 if (changes) {
6301 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006302 }
6303 } // release lock
6304 // Wake up poll loop since it may need to make new input dispatching choices.
6305 mLooper->wake();
6306}
6307
Vishnu Nairc519ff72021-01-21 08:23:08 -08006308void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6309 if (changes.oldFocus) {
6310 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006311 if (focusedInputChannel) {
6312 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6313 "focus left window");
6314 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006315 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006316 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006317 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006318 if (changes.newFocus) {
6319 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006320 }
6321
Prabir Pradhan99987712020-11-10 18:43:05 -08006322 // If a window has pointer capture, then it must have focus. We need to ensure that this
6323 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6324 // If the window loses focus before it loses pointer capture, then the window can be in a state
6325 // where it has pointer capture but not focus, violating the contract. Therefore we must
6326 // dispatch the pointer capture event before the focus event. Since focus events are added to
6327 // the front of the queue (above), we add the pointer capture event to the front of the queue
6328 // after the focus events are added. This ensures the pointer capture event ends up at the
6329 // front.
6330 disablePointerCaptureForcedLocked();
6331
Vishnu Nairc519ff72021-01-21 08:23:08 -08006332 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006333 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006334 }
6335}
Vishnu Nair958da932020-08-21 17:12:37 -07006336
Prabir Pradhan99987712020-11-10 18:43:05 -08006337void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006338 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006339 return;
6340 }
6341
6342 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6343
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006344 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006345 setPointerCaptureLocked(false);
6346 }
6347
6348 if (!mWindowTokenWithPointerCapture) {
6349 // No need to send capture changes because no window has capture.
6350 return;
6351 }
6352
6353 if (mPendingEvent != nullptr) {
6354 // Move the pending event to the front of the queue. This will give the chance
6355 // for the pending event to be dropped if it is a captured event.
6356 mInboundQueue.push_front(mPendingEvent);
6357 mPendingEvent = nullptr;
6358 }
6359
6360 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006361 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006362 mInboundQueue.push_front(std::move(entry));
6363}
6364
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006365void InputDispatcher::setPointerCaptureLocked(bool enable) {
6366 mCurrentPointerCaptureRequest.enable = enable;
6367 mCurrentPointerCaptureRequest.seq++;
6368 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006369 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006370 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006371 };
6372 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006373}
6374
Vishnu Nair599f1412021-06-21 10:39:58 -07006375void InputDispatcher::displayRemoved(int32_t displayId) {
6376 { // acquire lock
6377 std::scoped_lock _l(mLock);
6378 // Set an empty list to remove all handles from the specific display.
6379 setInputWindowsLocked(/* window handles */ {}, displayId);
6380 setFocusedApplicationLocked(displayId, nullptr);
6381 // Call focus resolver to clean up stale requests. This must be called after input windows
6382 // have been removed for the removed display.
6383 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006384 // Reset pointer capture eligibility, regardless of previous state.
6385 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006386 } // release lock
6387
6388 // Wake up poll loop since it may need to make new input dispatching choices.
6389 mLooper->wake();
6390}
6391
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006392void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6393 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006394 // The listener sends the windows as a flattened array. Separate the windows by display for
6395 // more convenient parsing.
6396 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006397 for (const auto& info : windowInfos) {
6398 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006399 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006400 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006401
6402 { // acquire lock
6403 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006404
6405 // Ensure that we have an entry created for all existing displays so that if a displayId has
6406 // no windows, we can tell that the windows were removed from the display.
6407 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6408 handlesPerDisplay[displayId];
6409 }
6410
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006411 mDisplayInfos.clear();
6412 for (const auto& displayInfo : displayInfos) {
6413 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6414 }
6415
6416 for (const auto& [displayId, handles] : handlesPerDisplay) {
6417 setInputWindowsLocked(handles, displayId);
6418 }
6419 }
6420 // Wake up poll loop since it may need to make new input dispatching choices.
6421 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006422}
6423
Vishnu Nair062a8672021-09-03 16:07:44 -07006424bool InputDispatcher::shouldDropInput(
6425 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006426 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6427 (windowHandle->getInfo()->inputConfig.test(
6428 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006429 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006430 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6431 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006432 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006433 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006434 windowHandle->getInfo()->displayId);
6435 return true;
6436 }
6437 return false;
6438}
6439
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006440void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6441 const std::vector<gui::WindowInfo>& windowInfos,
6442 const std::vector<DisplayInfo>& displayInfos) {
6443 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6444}
6445
Arthur Hungdfd528e2021-12-08 13:23:04 +00006446void InputDispatcher::cancelCurrentTouch() {
6447 {
6448 std::scoped_lock _l(mLock);
6449 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6450 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6451 "cancel current touch");
6452 synthesizeCancelationEventsForAllConnectionsLocked(options);
6453
6454 mTouchStatesByDisplay.clear();
6455 mLastHoverWindowHandle.clear();
6456 }
6457 // Wake up poll loop since there might be work to do.
6458 mLooper->wake();
6459}
6460
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006461void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6462 std::scoped_lock _l(mLock);
6463 mMonitorDispatchingTimeout = timeout;
6464}
6465
Garfield Tane84e6f92019-08-29 17:28:41 -07006466} // namespace android::inputdispatcher