blob: b3843eb2e1dd9ac8845a335f2da134933e0ac020 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080023#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080024#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050025#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070026#include <binder/Binder.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080027#include <ftl/enum.h>
chaviw15fab6f2021-06-07 14:15:52 -050028#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080029#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070030#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010031#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070032#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
Michael Wright44753b12020-07-08 13:48:11 +010034#include <cerrno>
35#include <cinttypes>
36#include <climits>
37#include <cstddef>
38#include <ctime>
39#include <queue>
40#include <sstream>
41
42#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000043#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070044#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010045
Michael Wrightd02c5b62014-02-10 15:10:22 -080046#define INDENT " "
47#define INDENT2 " "
48#define INDENT3 " "
49#define INDENT4 " "
50
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080051using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000052using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080053using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070054using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050055using android::gui::FocusRequest;
56using android::gui::TouchOcclusionMode;
57using android::gui::WindowInfo;
58using android::gui::WindowInfoHandle;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100059using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080060using android::os::InputEventInjectionResult;
61using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080062
Garfield Tane84e6f92019-08-29 17:28:41 -070063namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080064
Prabir Pradhancef936d2021-07-21 16:17:52 +000065namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000066// Temporarily releases a held mutex for the lifetime of the instance.
67// Named to match std::scoped_lock
68class scoped_unlock {
69public:
70 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
71 ~scoped_unlock() { mMutex.lock(); }
72
73private:
74 std::mutex& mMutex;
75};
76
Michael Wrightd02c5b62014-02-10 15:10:22 -080077// Default input dispatching timeout if there is no focused application or paused window
78// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080079const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
80 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
81 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080082
83// Amount of time to allow for all pending events to be processed when an app switch
84// key is on the way. This is used to preempt input dispatch and drop input events
85// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000086constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080087
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080088const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
Michael Wrightd02c5b62014-02-10 15:10:22 -080090// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000091constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
92
93// Log a warning when an interception call takes longer than this to process.
94constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080095
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -070096// Additional key latency in case a connection is still processing some motion events.
97// This will help with the case when a user touched a button that opens a new window,
98// and gives us the chance to dispatch the key to this new window.
99constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
100
Michael Wrightd02c5b62014-02-10 15:10:22 -0800101// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000102constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
103
Antonio Kantekea47acb2021-12-23 12:41:25 -0800104// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000105constexpr int LOGTAG_INPUT_INTERACTION = 62000;
106constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000107constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000108
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000109inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800110 return systemTime(SYSTEM_TIME_MONOTONIC);
111}
112
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000113inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800114 return value ? "true" : "false";
115}
116
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000117inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000118 if (binder == nullptr) {
119 return "<null>";
120 }
121 return StringPrintf("%p", binder.get());
122}
123
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000124inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700125 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
126 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800127}
128
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000129bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800130 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700131 case AKEY_EVENT_ACTION_DOWN:
132 case AKEY_EVENT_ACTION_UP:
133 return true;
134 default:
135 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800136 }
137}
138
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000139bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700140 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800141 ALOGE("Key event has invalid action code 0x%x", action);
142 return false;
143 }
144 return true;
145}
146
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000147bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800148 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700149 case AMOTION_EVENT_ACTION_DOWN:
150 case AMOTION_EVENT_ACTION_UP:
151 case AMOTION_EVENT_ACTION_CANCEL:
152 case AMOTION_EVENT_ACTION_MOVE:
153 case AMOTION_EVENT_ACTION_OUTSIDE:
154 case AMOTION_EVENT_ACTION_HOVER_ENTER:
155 case AMOTION_EVENT_ACTION_HOVER_MOVE:
156 case AMOTION_EVENT_ACTION_HOVER_EXIT:
157 case AMOTION_EVENT_ACTION_SCROLL:
158 return true;
159 case AMOTION_EVENT_ACTION_POINTER_DOWN:
160 case AMOTION_EVENT_ACTION_POINTER_UP: {
161 int32_t index = getMotionEventActionPointerIndex(action);
162 return index >= 0 && index < pointerCount;
163 }
164 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
165 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
166 return actionButton != 0;
167 default:
168 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800169 }
170}
171
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000172int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500173 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
174}
175
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000176bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
177 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700178 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800179 ALOGE("Motion event has invalid action code 0x%x", action);
180 return false;
181 }
182 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800183 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %zu.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700184 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 return false;
186 }
187 BitSet32 pointerIdBits;
188 for (size_t i = 0; i < pointerCount; i++) {
189 int32_t id = pointerProperties[i].id;
190 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700191 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
192 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800193 return false;
194 }
195 if (pointerIdBits.hasBit(id)) {
196 ALOGE("Motion event has duplicate pointer id %d", id);
197 return false;
198 }
199 pointerIdBits.markBit(id);
200 }
201 return true;
202}
203
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000204std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800205 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000206 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800207 }
208
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000209 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800210 bool first = true;
211 Region::const_iterator cur = region.begin();
212 Region::const_iterator const tail = region.end();
213 while (cur != tail) {
214 if (first) {
215 first = false;
216 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800217 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800219 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 cur++;
221 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000222 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223}
224
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000225std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500226 constexpr size_t maxEntries = 50; // max events to print
227 constexpr size_t skipBegin = maxEntries / 2;
228 const size_t skipEnd = queue.size() - maxEntries / 2;
229 // skip from maxEntries / 2 ... size() - maxEntries/2
230 // only print from 0 .. skipBegin and then from skipEnd .. size()
231
232 std::string dump;
233 for (size_t i = 0; i < queue.size(); i++) {
234 const DispatchEntry& entry = *queue[i];
235 if (i >= skipBegin && i < skipEnd) {
236 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
237 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
238 continue;
239 }
240 dump.append(INDENT4);
241 dump += entry.eventEntry->getDescription();
242 dump += StringPrintf(", seq=%" PRIu32
243 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
244 entry.seq, entry.targetFlags, entry.resolvedAction,
245 ns2ms(currentTime - entry.eventEntry->eventTime));
246 if (entry.deliveryTime != 0) {
247 // This entry was delivered, so add information on how long we've been waiting
248 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
249 }
250 dump.append("\n");
251 }
252 return dump;
253}
254
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700255/**
256 * Find the entry in std::unordered_map by key, and return it.
257 * If the entry is not found, return a default constructed entry.
258 *
259 * Useful when the entries are vectors, since an empty vector will be returned
260 * if the entry is not found.
261 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
262 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700263template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000264V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700265 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700266 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800267}
268
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000269bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700270 if (first == second) {
271 return true;
272 }
273
274 if (first == nullptr || second == nullptr) {
275 return false;
276 }
277
278 return first->getToken() == second->getToken();
279}
280
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000281bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000282 if (first == nullptr || second == nullptr) {
283 return false;
284 }
285 return first->applicationInfo.token != nullptr &&
286 first->applicationInfo.token == second->applicationInfo.token;
287}
288
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000289std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
290 std::shared_ptr<EventEntry> eventEntry,
291 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700292 if (inputTarget.useDefaultPointerTransform()) {
293 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700294 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700295 inputTarget.displayTransform,
296 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000297 }
298
299 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
300 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
301
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700302 std::vector<PointerCoords> pointerCoords;
303 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000304
305 // Use the first pointer information to normalize all other pointers. This could be any pointer
306 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700307 // uses the transform for the normalized pointer.
308 const ui::Transform& firstPointerTransform =
309 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
310 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000311
312 // Iterate through all pointers in the event to normalize against the first.
313 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
314 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
315 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700316 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000317
318 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700319 // First, apply the current pointer's transform to update the coordinates into
320 // window space.
321 pointerCoords[pointerIndex].transform(currTransform);
322 // Next, apply the inverse transform of the normalized coordinates so the
323 // current coordinates are transformed into the normalized coordinate space.
324 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000325 }
326
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700327 std::unique_ptr<MotionEntry> combinedMotionEntry =
328 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
329 motionEntry.deviceId, motionEntry.source,
330 motionEntry.displayId, motionEntry.policyFlags,
331 motionEntry.action, motionEntry.actionButton,
332 motionEntry.flags, motionEntry.metaState,
333 motionEntry.buttonState, motionEntry.classification,
334 motionEntry.edgeFlags, motionEntry.xPrecision,
335 motionEntry.yPrecision, motionEntry.xCursorPosition,
336 motionEntry.yCursorPosition, motionEntry.downTime,
337 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000338 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000339
340 if (motionEntry.injectionState) {
341 combinedMotionEntry->injectionState = motionEntry.injectionState;
342 combinedMotionEntry->injectionState->refCount += 1;
343 }
344
345 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700346 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700347 firstPointerTransform, inputTarget.displayTransform,
348 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000349 return dispatchEntry;
350}
351
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000352status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
353 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700354 std::unique_ptr<InputChannel> uniqueServerChannel;
355 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
356
357 serverChannel = std::move(uniqueServerChannel);
358 return result;
359}
360
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500361template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000362bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500363 if (lhs == nullptr && rhs == nullptr) {
364 return true;
365 }
366 if (lhs == nullptr || rhs == nullptr) {
367 return false;
368 }
369 return *lhs == *rhs;
370}
371
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000372KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000373 KeyEvent event;
374 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
375 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
376 entry.repeatCount, entry.downTime, entry.eventTime);
377 return event;
378}
379
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000380bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000381 // Do not keep track of gesture monitors. They receive every event and would disproportionately
382 // affect the statistics.
383 if (connection.monitor) {
384 return false;
385 }
386 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
387 if (!connection.responsive) {
388 return false;
389 }
390 return true;
391}
392
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000393bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000394 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
395 const int32_t& inputEventId = eventEntry.id;
396 if (inputEventId != dispatchEntry.resolvedEventId) {
397 // Event was transmuted
398 return false;
399 }
400 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
401 return false;
402 }
403 // Only track latency for events that originated from hardware
404 if (eventEntry.isSynthesized()) {
405 return false;
406 }
407 const EventEntry::Type& inputEventEntryType = eventEntry.type;
408 if (inputEventEntryType == EventEntry::Type::KEY) {
409 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
410 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
411 return false;
412 }
413 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
414 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
415 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
416 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
417 return false;
418 }
419 } else {
420 // Not a key or a motion
421 return false;
422 }
423 if (!shouldReportMetricsForConnection(connection)) {
424 return false;
425 }
426 return true;
427}
428
Prabir Pradhancef936d2021-07-21 16:17:52 +0000429/**
430 * Connection is responsive if it has no events in the waitQueue that are older than the
431 * current time.
432 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000433bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000434 const nsecs_t currentTime = now();
435 for (const DispatchEntry* entry : connection.waitQueue) {
436 if (entry->timeoutTime < currentTime) {
437 return false;
438 }
439 }
440 return true;
441}
442
Antonio Kantekf16f2832021-09-28 04:39:20 +0000443// Returns true if the event type passed as argument represents a user activity.
444bool isUserActivityEvent(const EventEntry& eventEntry) {
445 switch (eventEntry.type) {
446 case EventEntry::Type::FOCUS:
447 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
448 case EventEntry::Type::DRAG:
449 case EventEntry::Type::TOUCH_MODE_CHANGED:
450 case EventEntry::Type::SENSOR:
451 case EventEntry::Type::CONFIGURATION_CHANGED:
452 return false;
453 case EventEntry::Type::DEVICE_RESET:
454 case EventEntry::Type::KEY:
455 case EventEntry::Type::MOTION:
456 return true;
457 }
458}
459
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800460// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhand65552b2021-10-07 11:23:50 -0700461bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, int32_t x, int32_t y,
462 bool isStylus) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800463 const auto inputConfig = windowInfo.inputConfig;
464 if (windowInfo.displayId != displayId ||
465 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800466 return false;
467 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700468 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800469 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800470 return false;
471 }
Prabir Pradhan06349042022-02-04 09:19:17 -0800472 if (!windowInfo.touchableRegionContainsPoint(x, y)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800473 return false;
474 }
475 return true;
476}
477
Prabir Pradhand65552b2021-10-07 11:23:50 -0700478bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
479 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
480 (entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
481 entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_ERASER);
482}
483
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000484// Determines if the given window can be targeted as InputTarget::FLAG_FOREGROUND.
485// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
486// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
487// be sent to such a window, but it is not a foreground event and doesn't use
488// InputTarget::FLAG_FOREGROUND.
489bool canReceiveForegroundTouches(const WindowInfo& info) {
490 // A non-touchable window can still receive touch events (e.g. in the case of
491 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
492 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
493}
494
Antonio Kantek48710e42022-03-24 14:19:30 -0700495bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
496 if (windowHandle == nullptr) {
497 return false;
498 }
499 const WindowInfo* windowInfo = windowHandle->getInfo();
500 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
501 return true;
502 }
503 return false;
504}
505
Prabir Pradhan5735a322022-04-11 17:23:34 +0000506// Checks targeted injection using the window's owner's uid.
507// Returns an empty string if an entry can be sent to the given window, or an error message if the
508// entry is a targeted injection whose uid target doesn't match the window owner.
509std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
510 const EventEntry& entry) {
511 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
512 // The event was not injected, or the injected event does not target a window.
513 return {};
514 }
515 const int32_t uid = *entry.injectionState->targetUid;
516 if (window == nullptr) {
517 return StringPrintf("No valid window target for injection into uid %d.", uid);
518 }
519 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
520 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
521 "owned by uid %d.",
522 uid, window->getName().c_str(), window->getInfo()->ownerUid);
523 }
524 return {};
525}
526
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000527} // namespace
528
Michael Wrightd02c5b62014-02-10 15:10:22 -0800529// --- InputDispatcher ---
530
Garfield Tan00f511d2019-06-12 16:55:40 -0700531InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800532 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
533
534InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
535 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700536 : mPolicy(policy),
537 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700538 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800539 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700540 mAppSwitchSawKeyDown(false),
541 mAppSwitchDueTime(LONG_LONG_MAX),
542 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800543 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700544 mDispatchEnabled(false),
545 mDispatchFrozen(false),
546 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800547 // mInTouchMode will be initialized by the WindowManager to the default device config.
548 // To avoid leaking stack in case that call never comes, and for tests,
549 // initialize it here anyways.
Antonio Kantekf16f2832021-09-28 04:39:20 +0000550 mInTouchMode(kDefaultInTouchMode),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100551 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000552 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800553 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800554 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000555 mLatencyAggregator(),
Siarhei Vishniakoubd252722022-01-06 03:49:35 -0800556 mLatencyTracker(&mLatencyAggregator) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800557 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800558 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800559
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700560 mWindowInfoListener = new DispatcherWindowListener(*this);
561 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
562
Yi Kong9b14ac62018-07-17 13:48:38 -0700563 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800564
565 policy->getDispatcherConfiguration(&mConfig);
566}
567
568InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000569 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800570
Prabir Pradhancef936d2021-07-21 16:17:52 +0000571 resetKeyRepeatLocked();
572 releasePendingEventLocked();
573 drainInboundQueueLocked();
574 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800575
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000576 while (!mConnectionsByToken.empty()) {
577 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000578 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
579 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800580 }
581}
582
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700583status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700584 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700585 return ALREADY_EXISTS;
586 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700587 mThread = std::make_unique<InputThread>(
588 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
589 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700590}
591
592status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700593 if (mThread && mThread->isCallingThread()) {
594 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700595 return INVALID_OPERATION;
596 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700597 mThread.reset();
598 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700599}
600
Michael Wrightd02c5b62014-02-10 15:10:22 -0800601void InputDispatcher::dispatchOnce() {
602 nsecs_t nextWakeupTime = LONG_LONG_MAX;
603 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800604 std::scoped_lock _l(mLock);
605 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800606
607 // Run a dispatch loop if there are no pending commands.
608 // The dispatch loop might enqueue commands to run afterwards.
609 if (!haveCommandsLocked()) {
610 dispatchOnceInnerLocked(&nextWakeupTime);
611 }
612
613 // Run all pending commands if there are any.
614 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000615 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800616 nextWakeupTime = LONG_LONG_MIN;
617 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800618
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700619 // If we are still waiting for ack on some events,
620 // we might have to wake up earlier to check if an app is anr'ing.
621 const nsecs_t nextAnrCheck = processAnrsLocked();
622 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
623
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800624 // We are about to enter an infinitely long sleep, because we have no commands or
625 // pending or queued events
626 if (nextWakeupTime == LONG_LONG_MAX) {
627 mDispatcherEnteredIdle.notify_all();
628 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629 } // release lock
630
631 // Wait for callback or timeout or wake. (make sure we round up, not down)
632 nsecs_t currentTime = now();
633 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
634 mLooper->pollOnce(timeoutMillis);
635}
636
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700637/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500638 * Raise ANR if there is no focused window.
639 * Before the ANR is raised, do a final state check:
640 * 1. The currently focused application must be the same one we are waiting for.
641 * 2. Ensure we still don't have a focused window.
642 */
643void InputDispatcher::processNoFocusedWindowAnrLocked() {
644 // Check if the application that we are waiting for is still focused.
645 std::shared_ptr<InputApplicationHandle> focusedApplication =
646 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
647 if (focusedApplication == nullptr ||
648 focusedApplication->getApplicationToken() !=
649 mAwaitedFocusedApplication->getApplicationToken()) {
650 // Unexpected because we should have reset the ANR timer when focused application changed
651 ALOGE("Waited for a focused window, but focused application has already changed to %s",
652 focusedApplication->getName().c_str());
653 return; // The focused application has changed.
654 }
655
chaviw98318de2021-05-19 16:45:23 -0500656 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500657 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
658 if (focusedWindowHandle != nullptr) {
659 return; // We now have a focused window. No need for ANR.
660 }
661 onAnrLocked(mAwaitedFocusedApplication);
662}
663
664/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700665 * Check if any of the connections' wait queues have events that are too old.
666 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
667 * Return the time at which we should wake up next.
668 */
669nsecs_t InputDispatcher::processAnrsLocked() {
670 const nsecs_t currentTime = now();
671 nsecs_t nextAnrCheck = LONG_LONG_MAX;
672 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
673 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
674 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500675 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700676 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500677 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700678 return LONG_LONG_MIN;
679 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500680 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700681 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
682 }
683 }
684
685 // Check if any connection ANRs are due
686 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
687 if (currentTime < nextAnrCheck) { // most likely scenario
688 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
689 }
690
691 // If we reached here, we have an unresponsive connection.
692 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
693 if (connection == nullptr) {
694 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
695 return nextAnrCheck;
696 }
697 connection->responsive = false;
698 // Stop waking up for this unresponsive connection
699 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000700 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700701 return LONG_LONG_MIN;
702}
703
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800704std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
705 const sp<Connection>& connection) {
706 if (connection->monitor) {
707 return mMonitorDispatchingTimeout;
708 }
709 const sp<WindowInfoHandle> window =
710 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700711 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500712 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700713 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500714 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700715}
716
Michael Wrightd02c5b62014-02-10 15:10:22 -0800717void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
718 nsecs_t currentTime = now();
719
Jeff Browndc5992e2014-04-11 01:27:26 -0700720 // Reset the key repeat timer whenever normal dispatch is suspended while the
721 // device is in a non-interactive state. This is to ensure that we abort a key
722 // repeat if the device is just coming out of sleep.
723 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800724 resetKeyRepeatLocked();
725 }
726
727 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
728 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100729 if (DEBUG_FOCUS) {
730 ALOGD("Dispatch frozen. Waiting some more.");
731 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800732 return;
733 }
734
735 // Optimize latency of app switches.
736 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
737 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
738 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
739 if (mAppSwitchDueTime < *nextWakeupTime) {
740 *nextWakeupTime = mAppSwitchDueTime;
741 }
742
743 // Ready to start a new event.
744 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700745 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700746 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747 if (isAppSwitchDue) {
748 // The inbound queue is empty so the app switch key we were waiting
749 // for will never arrive. Stop waiting for it.
750 resetPendingAppSwitchLocked(false);
751 isAppSwitchDue = false;
752 }
753
754 // Synthesize a key repeat if appropriate.
755 if (mKeyRepeatState.lastKeyEntry) {
756 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
757 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
758 } else {
759 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
760 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
761 }
762 }
763 }
764
765 // Nothing to do if there is no pending event.
766 if (!mPendingEvent) {
767 return;
768 }
769 } else {
770 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700771 mPendingEvent = mInboundQueue.front();
772 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773 traceInboundQueueLengthLocked();
774 }
775
776 // Poke user activity for this event.
777 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700778 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 }
781
782 // Now we have an event to dispatch.
783 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700784 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800785 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700786 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700788 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800789 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700790 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800791 }
792
793 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700794 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800795 }
796
797 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700798 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700799 const ConfigurationChangedEntry& typedEntry =
800 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700801 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700802 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700803 break;
804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700806 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700807 const DeviceResetEntry& typedEntry =
808 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700809 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700810 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700811 break;
812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100814 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700815 std::shared_ptr<FocusEntry> typedEntry =
816 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100817 dispatchFocusLocked(currentTime, typedEntry);
818 done = true;
819 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
820 break;
821 }
822
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700823 case EventEntry::Type::TOUCH_MODE_CHANGED: {
824 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
825 dispatchTouchModeChangeLocked(currentTime, typedEntry);
826 done = true;
827 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
828 break;
829 }
830
Prabir Pradhan99987712020-11-10 18:43:05 -0800831 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
832 const auto typedEntry =
833 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
834 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
835 done = true;
836 break;
837 }
838
arthurhungb89ccb02020-12-30 16:19:01 +0800839 case EventEntry::Type::DRAG: {
840 std::shared_ptr<DragEntry> typedEntry =
841 std::static_pointer_cast<DragEntry>(mPendingEvent);
842 dispatchDragLocked(currentTime, typedEntry);
843 done = true;
844 break;
845 }
846
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700847 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700848 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700849 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700850 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700851 resetPendingAppSwitchLocked(true);
852 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700853 } else if (dropReason == DropReason::NOT_DROPPED) {
854 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700855 }
856 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700857 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700858 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700859 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700860 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
861 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700862 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700863 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700864 break;
865 }
866
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700867 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700868 std::shared_ptr<MotionEntry> motionEntry =
869 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700870 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
871 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700873 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700874 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700875 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700876 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
877 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700878 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700879 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700880 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881 }
Chris Yef59a2f42020-10-16 12:55:26 -0700882
883 case EventEntry::Type::SENSOR: {
884 std::shared_ptr<SensorEntry> sensorEntry =
885 std::static_pointer_cast<SensorEntry>(mPendingEvent);
886 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
887 dropReason = DropReason::APP_SWITCH;
888 }
889 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
890 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
891 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
892 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
893 dropReason = DropReason::STALE;
894 }
895 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
896 done = true;
897 break;
898 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 }
900
901 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700902 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700903 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 }
Michael Wright3a981722015-06-10 15:26:13 +0100905 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906
907 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700908 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909 }
910}
911
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800912bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
913 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
914}
915
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700916/**
917 * Return true if the events preceding this incoming motion event should be dropped
918 * Return false otherwise (the default behaviour)
919 */
920bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700921 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700922 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700923
924 // Optimize case where the current application is unresponsive and the user
925 // decides to touch a window in a different application.
926 // If the application takes too long to catch up then we drop all events preceding
927 // the touch into the other window.
928 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700929 int32_t displayId = motionEntry.displayId;
930 int32_t x = static_cast<int32_t>(
931 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
932 int32_t y = static_cast<int32_t>(
933 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Prabir Pradhand65552b2021-10-07 11:23:50 -0700934
935 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -0500936 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700937 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700938 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700939 touchedWindowHandle->getApplicationToken() !=
940 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700941 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700942 ALOGI("Pruning input queue because user touched a different application while waiting "
943 "for %s",
944 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700945 return true;
946 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700947
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800948 // Alternatively, maybe there's a spy window that could handle this event.
949 const std::vector<sp<WindowInfoHandle>> touchedSpies =
950 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
951 for (const auto& windowHandle : touchedSpies) {
952 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000953 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800954 // This spy window could take more input. Drop all events preceding this
955 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700956 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800957 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700958 mAwaitedFocusedApplication->getName().c_str());
959 return true;
960 }
961 }
962 }
963
964 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
965 // yet been processed by some connections, the dispatcher will wait for these motion
966 // events to be processed before dispatching the key event. This is because these motion events
967 // may cause a new window to be launched, which the user might expect to receive focus.
968 // To prevent waiting forever for such events, just send the key to the currently focused window
969 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
970 ALOGD("Received a new pointer down event, stop waiting for events to process and "
971 "just send the pending key event to the focused window.");
972 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700973 }
974 return false;
975}
976
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700977bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700978 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700979 mInboundQueue.push_back(std::move(newEntry));
980 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981 traceInboundQueueLengthLocked();
982
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700983 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700984 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +0000985 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
986 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700987 // Optimize app switch latency.
988 // If the application takes too long to catch up then we drop all events preceding
989 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700990 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700991 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700992 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700993 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700994 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700995 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000996 if (DEBUG_APP_SWITCH) {
997 ALOGD("App switch is pending!");
998 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700999 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001000 mAppSwitchSawKeyDown = false;
1001 needWake = true;
1002 }
1003 }
1004 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001005
1006 // If a new up event comes in, and the pending event with same key code has been asked
1007 // to try again later because of the policy. We have to reset the intercept key wake up
1008 // time for it may have been handled in the policy and could be dropped.
1009 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1010 mPendingEvent->type == EventEntry::Type::KEY) {
1011 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1012 if (pendingKey.keyCode == keyEntry.keyCode &&
1013 pendingKey.interceptKeyResult ==
1014 KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1015 pendingKey.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1016 pendingKey.interceptKeyWakeupTime = 0;
1017 needWake = true;
1018 }
1019 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001020 break;
1021 }
1022
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001023 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001024 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1025 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001026 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1027 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001028 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001031 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001032 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001033 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1034 break;
1035 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001036 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001037 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001038 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001039 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001040 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1041 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001042 // nothing to do
1043 break;
1044 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045 }
1046
1047 return needWake;
1048}
1049
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001050void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001051 // Do not store sensor event in recent queue to avoid flooding the queue.
1052 if (entry->type != EventEntry::Type::SENSOR) {
1053 mRecentQueue.push_back(entry);
1054 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001055 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001056 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057 }
1058}
1059
chaviw98318de2021-05-19 16:45:23 -05001060sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1061 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001062 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001063 bool addOutsideTargets,
1064 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001065 if (addOutsideTargets && touchState == nullptr) {
1066 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001069 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001070 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001071 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001072 continue;
1073 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001074
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001075 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001076 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001077 return windowHandle;
1078 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001079
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001080 if (addOutsideTargets &&
1081 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001082 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1083 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084 }
1085 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001086 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001087}
1088
Prabir Pradhand65552b2021-10-07 11:23:50 -07001089std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1090 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001091 // Traverse windows from front to back and gather the touched spy windows.
1092 std::vector<sp<WindowInfoHandle>> spyWindows;
1093 const auto& windowHandles = getWindowHandlesLocked(displayId);
1094 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1095 const WindowInfo& info = *windowHandle->getInfo();
1096
Prabir Pradhand65552b2021-10-07 11:23:50 -07001097 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001098 continue;
1099 }
1100 if (!info.isSpy()) {
1101 // The first touched non-spy window was found, so return the spy windows touched so far.
1102 return spyWindows;
1103 }
1104 spyWindows.push_back(windowHandle);
1105 }
1106 return spyWindows;
1107}
1108
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001109void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001110 const char* reason;
1111 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001112 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001113 if (DEBUG_INBOUND_EVENT_DETAILS) {
1114 ALOGD("Dropped event because policy consumed it.");
1115 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001116 reason = "inbound event was dropped because the policy consumed it";
1117 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001118 case DropReason::DISABLED:
1119 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001120 ALOGI("Dropped event because input dispatch is disabled.");
1121 }
1122 reason = "inbound event was dropped because input dispatch is disabled";
1123 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001124 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001125 ALOGI("Dropped event because of pending overdue app switch.");
1126 reason = "inbound event was dropped because of pending overdue app switch";
1127 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001128 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001129 ALOGI("Dropped event because the current application is not responding and the user "
1130 "has started interacting with a different application.");
1131 reason = "inbound event was dropped because the current application is not responding "
1132 "and the user has started interacting with a different application";
1133 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001134 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001135 ALOGI("Dropped event because it is stale.");
1136 reason = "inbound event was dropped because it is stale";
1137 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001138 case DropReason::NO_POINTER_CAPTURE:
1139 ALOGI("Dropped event because there is no window with Pointer Capture.");
1140 reason = "inbound event was dropped because there is no window with Pointer Capture";
1141 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001142 case DropReason::NOT_DROPPED: {
1143 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001144 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001145 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146 }
1147
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001148 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001149 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001150 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1151 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001152 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001154 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001155 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1156 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001157 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1158 synthesizeCancelationEventsForAllConnectionsLocked(options);
1159 } else {
1160 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1161 synthesizeCancelationEventsForAllConnectionsLocked(options);
1162 }
1163 break;
1164 }
Chris Yef59a2f42020-10-16 12:55:26 -07001165 case EventEntry::Type::SENSOR: {
1166 break;
1167 }
arthurhungb89ccb02020-12-30 16:19:01 +08001168 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1169 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001170 break;
1171 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001172 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001173 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001174 case EventEntry::Type::CONFIGURATION_CHANGED:
1175 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001176 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001177 break;
1178 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179 }
1180}
1181
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001182static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001183 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1184 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185}
1186
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001187bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1188 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1189 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1190 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191}
1192
1193bool InputDispatcher::isAppSwitchPendingLocked() {
1194 return mAppSwitchDueTime != LONG_LONG_MAX;
1195}
1196
1197void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1198 mAppSwitchDueTime = LONG_LONG_MAX;
1199
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001200 if (DEBUG_APP_SWITCH) {
1201 if (handled) {
1202 ALOGD("App switch has arrived.");
1203 } else {
1204 ALOGD("App switch was abandoned.");
1205 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207}
1208
Michael Wrightd02c5b62014-02-10 15:10:22 -08001209bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001210 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211}
1212
Prabir Pradhancef936d2021-07-21 16:17:52 +00001213bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001214 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215 return false;
1216 }
1217
1218 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001219 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001220 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001221 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1222 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001223 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224 return true;
1225}
1226
Prabir Pradhancef936d2021-07-21 16:17:52 +00001227void InputDispatcher::postCommandLocked(Command&& command) {
1228 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229}
1230
1231void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001232 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001233 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001234 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 releaseInboundEventLocked(entry);
1236 }
1237 traceInboundQueueLengthLocked();
1238}
1239
1240void InputDispatcher::releasePendingEventLocked() {
1241 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001243 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 }
1245}
1246
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001247void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001249 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001250 if (DEBUG_DISPATCH_CYCLE) {
1251 ALOGD("Injected inbound event was dropped.");
1252 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001253 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254 }
1255 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001256 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257 }
1258 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259}
1260
1261void InputDispatcher::resetKeyRepeatLocked() {
1262 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001263 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 }
1265}
1266
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001267std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1268 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001269
Michael Wright2e732952014-09-24 13:26:59 -07001270 uint32_t policyFlags = entry->policyFlags &
1271 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001273 std::shared_ptr<KeyEntry> newEntry =
1274 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1275 entry->source, entry->displayId, policyFlags, entry->action,
1276 entry->flags, entry->keyCode, entry->scanCode,
1277 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001279 newEntry->syntheticRepeat = true;
1280 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001281 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001282 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283}
1284
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001285bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001286 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001287 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1288 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290
1291 // Reset key repeating in case a keyboard device was added or removed or something.
1292 resetKeyRepeatLocked();
1293
1294 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001295 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1296 scoped_unlock unlock(mLock);
1297 mPolicy->notifyConfigurationChanged(eventTime);
1298 };
1299 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001300 return true;
1301}
1302
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001303bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1304 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001305 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1306 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1307 entry.deviceId);
1308 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309
liushenxiang42232912021-05-21 20:24:09 +08001310 // Reset key repeating in case a keyboard device was disabled or enabled.
1311 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1312 resetKeyRepeatLocked();
1313 }
1314
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001315 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001316 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317 synthesizeCancelationEventsForAllConnectionsLocked(options);
1318 return true;
1319}
1320
Vishnu Nairad321cd2020-08-20 16:40:21 -07001321void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001322 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001323 if (mPendingEvent != nullptr) {
1324 // Move the pending event to the front of the queue. This will give the chance
1325 // for the pending event to get dispatched to the newly focused window
1326 mInboundQueue.push_front(mPendingEvent);
1327 mPendingEvent = nullptr;
1328 }
1329
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001330 std::unique_ptr<FocusEntry> focusEntry =
1331 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1332 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001333
1334 // This event should go to the front of the queue, but behind all other focus events
1335 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001336 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001337 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001338 [](const std::shared_ptr<EventEntry>& event) {
1339 return event->type == EventEntry::Type::FOCUS;
1340 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001341
1342 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001343 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001344}
1345
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001346void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001347 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001348 if (channel == nullptr) {
1349 return; // Window has gone away
1350 }
1351 InputTarget target;
1352 target.inputChannel = channel;
1353 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1354 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001355 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1356 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001357 std::string reason = std::string("reason=").append(entry->reason);
1358 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001359 dispatchEventLocked(currentTime, entry, {target});
1360}
1361
Prabir Pradhan99987712020-11-10 18:43:05 -08001362void InputDispatcher::dispatchPointerCaptureChangedLocked(
1363 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1364 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001365 dropReason = DropReason::NOT_DROPPED;
1366
Prabir Pradhan99987712020-11-10 18:43:05 -08001367 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001368 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001369
1370 if (entry->pointerCaptureRequest.enable) {
1371 // Enable Pointer Capture.
1372 if (haveWindowWithPointerCapture &&
1373 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001374 // This can happen if pointer capture is disabled and re-enabled before we notify the
1375 // app of the state change, so there is no need to notify the app.
1376 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1377 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001378 }
1379 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001380 // This can happen if a window requests capture and immediately releases capture.
1381 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001382 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001383 return;
1384 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001385 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1386 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1387 return;
1388 }
1389
Vishnu Nairc519ff72021-01-21 08:23:08 -08001390 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001391 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1392 mWindowTokenWithPointerCapture = token;
1393 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001394 // Disable Pointer Capture.
1395 // We do not check if the sequence number matches for requests to disable Pointer Capture
1396 // for two reasons:
1397 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1398 // to disable capture with the same sequence number: one generated by
1399 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1400 // Capture being disabled in InputReader.
1401 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1402 // actual Pointer Capture state that affects events being generated by input devices is
1403 // in InputReader.
1404 if (!haveWindowWithPointerCapture) {
1405 // Pointer capture was already forcefully disabled because of focus change.
1406 dropReason = DropReason::NOT_DROPPED;
1407 return;
1408 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001409 token = mWindowTokenWithPointerCapture;
1410 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001411 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001412 setPointerCaptureLocked(false);
1413 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001414 }
1415
1416 auto channel = getInputChannelLocked(token);
1417 if (channel == nullptr) {
1418 // Window has gone away, clean up Pointer Capture state.
1419 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001420 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001421 setPointerCaptureLocked(false);
1422 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001423 return;
1424 }
1425 InputTarget target;
1426 target.inputChannel = channel;
1427 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1428 entry->dispatchInProgress = true;
1429 dispatchEventLocked(currentTime, entry, {target});
1430
1431 dropReason = DropReason::NOT_DROPPED;
1432}
1433
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001434void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1435 const std::shared_ptr<TouchModeEntry>& entry) {
1436 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1437 getWindowHandlesLocked(mFocusedDisplayId);
1438 if (windowHandles.empty()) {
1439 return;
1440 }
1441 const std::vector<InputTarget> inputTargets =
1442 getInputTargetsFromWindowHandlesLocked(windowHandles);
1443 if (inputTargets.empty()) {
1444 return;
1445 }
1446 entry->dispatchInProgress = true;
1447 dispatchEventLocked(currentTime, entry, inputTargets);
1448}
1449
1450std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1451 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1452 std::vector<InputTarget> inputTargets;
1453 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1454 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1455 const sp<IBinder>& token = handle->getToken();
1456 if (token == nullptr) {
1457 continue;
1458 }
1459 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1460 if (channel == nullptr) {
1461 continue; // Window has gone away
1462 }
1463 InputTarget target;
1464 target.inputChannel = channel;
1465 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1466 inputTargets.push_back(target);
1467 }
1468 return inputTargets;
1469}
1470
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001471bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001472 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001474 if (!entry->dispatchInProgress) {
1475 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1476 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1477 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1478 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001479 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 // We have seen two identical key downs in a row which indicates that the device
1481 // driver is automatically generating key repeats itself. We take note of the
1482 // repeat here, but we disable our own next key repeat timer since it is clear that
1483 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001484 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1485 // Make sure we don't get key down from a different device. If a different
1486 // device Id has same key pressed down, the new device Id will replace the
1487 // current one to hold the key repeat with repeat count reset.
1488 // In the future when got a KEY_UP on the device id, drop it and do not
1489 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001490 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1491 resetKeyRepeatLocked();
1492 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1493 } else {
1494 // Not a repeat. Save key down state in case we do see a repeat later.
1495 resetKeyRepeatLocked();
1496 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1497 }
1498 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001499 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1500 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001501 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001502 if (DEBUG_INBOUND_EVENT_DETAILS) {
1503 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1504 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001505 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506 resetKeyRepeatLocked();
1507 }
1508
1509 if (entry->repeatCount == 1) {
1510 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1511 } else {
1512 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1513 }
1514
1515 entry->dispatchInProgress = true;
1516
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001517 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518 }
1519
1520 // Handle case where the policy asked us to try again later last time.
1521 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1522 if (currentTime < entry->interceptKeyWakeupTime) {
1523 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1524 *nextWakeupTime = entry->interceptKeyWakeupTime;
1525 }
1526 return false; // wait until next wakeup
1527 }
1528 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1529 entry->interceptKeyWakeupTime = 0;
1530 }
1531
1532 // Give the policy a chance to intercept the key.
1533 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1534 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001535 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001536 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001537
1538 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1539 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1540 };
1541 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542 return false; // wait for the command to run
1543 } else {
1544 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1545 }
1546 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001547 if (*dropReason == DropReason::NOT_DROPPED) {
1548 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549 }
1550 }
1551
1552 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001553 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001554 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001555 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1556 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001557 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558 return true;
1559 }
1560
1561 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001562 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001563 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001564 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001565 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001566 return false;
1567 }
1568
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001569 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001570 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571 return true;
1572 }
1573
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001574 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001575 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576
1577 // Dispatch the key.
1578 dispatchEventLocked(currentTime, entry, inputTargets);
1579 return true;
1580}
1581
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001582void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001583 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1584 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1585 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1586 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1587 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1588 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1589 entry.metaState, entry.repeatCount, entry.downTime);
1590 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591}
1592
Prabir Pradhancef936d2021-07-21 16:17:52 +00001593void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1594 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001595 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001596 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1597 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1598 "source=0x%x, sensorType=%s",
1599 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001600 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001601 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001602 auto command = [this, entry]() REQUIRES(mLock) {
1603 scoped_unlock unlock(mLock);
1604
1605 if (entry->accuracyChanged) {
1606 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1607 }
1608 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1609 entry->hwTimestamp, entry->values);
1610 };
1611 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001612}
1613
1614bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001615 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1616 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001617 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001618 }
Chris Yef59a2f42020-10-16 12:55:26 -07001619 { // acquire lock
1620 std::scoped_lock _l(mLock);
1621
1622 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1623 std::shared_ptr<EventEntry> entry = *it;
1624 if (entry->type == EventEntry::Type::SENSOR) {
1625 it = mInboundQueue.erase(it);
1626 releaseInboundEventLocked(entry);
1627 }
1628 }
1629 }
1630 return true;
1631}
1632
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001633bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001634 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001635 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001637 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001638 entry->dispatchInProgress = true;
1639
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001640 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641 }
1642
1643 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001644 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001645 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001646 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1647 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001648 return true;
1649 }
1650
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001651 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652
1653 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001654 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001655
1656 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001657 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658 if (isPointerEvent) {
1659 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001660 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001661 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001662 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001663 } else {
1664 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001665 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001666 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001668 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 return false;
1670 }
1671
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001672 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001673 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001674 return true;
1675 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001676 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001677 CancelationOptions::Mode mode(isPointerEvent
1678 ? CancelationOptions::CANCEL_POINTER_EVENTS
1679 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1680 CancelationOptions options(mode, "input event injection failed");
1681 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 return true;
1683 }
1684
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001685 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001686 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001687
1688 // Dispatch the motion.
1689 if (conflictingPointerActions) {
1690 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001691 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001692 synthesizeCancelationEventsForAllConnectionsLocked(options);
1693 }
1694 dispatchEventLocked(currentTime, entry, inputTargets);
1695 return true;
1696}
1697
chaviw98318de2021-05-19 16:45:23 -05001698void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001699 bool isExiting, const int32_t rawX,
1700 const int32_t rawY) {
1701 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001702 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001703 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1704 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001705
1706 enqueueInboundEventLocked(std::move(dragEntry));
1707}
1708
1709void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1710 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1711 if (channel == nullptr) {
1712 return; // Window has gone away
1713 }
1714 InputTarget target;
1715 target.inputChannel = channel;
1716 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1717 entry->dispatchInProgress = true;
1718 dispatchEventLocked(currentTime, entry, {target});
1719}
1720
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001721void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001722 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1723 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1724 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001725 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001726 "metaState=0x%x, buttonState=0x%x,"
1727 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1728 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001729 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1730 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1731 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001732
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001733 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1734 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1735 "x=%f, y=%f, pressure=%f, size=%f, "
1736 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1737 "orientation=%f",
1738 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1739 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1740 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1741 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1742 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1743 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1744 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1745 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1746 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1747 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1748 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750}
1751
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001752void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1753 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001754 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001755 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001756 if (DEBUG_DISPATCH_CYCLE) {
1757 ALOGD("dispatchEventToCurrentInputTargets");
1758 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001760 updateInteractionTokensLocked(*eventEntry, inputTargets);
1761
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1763
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001764 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001766 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001767 sp<Connection> connection =
1768 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001769 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001770 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001771 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001772 if (DEBUG_FOCUS) {
1773 ALOGD("Dropping event delivery to target with channel '%s' because it "
1774 "is no longer registered with the input dispatcher.",
1775 inputTarget.inputChannel->getName().c_str());
1776 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777 }
1778 }
1779}
1780
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001781void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1782 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1783 // If the policy decides to close the app, we will get a channel removal event via
1784 // unregisterInputChannel, and will clean up the connection that way. We are already not
1785 // sending new pointers to the connection when it blocked, but focused events will continue to
1786 // pile up.
1787 ALOGW("Canceling events for %s because it is unresponsive",
1788 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001789 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001790 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1791 "application not responding");
1792 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 }
1794}
1795
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001796void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001797 if (DEBUG_FOCUS) {
1798 ALOGD("Resetting ANR timeouts.");
1799 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800
1801 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001802 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001803 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001804}
1805
Tiger Huang721e26f2018-07-24 22:26:19 +08001806/**
1807 * Get the display id that the given event should go to. If this event specifies a valid display id,
1808 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1809 * Focused display is the display that the user most recently interacted with.
1810 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001811int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001812 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001813 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001814 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001815 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1816 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001817 break;
1818 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001819 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001820 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1821 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001822 break;
1823 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001824 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001825 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001826 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001827 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001828 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001829 case EventEntry::Type::SENSOR:
1830 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001831 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001832 return ADISPLAY_ID_NONE;
1833 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001834 }
1835 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1836}
1837
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001838bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1839 const char* focusedWindowName) {
1840 if (mAnrTracker.empty()) {
1841 // already processed all events that we waited for
1842 mKeyIsWaitingForEventsTimeout = std::nullopt;
1843 return false;
1844 }
1845
1846 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1847 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001848 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001849 mKeyIsWaitingForEventsTimeout = currentTime +
1850 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1851 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001852 return true;
1853 }
1854
1855 // We still have pending events, and already started the timer
1856 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1857 return true; // Still waiting
1858 }
1859
1860 // Waited too long, and some connection still hasn't processed all motions
1861 // Just send the key to the focused window
1862 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1863 focusedWindowName);
1864 mKeyIsWaitingForEventsTimeout = std::nullopt;
1865 return false;
1866}
1867
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001868InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1869 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1870 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001871 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001872
Tiger Huang721e26f2018-07-24 22:26:19 +08001873 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001874 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001875 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001876 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1877
Michael Wrightd02c5b62014-02-10 15:10:22 -08001878 // If there is no currently focused window and no focused application
1879 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001880 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1881 ALOGI("Dropping %s event because there is no focused window or focused application in "
1882 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001883 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001884 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885 }
1886
Vishnu Nair062a8672021-09-03 16:07:44 -07001887 // Drop key events if requested by input feature
1888 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1889 return InputEventInjectionResult::FAILED;
1890 }
1891
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001892 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1893 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1894 // start interacting with another application via touch (app switch). This code can be removed
1895 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1896 // an app is expected to have a focused window.
1897 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1898 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1899 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001900 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1901 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1902 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001903 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001904 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001905 ALOGW("Waiting because no window has focus but %s may eventually add a "
1906 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001907 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001908 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001909 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001910 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1911 // Already raised ANR. Drop the event
1912 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001913 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001914 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001915 } else {
1916 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001917 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001918 }
1919 }
1920
1921 // we have a valid, non-null focused window
1922 resetNoFocusedWindowTimeoutLocked();
1923
Prabir Pradhan5735a322022-04-11 17:23:34 +00001924 // Verify targeted injection.
1925 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
1926 ALOGW("Dropping injected event: %s", (*err).c_str());
1927 return InputEventInjectionResult::TARGET_MISMATCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928 }
1929
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001930 if (focusedWindowHandle->getInfo()->inputConfig.test(
1931 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001932 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001933 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001934 }
1935
1936 // If the event is a key event, then we must wait for all previous events to
1937 // complete before delivering it because previous events may have the
1938 // side-effect of transferring focus to a different window and we want to
1939 // ensure that the following keys are sent to the new window.
1940 //
1941 // Suppose the user touches a button in a window then immediately presses "A".
1942 // If the button causes a pop-up window to appear then we want to ensure that
1943 // the "A" key is delivered to the new pop-up window. This is because users
1944 // often anticipate pending UI changes when typing on a keyboard.
1945 // To obtain this behavior, we must serialize key events with respect to all
1946 // prior input events.
1947 if (entry.type == EventEntry::Type::KEY) {
1948 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1949 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001950 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952 }
1953
1954 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001955 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001956 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1957 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001958
1959 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001960 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961}
1962
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001963/**
1964 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1965 * that are currently unresponsive.
1966 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001967std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1968 const std::vector<Monitor>& monitors) const {
1969 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001970 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001971 [this](const Monitor& monitor) REQUIRES(mLock) {
1972 sp<Connection> connection =
1973 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001974 if (connection == nullptr) {
1975 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001976 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001977 return false;
1978 }
1979 if (!connection->responsive) {
1980 ALOGW("Unresponsive monitor %s will not get the new gesture",
1981 connection->inputChannel->getName().c_str());
1982 return false;
1983 }
1984 return true;
1985 });
1986 return responsiveMonitors;
1987}
1988
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001989InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
1990 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
1991 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001992 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001993
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 // For security reasons, we defer updating the touch state until we are sure that
1995 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001996 const int32_t displayId = entry.displayId;
1997 const int32_t action = entry.action;
1998 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999
2000 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002001 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
chaviw98318de2021-05-19 16:45:23 -05002002 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2003 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002005 // Copy current touch state into tempTouchState.
2006 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2007 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002008 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002009 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002010 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2011 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002012 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002013 }
2014
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002015 bool isSplit = tempTouchState.split;
2016 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2017 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2018 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002019
2020 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2021 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2022 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2023 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2024 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002025 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002026 bool wrongDevice = false;
2027 if (newGesture) {
2028 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002029 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002030 ALOGI("Dropping event because a pointer for a different device is already down "
2031 "in display %" PRId32,
2032 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002033 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002034 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002035 switchedDevice = false;
2036 wrongDevice = true;
2037 goto Failed;
2038 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002039 tempTouchState.reset();
2040 tempTouchState.down = down;
2041 tempTouchState.deviceId = entry.deviceId;
2042 tempTouchState.source = entry.source;
2043 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002045 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002046 ALOGI("Dropping move event because a pointer for a different device is already active "
2047 "in display %" PRId32,
2048 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002049 // TODO: test multiple simultaneous input streams.
Prabir Pradhan5735a322022-04-11 17:23:34 +00002050 injectionResult = InputEventInjectionResult::FAILED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002051 switchedDevice = false;
2052 wrongDevice = true;
2053 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054 }
2055
2056 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2057 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2058
Garfield Tan00f511d2019-06-12 16:55:40 -07002059 int32_t x;
2060 int32_t y;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002061 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002062 // Always dispatch mouse events to cursor position.
2063 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002064 x = int32_t(entry.xCursorPosition);
2065 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07002066 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002067 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
2068 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07002069 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002070 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002071 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002072 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002073 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002074
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002076 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002077 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2078 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002080 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002081 }
2082
Prabir Pradhan5735a322022-04-11 17:23:34 +00002083 // Verify targeted injection.
2084 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2085 ALOGW("Dropping injected touch event: %s", (*err).c_str());
2086 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2087 newTouchedWindowHandle = nullptr;
2088 goto Failed;
2089 }
2090
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002091 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002092 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002093 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2094 // New window supports splitting, but we should never split mouse events.
2095 isSplit = !isFromMouse;
2096 } else if (isSplit) {
2097 // New window does not support splitting but we have already split events.
2098 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002099 newTouchedWindowHandle = nullptr;
2100 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002101 } else {
2102 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002103 // be delivered to a new window which supports split touch. Pointers from a mouse device
2104 // should never be split.
2105 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002106 }
2107
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002108 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002109 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002110 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2111 newHoverWindowHandle = nullptr;
2112 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002113 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002114 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002115 }
2116
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002117 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002118 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002119 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002120 // Process the foreground window first so that it is the first to receive the event.
2121 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002122 }
2123
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002124 if (newTouchedWindows.empty()) {
2125 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2126 x, y, displayId);
2127 injectionResult = InputEventInjectionResult::FAILED;
2128 goto Failed;
2129 }
2130
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002131 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2132 const WindowInfo& info = *windowHandle->getInfo();
2133
Prabir Pradhan5735a322022-04-11 17:23:34 +00002134 // Skip spy window targets that are not valid for targeted injection.
2135 if (const auto err = verifyTargetedInjection(windowHandle, entry); err) {
2136 continue;
2137 }
2138
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002139 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002140 ALOGI("Not sending touch event to %s because it is paused",
2141 windowHandle->getName().c_str());
2142 continue;
2143 }
2144
2145 // Ensure the window has a connection and the connection is responsive
2146 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2147 if (!isResponsive) {
2148 ALOGW("Not sending touch gesture to %s because it is not responsive",
2149 windowHandle->getName().c_str());
2150 continue;
2151 }
2152
2153 // Drop events that can't be trusted due to occlusion
Hani Kazmi3ce9c3a2022-04-25 09:40:23 +00002154 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(windowHandle, x, y);
2155 if (!isTouchTrustedLocked(occlusionInfo)) {
2156 if (DEBUG_TOUCH_OCCLUSION) {
2157 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
2158 for (const auto& log : occlusionInfo.debugInfo) {
2159 ALOGD("%s", log.c_str());
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002160 }
2161 }
Hani Kazmi3ce9c3a2022-04-25 09:40:23 +00002162 ALOGW("Dropping untrusted touch event due to %s/%d",
2163 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2164 continue;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002165 }
2166
2167 // Drop touch events if requested by input feature
2168 if (shouldDropInput(entry, windowHandle)) {
2169 continue;
2170 }
2171
2172 // Set target flags.
2173 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2174
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002175 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2176 // There should only be one touched window that can be "foreground" for the pointer.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002177 targetFlags |= InputTarget::FLAG_FOREGROUND;
2178 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002179
2180 if (isSplit) {
2181 targetFlags |= InputTarget::FLAG_SPLIT;
2182 }
2183 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2184 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2185 } else if (isWindowObscuredLocked(windowHandle)) {
2186 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2187 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002188
2189 // Update the temporary touch state.
2190 BitSet32 pointerIds;
2191 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002192 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00002193 pointerIds.markBit(pointerId);
2194 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002195
2196 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198 } else {
2199 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2200
2201 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002202 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002203 if (DEBUG_FOCUS) {
2204 ALOGD("Dropping event because the pointer is not down or we previously "
2205 "dropped the pointer down event in display %" PRId32,
2206 displayId);
2207 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002208 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209 goto Failed;
2210 }
2211
arthurhung6d4bed92021-03-17 11:59:33 +08002212 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002213
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002215 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002216 tempTouchState.isSlippery()) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002217 const int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
2218 const int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219
Prabir Pradhand65552b2021-10-07 11:23:50 -07002220 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002221 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002222 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002223 newTouchedWindowHandle =
2224 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002225
Prabir Pradhan5735a322022-04-11 17:23:34 +00002226 // Verify targeted injection.
2227 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2228 ALOGW("Dropping injected event: %s", (*err).c_str());
2229 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2230 newTouchedWindowHandle = nullptr;
2231 goto Failed;
2232 }
2233
Vishnu Nair062a8672021-09-03 16:07:44 -07002234 // Drop touch events if requested by input feature
2235 if (newTouchedWindowHandle != nullptr &&
2236 shouldDropInput(entry, newTouchedWindowHandle)) {
2237 newTouchedWindowHandle = nullptr;
2238 }
2239
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002240 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2241 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002242 if (DEBUG_FOCUS) {
2243 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2244 oldTouchedWindowHandle->getName().c_str(),
2245 newTouchedWindowHandle->getName().c_str(), displayId);
2246 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002248 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2249 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2250 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251
2252 // Make a slippery entrance into the new window.
2253 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002254 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255 }
2256
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002257 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
2258 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
2259 targetFlags |= InputTarget::FLAG_FOREGROUND;
2260 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 if (isSplit) {
2262 targetFlags |= InputTarget::FLAG_SPLIT;
2263 }
2264 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2265 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002266 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2267 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268 }
2269
2270 BitSet32 pointerIds;
2271 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002272 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002273 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002274 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275 }
2276 }
2277 }
2278
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002279 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002281 // Let the previous window know that the hover sequence is over, unless we already did
2282 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002283 if (mLastHoverWindowHandle != nullptr &&
2284 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2285 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002286 if (DEBUG_HOVER) {
2287 ALOGD("Sending hover exit event to window %s.",
2288 mLastHoverWindowHandle->getName().c_str());
2289 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002290 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2291 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002292 }
2293
Garfield Tandf26e862020-07-01 20:18:19 -07002294 // Let the new window know that the hover sequence is starting, unless we already did it
2295 // when dispatching it as is to newTouchedWindowHandle.
2296 if (newHoverWindowHandle != nullptr &&
2297 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2298 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002299 if (DEBUG_HOVER) {
2300 ALOGD("Sending hover enter event to window %s.",
2301 newHoverWindowHandle->getName().c_str());
2302 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002303 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2304 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2305 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 }
2307 }
2308
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002309 // Ensure that we have at least one foreground window or at least one window that cannot be a
2310 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2311 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2312 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002313 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2314 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002315 return !canReceiveForegroundTouches(
2316 *touchedWindow.windowHandle->getInfo()) ||
2317 (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002318 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002319 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2320 displayId, entry.getDescription().c_str());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002321 injectionResult = InputEventInjectionResult::FAILED;
2322 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323 }
2324
Prabir Pradhan5735a322022-04-11 17:23:34 +00002325 // Ensure that all touched windows are valid for injection.
2326 if (entry.injectionState != nullptr) {
2327 std::string errs;
2328 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
2329 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2330 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2331 // dispatched to any uid, since the coords will be zeroed out later.
2332 continue;
2333 }
2334 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2335 if (err) errs += "\n - " + *err;
2336 }
2337 if (!errs.empty()) {
2338 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2339 "%d:%s",
2340 *entry.injectionState->targetUid, errs.c_str());
2341 injectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2342 goto Failed;
2343 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002344 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002345
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346 // Check whether windows listening for outside touches are owned by the same UID. If it is
2347 // set the policy flag that we will not reveal coordinate information to this window.
2348 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002349 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002350 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002351 if (foregroundWindowHandle) {
2352 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002353 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002354 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002355 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2356 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2357 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002358 InputTarget::FLAG_ZERO_COORDS,
2359 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002361 }
2362 }
2363 }
2364 }
2365
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366 // If this is the first pointer going down and the touched window has a wallpaper
2367 // then also add the touched wallpaper windows so they are locked in for the duration
2368 // of the touch gesture.
2369 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2370 // engine only supports touch events. We would need to add a mechanism similar
2371 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2372 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002373 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002374 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002375 if (foregroundWindowHandle &&
2376 foregroundWindowHandle->getInfo()->inputConfig.test(
2377 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002378 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002379 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002380 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2381 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002382 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002383 windowHandle->getInfo()->inputConfig.test(
2384 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002385 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002386 .addOrUpdateWindow(windowHandle,
2387 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2388 InputTarget::
2389 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2390 InputTarget::FLAG_DISPATCH_AS_IS,
2391 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392 }
2393 }
2394 }
2395 }
2396
2397 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002398 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002400 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002401 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002402 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 }
2404
2405 // Drop the outside or hover touch windows since we will not care about them
2406 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002407 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002408
2409Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002411 if (!wrongDevice) {
2412 if (switchedDevice) {
2413 if (DEBUG_FOCUS) {
2414 ALOGD("Conflicting pointer actions: Switched to a different device.");
2415 }
2416 *outConflictingPointerActions = true;
2417 }
2418
2419 if (isHoverAction) {
2420 // Started hovering, therefore no longer down.
2421 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002422 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002423 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2424 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002425 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002426 *outConflictingPointerActions = true;
2427 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002428 tempTouchState.reset();
2429 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2430 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2431 tempTouchState.deviceId = entry.deviceId;
2432 tempTouchState.source = entry.source;
2433 tempTouchState.displayId = displayId;
2434 }
2435 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2436 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2437 // All pointers up or canceled.
2438 tempTouchState.reset();
2439 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2440 // First pointer went down.
2441 if (oldState && oldState->down) {
2442 if (DEBUG_FOCUS) {
2443 ALOGD("Conflicting pointer actions: Down received while already down.");
2444 }
2445 *outConflictingPointerActions = true;
2446 }
2447 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2448 // One pointer went up.
2449 if (isSplit) {
2450 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2451 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002453 for (size_t i = 0; i < tempTouchState.windows.size();) {
2454 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2455 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
2456 touchedWindow.pointerIds.clearBit(pointerId);
2457 if (touchedWindow.pointerIds.isEmpty()) {
2458 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2459 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002460 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002461 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002462 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002464 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002465 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002466
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002467 // Save changes unless the action was scroll in which case the temporary touch
2468 // state was only valid for this one action.
2469 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2470 if (tempTouchState.displayId >= 0) {
2471 mTouchStatesByDisplay[displayId] = tempTouchState;
2472 } else {
2473 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002475 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002476
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002477 // Update hover state.
2478 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002479 }
2480
Michael Wrightd02c5b62014-02-10 15:10:22 -08002481 return injectionResult;
2482}
2483
arthurhung6d4bed92021-03-17 11:59:33 +08002484void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002485 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2486 // have an explicit reason to support it.
2487 constexpr bool isStylus = false;
2488
chaviw98318de2021-05-19 16:45:23 -05002489 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002490 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002491 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002492 if (dropWindow) {
2493 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002494 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002495 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002496 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002497 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002498 }
2499 mDragState.reset();
2500}
2501
2502void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung54745652022-04-20 07:17:41 +00002503 if (!mDragState) {
arthurhungb89ccb02020-12-30 16:19:01 +08002504 return;
2505 }
2506
arthurhung6d4bed92021-03-17 11:59:33 +08002507 if (!mDragState->isStartDrag) {
2508 mDragState->isStartDrag = true;
2509 mDragState->isStylusButtonDownAtStart =
2510 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2511 }
2512
Arthur Hung54745652022-04-20 07:17:41 +00002513 // Find the pointer index by id.
2514 int32_t pointerIndex = 0;
2515 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2516 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2517 if (pointerProperties.id == mDragState->pointerId) {
2518 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002519 }
Arthur Hung54745652022-04-20 07:17:41 +00002520 }
arthurhung6d4bed92021-03-17 11:59:33 +08002521
Arthur Hung54745652022-04-20 07:17:41 +00002522 if (uint32_t(pointerIndex) == entry.pointerCount) {
2523 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002524 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002525 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002526 return;
2527 }
2528
2529 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2530 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2531 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2532
2533 switch (maskedAction) {
2534 case AMOTION_EVENT_ACTION_MOVE: {
2535 // Handle the special case : stylus button no longer pressed.
2536 bool isStylusButtonDown =
2537 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2538 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2539 finishDragAndDrop(entry.displayId, x, y);
2540 return;
2541 }
2542
2543 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2544 // until we have an explicit reason to support it.
2545 constexpr bool isStylus = false;
2546
2547 const sp<WindowInfoHandle> hoverWindowHandle =
2548 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2549 isStylus, false /*addOutsideTargets*/,
2550 true /*ignoreDragWindow*/);
2551 // enqueue drag exit if needed.
2552 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2553 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2554 if (mDragState->dragHoverWindowHandle != nullptr) {
2555 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2556 y);
2557 }
2558 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2559 }
2560 // enqueue drag location if needed.
2561 if (hoverWindowHandle != nullptr) {
2562 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2563 }
2564 break;
2565 }
2566
2567 case AMOTION_EVENT_ACTION_POINTER_UP:
2568 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2569 break;
2570 }
2571 // The drag pointer is up.
2572 [[fallthrough]];
2573 case AMOTION_EVENT_ACTION_UP:
2574 finishDragAndDrop(entry.displayId, x, y);
2575 break;
2576 case AMOTION_EVENT_ACTION_CANCEL: {
2577 ALOGD("Receiving cancel when drag and drop.");
2578 sendDropWindowCommandLocked(nullptr, 0, 0);
2579 mDragState.reset();
2580 break;
2581 }
arthurhungb89ccb02020-12-30 16:19:01 +08002582 }
2583}
2584
chaviw98318de2021-05-19 16:45:23 -05002585void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002586 int32_t targetFlags, BitSet32 pointerIds,
2587 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002588 std::vector<InputTarget>::iterator it =
2589 std::find_if(inputTargets.begin(), inputTargets.end(),
2590 [&windowHandle](const InputTarget& inputTarget) {
2591 return inputTarget.inputChannel->getConnectionToken() ==
2592 windowHandle->getToken();
2593 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002594
chaviw98318de2021-05-19 16:45:23 -05002595 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002596
2597 if (it == inputTargets.end()) {
2598 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002599 std::shared_ptr<InputChannel> inputChannel =
2600 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002601 if (inputChannel == nullptr) {
2602 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2603 return;
2604 }
2605 inputTarget.inputChannel = inputChannel;
2606 inputTarget.flags = targetFlags;
2607 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002608 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2609 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002610 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002611 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002612 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002613 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002614 inputTargets.push_back(inputTarget);
2615 it = inputTargets.end() - 1;
2616 }
2617
2618 ALOG_ASSERT(it->flags == targetFlags);
2619 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2620
chaviw1ff3d1e2020-07-01 15:53:47 -07002621 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002622}
2623
Michael Wright3dd60e22019-03-27 22:06:44 +00002624void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002625 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002626 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2627 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002628
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002629 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2630 InputTarget target;
2631 target.inputChannel = monitor.inputChannel;
2632 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2633 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2634 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002635 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002636 target.setDefaultPointerTransform(target.displayTransform);
2637 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002638 }
2639}
2640
Robert Carrc9bf1d32020-04-13 17:21:08 -07002641/**
2642 * Indicate whether one window handle should be considered as obscuring
2643 * another window handle. We only check a few preconditions. Actually
2644 * checking the bounds is left to the caller.
2645 */
chaviw98318de2021-05-19 16:45:23 -05002646static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2647 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002648 // Compare by token so cloned layers aren't counted
2649 if (haveSameToken(windowHandle, otherHandle)) {
2650 return false;
2651 }
2652 auto info = windowHandle->getInfo();
2653 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002654 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002655 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002656 } else if (otherInfo->alpha == 0 &&
2657 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002658 // Those act as if they were invisible, so we don't need to flag them.
2659 // We do want to potentially flag touchable windows even if they have 0
2660 // opacity, since they can consume touches and alter the effects of the
2661 // user interaction (eg. apps that rely on
2662 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2663 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2664 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002665 } else if (info->ownerUid == otherInfo->ownerUid) {
2666 // If ownerUid is the same we don't generate occlusion events as there
2667 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002668 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002669 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002670 return false;
2671 } else if (otherInfo->displayId != info->displayId) {
2672 return false;
2673 }
2674 return true;
2675}
2676
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002677/**
2678 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2679 * untrusted, one should check:
2680 *
2681 * 1. If result.hasBlockingOcclusion is true.
2682 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2683 * BLOCK_UNTRUSTED.
2684 *
2685 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2686 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2687 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2688 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2689 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2690 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2691 *
2692 * If neither of those is true, then it means the touch can be allowed.
2693 */
2694InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002695 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2696 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002697 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002698 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002699 TouchOcclusionInfo info;
2700 info.hasBlockingOcclusion = false;
2701 info.obscuringOpacity = 0;
2702 info.obscuringUid = -1;
2703 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002704 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002705 if (windowHandle == otherHandle) {
2706 break; // All future windows are below us. Exit early.
2707 }
chaviw98318de2021-05-19 16:45:23 -05002708 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002709 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2710 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002711 if (DEBUG_TOUCH_OCCLUSION) {
2712 info.debugInfo.push_back(
2713 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2714 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002715 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2716 // we perform the checks below to see if the touch can be propagated or not based on the
2717 // window's touch occlusion mode
2718 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2719 info.hasBlockingOcclusion = true;
2720 info.obscuringUid = otherInfo->ownerUid;
2721 info.obscuringPackage = otherInfo->packageName;
2722 break;
2723 }
2724 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2725 uint32_t uid = otherInfo->ownerUid;
2726 float opacity =
2727 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2728 // Given windows A and B:
2729 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2730 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2731 opacityByUid[uid] = opacity;
2732 if (opacity > info.obscuringOpacity) {
2733 info.obscuringOpacity = opacity;
2734 info.obscuringUid = uid;
2735 info.obscuringPackage = otherInfo->packageName;
2736 }
2737 }
2738 }
2739 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002740 if (DEBUG_TOUCH_OCCLUSION) {
2741 info.debugInfo.push_back(
2742 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2743 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002744 return info;
2745}
2746
chaviw98318de2021-05-19 16:45:23 -05002747std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002748 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002749 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2750 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2751 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2752 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002753 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2754 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2755 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2756 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2757 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002758 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002759 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002760}
2761
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002762bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2763 if (occlusionInfo.hasBlockingOcclusion) {
2764 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2765 occlusionInfo.obscuringUid);
2766 return false;
2767 }
2768 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2769 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2770 "%.2f, maximum allowed = %.2f)",
2771 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2772 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2773 return false;
2774 }
2775 return true;
2776}
2777
chaviw98318de2021-05-19 16:45:23 -05002778bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002779 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002781 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2782 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002783 if (windowHandle == otherHandle) {
2784 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002785 }
chaviw98318de2021-05-19 16:45:23 -05002786 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002787 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002788 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002789 return true;
2790 }
2791 }
2792 return false;
2793}
2794
chaviw98318de2021-05-19 16:45:23 -05002795bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002796 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002797 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2798 const WindowInfo* windowInfo = windowHandle->getInfo();
2799 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002800 if (windowHandle == otherHandle) {
2801 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002802 }
chaviw98318de2021-05-19 16:45:23 -05002803 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002804 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002805 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002806 return true;
2807 }
2808 }
2809 return false;
2810}
2811
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002812std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002813 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002814 if (applicationHandle != nullptr) {
2815 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002816 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002817 } else {
2818 return applicationHandle->getName();
2819 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002820 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002821 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002823 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824 }
2825}
2826
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002827void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002828 if (!isUserActivityEvent(eventEntry)) {
2829 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002830 return;
2831 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002832 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002833 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002834 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002835 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002836 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002837 if (DEBUG_DISPATCH_CYCLE) {
2838 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2839 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002840 return;
2841 }
2842 }
2843
2844 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002845 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002846 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002847 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2848 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002849 return;
2850 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002852 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002853 eventType = USER_ACTIVITY_EVENT_TOUCH;
2854 }
2855 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002856 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002857 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002858 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2859 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002860 return;
2861 }
2862 eventType = USER_ACTIVITY_EVENT_BUTTON;
2863 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002865 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002866 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002867 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002868 break;
2869 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002870 }
2871
Prabir Pradhancef936d2021-07-21 16:17:52 +00002872 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2873 REQUIRES(mLock) {
2874 scoped_unlock unlock(mLock);
2875 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2876 };
2877 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002878}
2879
2880void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002881 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002882 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002883 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002884 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002885 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002886 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002887 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002888 ATRACE_NAME(message.c_str());
2889 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002890 if (DEBUG_DISPATCH_CYCLE) {
2891 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2892 "globalScaleFactor=%f, pointerIds=0x%x %s",
2893 connection->getInputChannelName().c_str(), inputTarget.flags,
2894 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2895 inputTarget.getPointerInfoString().c_str());
2896 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002897
2898 // Skip this event if the connection status is not normal.
2899 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002900 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002901 if (DEBUG_DISPATCH_CYCLE) {
2902 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002903 connection->getInputChannelName().c_str(),
2904 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002905 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002906 return;
2907 }
2908
2909 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002910 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2911 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2912 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002913 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002915 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002916 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002917 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002918 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919 if (!splitMotionEntry) {
2920 return; // split event was dropped
2921 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002922 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2923 std::string reason = std::string("reason=pointer cancel on split window");
2924 android_log_event_list(LOGTAG_INPUT_CANCEL)
2925 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2926 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002927 if (DEBUG_FOCUS) {
2928 ALOGD("channel '%s' ~ Split motion event.",
2929 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002930 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002931 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002932 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2933 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002934 return;
2935 }
2936 }
2937
2938 // Not splitting. Enqueue dispatch entries for the event as is.
2939 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2940}
2941
2942void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002943 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002944 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002945 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002946 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002947 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002948 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002949 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002950 ATRACE_NAME(message.c_str());
2951 }
2952
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002953 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002954
2955 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002956 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002957 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002958 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002959 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002960 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002961 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002962 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002963 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002964 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002965 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002966 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002967 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002968
2969 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002970 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002971 startDispatchCycleLocked(currentTime, connection);
2972 }
2973}
2974
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002975void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002976 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002977 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002978 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002979 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002980 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2981 connection->getInputChannelName().c_str(),
2982 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002983 ATRACE_NAME(message.c_str());
2984 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002985 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002986 if (!(inputTargetFlags & dispatchMode)) {
2987 return;
2988 }
2989 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2990
2991 // This is a new event.
2992 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002993 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002994 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002995
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002996 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2997 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002998 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002999 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003000 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003001 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003002 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003003 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003004 dispatchEntry->resolvedAction = keyEntry.action;
3005 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003006
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003007 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3008 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003009 if (DEBUG_DISPATCH_CYCLE) {
3010 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3011 "event",
3012 connection->getInputChannelName().c_str());
3013 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003014 return; // skip the inconsistent event
3015 }
3016 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003018
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003019 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003020 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003021 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3022 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3023 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3024 static_cast<int32_t>(IdGenerator::Source::OTHER);
3025 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003026 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3027 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3028 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3029 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3030 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3031 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3032 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3033 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3034 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3035 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3036 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003037 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003038 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003039 }
3040 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003041 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3042 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003043 if (DEBUG_DISPATCH_CYCLE) {
3044 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3045 "enter event",
3046 connection->getInputChannelName().c_str());
3047 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003048 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3049 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003050 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3051 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003053 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003054 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3055 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3056 }
3057 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3058 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3059 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003060
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003061 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3062 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003063 if (DEBUG_DISPATCH_CYCLE) {
3064 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3065 "event",
3066 connection->getInputChannelName().c_str());
3067 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003068 return; // skip the inconsistent event
3069 }
3070
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003071 dispatchEntry->resolvedEventId =
3072 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3073 ? mIdGenerator.nextId()
3074 : motionEntry.id;
3075 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3076 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3077 ") to MotionEvent(id=0x%" PRIx32 ").",
3078 motionEntry.id, dispatchEntry->resolvedEventId);
3079 ATRACE_NAME(message.c_str());
3080 }
3081
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003082 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3083 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3084 // Skip reporting pointer down outside focus to the policy.
3085 break;
3086 }
3087
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003088 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003089 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003090
3091 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003092 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003093 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003094 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003095 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3096 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003097 break;
3098 }
Chris Yef59a2f42020-10-16 12:55:26 -07003099 case EventEntry::Type::SENSOR: {
3100 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3101 break;
3102 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003103 case EventEntry::Type::CONFIGURATION_CHANGED:
3104 case EventEntry::Type::DEVICE_RESET: {
3105 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003106 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003107 break;
3108 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003109 }
3110
3111 // Remember that we are waiting for this dispatch to complete.
3112 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003113 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003114 }
3115
3116 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003117 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003118 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003119}
3120
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003121/**
3122 * This function is purely for debugging. It helps us understand where the user interaction
3123 * was taking place. For example, if user is touching launcher, we will see a log that user
3124 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3125 * We will see both launcher and wallpaper in that list.
3126 * Once the interaction with a particular set of connections starts, no new logs will be printed
3127 * until the set of interacted connections changes.
3128 *
3129 * The following items are skipped, to reduce the logspam:
3130 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3131 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3132 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3133 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3134 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003135 */
3136void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3137 const std::vector<InputTarget>& targets) {
3138 // Skip ACTION_UP events, and all events other than keys and motions
3139 if (entry.type == EventEntry::Type::KEY) {
3140 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3141 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3142 return;
3143 }
3144 } else if (entry.type == EventEntry::Type::MOTION) {
3145 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3146 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3147 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3148 return;
3149 }
3150 } else {
3151 return; // Not a key or a motion
3152 }
3153
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003154 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003155 std::vector<sp<Connection>> newConnections;
3156 for (const InputTarget& target : targets) {
3157 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3158 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3159 continue; // Skip windows that receive ACTION_OUTSIDE
3160 }
3161
3162 sp<IBinder> token = target.inputChannel->getConnectionToken();
3163 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003164 if (connection == nullptr) {
3165 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003166 }
3167 newConnectionTokens.insert(std::move(token));
3168 newConnections.emplace_back(connection);
3169 }
3170 if (newConnectionTokens == mInteractionConnectionTokens) {
3171 return; // no change
3172 }
3173 mInteractionConnectionTokens = newConnectionTokens;
3174
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003175 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003176 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003177 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003178 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003179 std::string message = "Interaction with: " + targetList;
3180 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003181 message += "<none>";
3182 }
3183 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3184}
3185
chaviwfd6d3512019-03-25 13:23:49 -07003186void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003187 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003188 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003189 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3190 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003191 return;
3192 }
3193
Vishnu Nairc519ff72021-01-21 08:23:08 -08003194 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003195 if (focusedToken == token) {
3196 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003197 return;
3198 }
3199
Prabir Pradhancef936d2021-07-21 16:17:52 +00003200 auto command = [this, token]() REQUIRES(mLock) {
3201 scoped_unlock unlock(mLock);
3202 mPolicy->onPointerDownOutsideFocus(token);
3203 };
3204 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205}
3206
3207void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003208 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003209 if (ATRACE_ENABLED()) {
3210 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003211 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003212 ATRACE_NAME(message.c_str());
3213 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003214 if (DEBUG_DISPATCH_CYCLE) {
3215 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3216 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003218 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003219 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003220 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003221 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003222 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003223
3224 // Publish the event.
3225 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003226 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3227 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003228 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003229 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3230 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003232 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003233 status = connection->inputPublisher
3234 .publishKeyEvent(dispatchEntry->seq,
3235 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3236 keyEntry.source, keyEntry.displayId,
3237 std::move(hmac), dispatchEntry->resolvedAction,
3238 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3239 keyEntry.scanCode, keyEntry.metaState,
3240 keyEntry.repeatCount, keyEntry.downTime,
3241 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003242 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243 }
3244
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003245 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003246 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003248 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003249 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003250
chaviw82357092020-01-28 13:13:06 -08003251 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003252 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003253 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3254 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003255 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003256 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3257 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003258 // Don't apply window scale here since we don't want scale to affect raw
3259 // coordinates. The scale will be sent back to the client and applied
3260 // later when requesting relative coordinates.
3261 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3262 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003263 }
3264 usingCoords = scaledCoords;
3265 }
3266 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003267 // We don't want the dispatch target to know.
3268 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003269 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003270 scaledCoords[i].clear();
3271 }
3272 usingCoords = scaledCoords;
3273 }
3274 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003275
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003276 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003277
3278 // Publish the motion event.
3279 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003280 .publishMotionEvent(dispatchEntry->seq,
3281 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003282 motionEntry.deviceId, motionEntry.source,
3283 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003284 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003285 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003286 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003287 motionEntry.edgeFlags, motionEntry.metaState,
3288 motionEntry.buttonState,
3289 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003290 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003291 motionEntry.xPrecision, motionEntry.yPrecision,
3292 motionEntry.xCursorPosition,
3293 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003294 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003295 motionEntry.downTime, motionEntry.eventTime,
3296 motionEntry.pointerCount,
3297 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003298 break;
3299 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003300
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003301 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003302 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003303 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003304 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003305 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003306 break;
3307 }
3308
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003309 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3310 const TouchModeEntry& touchModeEntry =
3311 static_cast<const TouchModeEntry&>(eventEntry);
3312 status = connection->inputPublisher
3313 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3314 touchModeEntry.inTouchMode);
3315
3316 break;
3317 }
3318
Prabir Pradhan99987712020-11-10 18:43:05 -08003319 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3320 const auto& captureEntry =
3321 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3322 status = connection->inputPublisher
3323 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003324 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003325 break;
3326 }
3327
arthurhungb89ccb02020-12-30 16:19:01 +08003328 case EventEntry::Type::DRAG: {
3329 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3330 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3331 dragEntry.id, dragEntry.x,
3332 dragEntry.y,
3333 dragEntry.isExiting);
3334 break;
3335 }
3336
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003337 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003338 case EventEntry::Type::DEVICE_RESET:
3339 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003340 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003341 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003342 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003343 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003344 }
3345
3346 // Check the result.
3347 if (status) {
3348 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003349 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003351 "This is unexpected because the wait queue is empty, so the pipe "
3352 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003353 "event to it, status=%s(%d)",
3354 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3355 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003356 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3357 } else {
3358 // Pipe is full and we are waiting for the app to finish process some events
3359 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003360 if (DEBUG_DISPATCH_CYCLE) {
3361 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3362 "waiting for the application to catch up",
3363 connection->getInputChannelName().c_str());
3364 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365 }
3366 } else {
3367 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003368 "status=%s(%d)",
3369 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3370 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3372 }
3373 return;
3374 }
3375
3376 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003377 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3378 connection->outboundQueue.end(),
3379 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003380 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003381 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003382 if (connection->responsive) {
3383 mAnrTracker.insert(dispatchEntry->timeoutTime,
3384 connection->inputChannel->getConnectionToken());
3385 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003386 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387 }
3388}
3389
chaviw09c8d2d2020-08-24 15:48:26 -07003390std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3391 size_t size;
3392 switch (event.type) {
3393 case VerifiedInputEvent::Type::KEY: {
3394 size = sizeof(VerifiedKeyEvent);
3395 break;
3396 }
3397 case VerifiedInputEvent::Type::MOTION: {
3398 size = sizeof(VerifiedMotionEvent);
3399 break;
3400 }
3401 }
3402 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3403 return mHmacKeyManager.sign(start, size);
3404}
3405
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003406const std::array<uint8_t, 32> InputDispatcher::getSignature(
3407 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003408 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3409 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003410 // Only sign events up and down events as the purely move events
3411 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003412 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003413 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003414
3415 VerifiedMotionEvent verifiedEvent =
3416 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3417 verifiedEvent.actionMasked = actionMasked;
3418 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3419 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003420}
3421
3422const std::array<uint8_t, 32> InputDispatcher::getSignature(
3423 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3424 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3425 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3426 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003427 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003428}
3429
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003431 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003432 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003433 if (DEBUG_DISPATCH_CYCLE) {
3434 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3435 connection->getInputChannelName().c_str(), seq, toString(handled));
3436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003438 if (connection->status == Connection::Status::BROKEN ||
3439 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003440 return;
3441 }
3442
3443 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003444 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3445 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3446 };
3447 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448}
3449
3450void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003451 const sp<Connection>& connection,
3452 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003453 if (DEBUG_DISPATCH_CYCLE) {
3454 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3455 connection->getInputChannelName().c_str(), toString(notify));
3456 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003457
3458 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003459 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003460 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003461 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003462 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003463
3464 // The connection appears to be unrecoverably broken.
3465 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003466 if (connection->status == Connection::Status::NORMAL) {
3467 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468
3469 if (notify) {
3470 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003471 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3472 connection->getInputChannelName().c_str());
3473
3474 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003475 scoped_unlock unlock(mLock);
3476 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3477 };
3478 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479 }
3480 }
3481}
3482
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003483void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3484 while (!queue.empty()) {
3485 DispatchEntry* dispatchEntry = queue.front();
3486 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003487 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003488 }
3489}
3490
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003491void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003493 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494 }
3495 delete dispatchEntry;
3496}
3497
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003498int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3499 std::scoped_lock _l(mLock);
3500 sp<Connection> connection = getConnectionLocked(connectionToken);
3501 if (connection == nullptr) {
3502 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3503 connectionToken.get(), events);
3504 return 0; // remove the callback
3505 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003507 bool notify;
3508 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3509 if (!(events & ALOOPER_EVENT_INPUT)) {
3510 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3511 "events=0x%x",
3512 connection->getInputChannelName().c_str(), events);
3513 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514 }
3515
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003516 nsecs_t currentTime = now();
3517 bool gotOne = false;
3518 status_t status = OK;
3519 for (;;) {
3520 Result<InputPublisher::ConsumerResponse> result =
3521 connection->inputPublisher.receiveConsumerResponse();
3522 if (!result.ok()) {
3523 status = result.error().code();
3524 break;
3525 }
3526
3527 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3528 const InputPublisher::Finished& finish =
3529 std::get<InputPublisher::Finished>(*result);
3530 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3531 finish.consumeTime);
3532 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003533 if (shouldReportMetricsForConnection(*connection)) {
3534 const InputPublisher::Timeline& timeline =
3535 std::get<InputPublisher::Timeline>(*result);
3536 mLatencyTracker
3537 .trackGraphicsLatency(timeline.inputEventId,
3538 connection->inputChannel->getConnectionToken(),
3539 std::move(timeline.graphicsTimeline));
3540 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003541 }
3542 gotOne = true;
3543 }
3544 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003545 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003546 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003547 return 1;
3548 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003549 }
3550
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003551 notify = status != DEAD_OBJECT || !connection->monitor;
3552 if (notify) {
3553 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3554 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3555 status);
3556 }
3557 } else {
3558 // Monitor channels are never explicitly unregistered.
3559 // We do it automatically when the remote endpoint is closed so don't warn about them.
3560 const bool stillHaveWindowHandle =
3561 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3562 notify = !connection->monitor && stillHaveWindowHandle;
3563 if (notify) {
3564 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3565 connection->getInputChannelName().c_str(), events);
3566 }
3567 }
3568
3569 // Remove the channel.
3570 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3571 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572}
3573
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003574void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003575 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003576 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003577 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003578 }
3579}
3580
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003581void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003582 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003583 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003584 for (const Monitor& monitor : monitors) {
3585 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003586 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003587 }
3588}
3589
Michael Wrightd02c5b62014-02-10 15:10:22 -08003590void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003591 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003592 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003593 if (connection == nullptr) {
3594 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003596
3597 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598}
3599
3600void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3601 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003602 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603 return;
3604 }
3605
3606 nsecs_t currentTime = now();
3607
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003608 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003609 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003611 if (cancelationEvents.empty()) {
3612 return;
3613 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003614 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3615 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3616 "with reality: %s, mode=%d.",
3617 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3618 options.mode);
3619 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003620
Arthur Hungb3307ee2021-10-14 10:57:37 +00003621 std::string reason = std::string("reason=").append(options.reason);
3622 android_log_event_list(LOGTAG_INPUT_CANCEL)
3623 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3624
Svet Ganov5d3bc372020-01-26 23:11:07 -08003625 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003626 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003627 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3628 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003629 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003630 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003631 target.globalScaleFactor = windowInfo->globalScaleFactor;
3632 }
3633 target.inputChannel = connection->inputChannel;
3634 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3635
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003636 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003637 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003638 switch (cancelationEventEntry->type) {
3639 case EventEntry::Type::KEY: {
3640 logOutboundKeyDetails("cancel - ",
3641 static_cast<const KeyEntry&>(*cancelationEventEntry));
3642 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003644 case EventEntry::Type::MOTION: {
3645 logOutboundMotionDetails("cancel - ",
3646 static_cast<const MotionEntry&>(*cancelationEventEntry));
3647 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003649 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003650 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003651 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3652 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003653 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003654 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003655 break;
3656 }
3657 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003658 case EventEntry::Type::DEVICE_RESET:
3659 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003660 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003661 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003662 break;
3663 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664 }
3665
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003666 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3667 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003668 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003669
3670 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003671}
3672
Svet Ganov5d3bc372020-01-26 23:11:07 -08003673void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3674 const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003675 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003676 return;
3677 }
3678
3679 nsecs_t currentTime = now();
3680
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003681 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003682 connection->inputState.synthesizePointerDownEvents(currentTime);
3683
3684 if (downEvents.empty()) {
3685 return;
3686 }
3687
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003688 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003689 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3690 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003691 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003692
3693 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003694 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003695 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3696 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003697 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003698 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003699 target.globalScaleFactor = windowInfo->globalScaleFactor;
3700 }
3701 target.inputChannel = connection->inputChannel;
3702 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3703
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003704 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003705 switch (downEventEntry->type) {
3706 case EventEntry::Type::MOTION: {
3707 logOutboundMotionDetails("down - ",
3708 static_cast<const MotionEntry&>(*downEventEntry));
3709 break;
3710 }
3711
3712 case EventEntry::Type::KEY:
3713 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003714 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003715 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003716 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003717 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003718 case EventEntry::Type::SENSOR:
3719 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003720 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003721 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003722 break;
3723 }
3724 }
3725
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003726 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3727 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003728 }
3729
3730 startDispatchCycleLocked(currentTime, connection);
3731}
3732
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003733std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3734 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003735 ALOG_ASSERT(pointerIds.value != 0);
3736
3737 uint32_t splitPointerIndexMap[MAX_POINTERS];
3738 PointerProperties splitPointerProperties[MAX_POINTERS];
3739 PointerCoords splitPointerCoords[MAX_POINTERS];
3740
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003741 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742 uint32_t splitPointerCount = 0;
3743
3744 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003745 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003746 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003747 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003748 uint32_t pointerId = uint32_t(pointerProperties.id);
3749 if (pointerIds.hasBit(pointerId)) {
3750 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3751 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3752 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003753 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754 splitPointerCount += 1;
3755 }
3756 }
3757
3758 if (splitPointerCount != pointerIds.count()) {
3759 // This is bad. We are missing some of the pointers that we expected to deliver.
3760 // Most likely this indicates that we received an ACTION_MOVE events that has
3761 // different pointer ids than we expected based on the previous ACTION_DOWN
3762 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3763 // in this way.
3764 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003765 "we expected there to be %d pointers. This probably means we received "
3766 "a broken sequence of pointer ids from the input device.",
3767 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003768 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769 }
3770
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003771 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003773 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3774 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3776 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003777 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003778 uint32_t pointerId = uint32_t(pointerProperties.id);
3779 if (pointerIds.hasBit(pointerId)) {
3780 if (pointerIds.count() == 1) {
3781 // The first/last pointer went down/up.
3782 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003783 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003784 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3785 ? AMOTION_EVENT_ACTION_CANCEL
3786 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787 } else {
3788 // A secondary pointer went down/up.
3789 uint32_t splitPointerIndex = 0;
3790 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3791 splitPointerIndex += 1;
3792 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003793 action = maskedAction |
3794 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795 }
3796 } else {
3797 // An unrelated pointer changed.
3798 action = AMOTION_EVENT_ACTION_MOVE;
3799 }
3800 }
3801
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003802 int32_t newId = mIdGenerator.nextId();
3803 if (ATRACE_ENABLED()) {
3804 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3805 ") to MotionEvent(id=0x%" PRIx32 ").",
3806 originalMotionEntry.id, newId);
3807 ATRACE_NAME(message.c_str());
3808 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003809 std::unique_ptr<MotionEntry> splitMotionEntry =
3810 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3811 originalMotionEntry.deviceId, originalMotionEntry.source,
3812 originalMotionEntry.displayId,
3813 originalMotionEntry.policyFlags, action,
3814 originalMotionEntry.actionButton,
3815 originalMotionEntry.flags, originalMotionEntry.metaState,
3816 originalMotionEntry.buttonState,
3817 originalMotionEntry.classification,
3818 originalMotionEntry.edgeFlags,
3819 originalMotionEntry.xPrecision,
3820 originalMotionEntry.yPrecision,
3821 originalMotionEntry.xCursorPosition,
3822 originalMotionEntry.yCursorPosition,
3823 originalMotionEntry.downTime, splitPointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00003824 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003825
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003826 if (originalMotionEntry.injectionState) {
3827 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828 splitMotionEntry->injectionState->refCount += 1;
3829 }
3830
3831 return splitMotionEntry;
3832}
3833
3834void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003835 if (DEBUG_INBOUND_EVENT_DETAILS) {
3836 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838
Antonio Kantekf16f2832021-09-28 04:39:20 +00003839 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003840 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003841 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003842
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003843 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3844 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3845 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003846 } // release lock
3847
3848 if (needWake) {
3849 mLooper->wake();
3850 }
3851}
3852
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003853/**
3854 * If one of the meta shortcuts is detected, process them here:
3855 * Meta + Backspace -> generate BACK
3856 * Meta + Enter -> generate HOME
3857 * This will potentially overwrite keyCode and metaState.
3858 */
3859void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003860 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003861 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3862 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3863 if (keyCode == AKEYCODE_DEL) {
3864 newKeyCode = AKEYCODE_BACK;
3865 } else if (keyCode == AKEYCODE_ENTER) {
3866 newKeyCode = AKEYCODE_HOME;
3867 }
3868 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003869 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003870 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003871 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003872 keyCode = newKeyCode;
3873 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3874 }
3875 } else if (action == AKEY_EVENT_ACTION_UP) {
3876 // In order to maintain a consistent stream of up and down events, check to see if the key
3877 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3878 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003879 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003880 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003881 auto replacementIt = mReplacedKeys.find(replacement);
3882 if (replacementIt != mReplacedKeys.end()) {
3883 keyCode = replacementIt->second;
3884 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003885 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3886 }
3887 }
3888}
3889
Michael Wrightd02c5b62014-02-10 15:10:22 -08003890void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003891 if (DEBUG_INBOUND_EVENT_DETAILS) {
3892 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3893 "policyFlags=0x%x, action=0x%x, "
3894 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3895 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3896 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3897 args->downTime);
3898 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899 if (!validateKeyEvent(args->action)) {
3900 return;
3901 }
3902
3903 uint32_t policyFlags = args->policyFlags;
3904 int32_t flags = args->flags;
3905 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003906 // InputDispatcher tracks and generates key repeats on behalf of
3907 // whatever notifies it, so repeatCount should always be set to 0
3908 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003909 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3910 policyFlags |= POLICY_FLAG_VIRTUAL;
3911 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3912 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003913 if (policyFlags & POLICY_FLAG_FUNCTION) {
3914 metaState |= AMETA_FUNCTION_ON;
3915 }
3916
3917 policyFlags |= POLICY_FLAG_TRUSTED;
3918
Michael Wright78f24442014-08-06 15:55:28 -07003919 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003920 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003921
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003923 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003924 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3925 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926
Michael Wright2b3c3302018-03-02 17:19:13 +00003927 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003929 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3930 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003931 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003932 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003933
Antonio Kantekf16f2832021-09-28 04:39:20 +00003934 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935 { // acquire lock
3936 mLock.lock();
3937
3938 if (shouldSendKeyToInputFilterLocked(args)) {
3939 mLock.unlock();
3940
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003941 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003942 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3943 return; // event was consumed by the filter
3944 }
3945
3946 mLock.lock();
3947 }
3948
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003949 std::unique_ptr<KeyEntry> newEntry =
3950 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3951 args->displayId, policyFlags, args->action, flags,
3952 keyCode, args->scanCode, metaState, repeatCount,
3953 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003955 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956 mLock.unlock();
3957 } // release lock
3958
3959 if (needWake) {
3960 mLooper->wake();
3961 }
3962}
3963
3964bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3965 return mInputFilterEnabled;
3966}
3967
3968void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003969 if (DEBUG_INBOUND_EVENT_DETAILS) {
3970 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3971 "displayId=%" PRId32 ", policyFlags=0x%x, "
3972 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3973 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3974 "yCursorPosition=%f, downTime=%" PRId64,
3975 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3976 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3977 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3978 args->xCursorPosition, args->yCursorPosition, args->downTime);
3979 for (uint32_t i = 0; i < args->pointerCount; i++) {
3980 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3981 "x=%f, y=%f, pressure=%f, size=%f, "
3982 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3983 "orientation=%f",
3984 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3985 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3986 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3987 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3988 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3989 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3990 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3991 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3992 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3993 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
3994 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003996 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3997 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998 return;
3999 }
4000
4001 uint32_t policyFlags = args->policyFlags;
4002 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004003
4004 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004005 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004006 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4007 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004008 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004009 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004010
Antonio Kantekf16f2832021-09-28 04:39:20 +00004011 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012 { // acquire lock
4013 mLock.lock();
4014
4015 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004016 ui::Transform displayTransform;
4017 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4018 displayTransform = it->second.transform;
4019 }
4020
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021 mLock.unlock();
4022
4023 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004024 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4025 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004026 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004027 displayTransform, args->xPrecision, args->yPrecision,
4028 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004029 args->downTime, args->eventTime, args->pointerCount,
4030 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004031
4032 policyFlags |= POLICY_FLAG_FILTERED;
4033 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4034 return; // event was consumed by the filter
4035 }
4036
4037 mLock.lock();
4038 }
4039
4040 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004041 std::unique_ptr<MotionEntry> newEntry =
4042 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4043 args->source, args->displayId, policyFlags,
4044 args->action, args->actionButton, args->flags,
4045 args->metaState, args->buttonState,
4046 args->classification, args->edgeFlags,
4047 args->xPrecision, args->yPrecision,
4048 args->xCursorPosition, args->yCursorPosition,
4049 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004050 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004052 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4053 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4054 !mInputFilterEnabled) {
4055 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4056 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4057 }
4058
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004059 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060 mLock.unlock();
4061 } // release lock
4062
4063 if (needWake) {
4064 mLooper->wake();
4065 }
4066}
4067
Chris Yef59a2f42020-10-16 12:55:26 -07004068void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004069 if (DEBUG_INBOUND_EVENT_DETAILS) {
4070 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4071 " sensorType=%s",
4072 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004073 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004074 }
Chris Yef59a2f42020-10-16 12:55:26 -07004075
Antonio Kantekf16f2832021-09-28 04:39:20 +00004076 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004077 { // acquire lock
4078 mLock.lock();
4079
4080 // Just enqueue a new sensor event.
4081 std::unique_ptr<SensorEntry> newEntry =
4082 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4083 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4084 args->sensorType, args->accuracy,
4085 args->accuracyChanged, args->values);
4086
4087 needWake = enqueueInboundEventLocked(std::move(newEntry));
4088 mLock.unlock();
4089 } // release lock
4090
4091 if (needWake) {
4092 mLooper->wake();
4093 }
4094}
4095
Chris Yefb552902021-02-03 17:18:37 -08004096void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004097 if (DEBUG_INBOUND_EVENT_DETAILS) {
4098 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4099 args->deviceId, args->isOn);
4100 }
Chris Yefb552902021-02-03 17:18:37 -08004101 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4102}
4103
Michael Wrightd02c5b62014-02-10 15:10:22 -08004104bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004105 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004106}
4107
4108void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004109 if (DEBUG_INBOUND_EVENT_DETAILS) {
4110 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4111 "switchMask=0x%08x",
4112 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4113 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114
4115 uint32_t policyFlags = args->policyFlags;
4116 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004117 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118}
4119
4120void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004121 if (DEBUG_INBOUND_EVENT_DETAILS) {
4122 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4123 args->deviceId);
4124 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125
Antonio Kantekf16f2832021-09-28 04:39:20 +00004126 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004128 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004130 std::unique_ptr<DeviceResetEntry> newEntry =
4131 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4132 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133 } // release lock
4134
4135 if (needWake) {
4136 mLooper->wake();
4137 }
4138}
4139
Prabir Pradhan7e186182020-11-10 13:56:45 -08004140void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004141 if (DEBUG_INBOUND_EVENT_DETAILS) {
4142 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004143 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004144 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004145
Antonio Kantekf16f2832021-09-28 04:39:20 +00004146 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004147 { // acquire lock
4148 std::scoped_lock _l(mLock);
4149 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004150 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004151 needWake = enqueueInboundEventLocked(std::move(entry));
4152 } // release lock
4153
4154 if (needWake) {
4155 mLooper->wake();
4156 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004157}
4158
Prabir Pradhan5735a322022-04-11 17:23:34 +00004159InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4160 std::optional<int32_t> targetUid,
4161 InputEventInjectionSync syncMode,
4162 std::chrono::milliseconds timeout,
4163 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004164 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004165 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4166 "policyFlags=0x%08x",
4167 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4168 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004169 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004170 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171
Prabir Pradhan5735a322022-04-11 17:23:34 +00004172 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004174 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004175 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4176 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4177 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4178 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4179 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004180 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004181 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004182 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004183 }
4184
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004185 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004187 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004188 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4189 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004190 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004191 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004192 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004194 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004195 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4196 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4197 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004198 int32_t keyCode = incomingKey.getKeyCode();
4199 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004200 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004201 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004202 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004203 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004204 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4205 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4206 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004208 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4209 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004210 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004211
4212 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4213 android::base::Timer t;
4214 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4215 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4216 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4217 std::to_string(t.duration().count()).c_str());
4218 }
4219 }
4220
4221 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004222 std::unique_ptr<KeyEntry> injectedEntry =
4223 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004224 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004225 incomingKey.getDisplayId(), policyFlags, action,
4226 flags, keyCode, incomingKey.getScanCode(), metaState,
4227 incomingKey.getRepeatCount(),
4228 incomingKey.getDownTime());
4229 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004230 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231 }
4232
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004233 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004234 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004235 const int32_t action = motionEvent.getAction();
4236 const bool isPointerEvent =
4237 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4238 // If a pointer event has no displayId specified, inject it to the default display.
4239 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4240 ? ADISPLAY_ID_DEFAULT
4241 : event->getDisplayId();
4242 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004243 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004244 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004245 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004246 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004247 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004248 }
4249
4250 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004251 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004252 android::base::Timer t;
4253 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4254 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4255 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4256 std::to_string(t.duration().count()).c_str());
4257 }
4258 }
4259
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004260 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4261 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4262 }
4263
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004264 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004265 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4266 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004267 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004268 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4269 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004270 displayId, policyFlags, action, actionButton,
4271 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004272 motionEvent.getButtonState(),
4273 motionEvent.getClassification(),
4274 motionEvent.getEdgeFlags(),
4275 motionEvent.getXPrecision(),
4276 motionEvent.getYPrecision(),
4277 motionEvent.getRawXCursorPosition(),
4278 motionEvent.getRawYCursorPosition(),
4279 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004280 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004281 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004282 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004283 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004284 sampleEventTimes += 1;
4285 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004286 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004287 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4288 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004289 displayId, policyFlags, action, actionButton,
4290 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004291 motionEvent.getButtonState(),
4292 motionEvent.getClassification(),
4293 motionEvent.getEdgeFlags(),
4294 motionEvent.getXPrecision(),
4295 motionEvent.getYPrecision(),
4296 motionEvent.getRawXCursorPosition(),
4297 motionEvent.getRawYCursorPosition(),
4298 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004299 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004300 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004301 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4302 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004303 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004304 }
4305 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004308 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004309 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004310 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 }
4312
Prabir Pradhan5735a322022-04-11 17:23:34 +00004313 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004314 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315 injectionState->injectionIsAsync = true;
4316 }
4317
4318 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004319 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320
4321 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004322 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004323 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004324 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325 }
4326
4327 mLock.unlock();
4328
4329 if (needWake) {
4330 mLooper->wake();
4331 }
4332
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004333 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004335 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004337 if (syncMode == InputEventInjectionSync::NONE) {
4338 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339 } else {
4340 for (;;) {
4341 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004342 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343 break;
4344 }
4345
4346 nsecs_t remainingTimeout = endTime - now();
4347 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004348 if (DEBUG_INJECTION) {
4349 ALOGD("injectInputEvent - Timed out waiting for injection result "
4350 "to become available.");
4351 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004352 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004353 break;
4354 }
4355
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004356 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357 }
4358
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004359 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4360 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004362 if (DEBUG_INJECTION) {
4363 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4364 injectionState->pendingForegroundDispatches);
4365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 nsecs_t remainingTimeout = endTime - now();
4367 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004368 if (DEBUG_INJECTION) {
4369 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4370 "dispatches to finish.");
4371 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004372 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 break;
4374 }
4375
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004376 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377 }
4378 }
4379 }
4380
4381 injectionState->release();
4382 } // release lock
4383
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004384 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004385 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004386 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387
4388 return injectionResult;
4389}
4390
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004391std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004392 std::array<uint8_t, 32> calculatedHmac;
4393 std::unique_ptr<VerifiedInputEvent> result;
4394 switch (event.getType()) {
4395 case AINPUT_EVENT_TYPE_KEY: {
4396 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4397 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4398 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004399 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004400 break;
4401 }
4402 case AINPUT_EVENT_TYPE_MOTION: {
4403 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4404 VerifiedMotionEvent verifiedMotionEvent =
4405 verifiedMotionEventFromMotionEvent(motionEvent);
4406 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004407 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004408 break;
4409 }
4410 default: {
4411 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4412 return nullptr;
4413 }
4414 }
4415 if (calculatedHmac == INVALID_HMAC) {
4416 return nullptr;
4417 }
4418 if (calculatedHmac != event.getHmac()) {
4419 return nullptr;
4420 }
4421 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004422}
4423
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004424void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004425 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004426 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004427 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004428 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004429 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004430 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004431
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004432 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433 // Log the outcome since the injector did not wait for the injection result.
4434 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004435 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004436 ALOGV("Asynchronous input event injection succeeded.");
4437 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004438 case InputEventInjectionResult::TARGET_MISMATCH:
4439 ALOGV("Asynchronous input event injection target mismatch.");
4440 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004441 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004442 ALOGW("Asynchronous input event injection failed.");
4443 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004444 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004445 ALOGW("Asynchronous input event injection timed out.");
4446 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004447 case InputEventInjectionResult::PENDING:
4448 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4449 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004450 }
4451 }
4452
4453 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004454 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004455 }
4456}
4457
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004458void InputDispatcher::transformMotionEntryForInjectionLocked(
4459 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004460 // Input injection works in the logical display coordinate space, but the input pipeline works
4461 // display space, so we need to transform the injected events accordingly.
4462 const auto it = mDisplayInfos.find(entry.displayId);
4463 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004464 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004465
4466 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004467 entry.pointerCoords[i] =
4468 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4469 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004470 }
4471}
4472
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004473void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4474 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004475 if (injectionState) {
4476 injectionState->pendingForegroundDispatches += 1;
4477 }
4478}
4479
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004480void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4481 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004482 if (injectionState) {
4483 injectionState->pendingForegroundDispatches -= 1;
4484
4485 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004486 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004487 }
4488 }
4489}
4490
chaviw98318de2021-05-19 16:45:23 -05004491const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004492 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004493 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004494 auto it = mWindowHandlesByDisplay.find(displayId);
4495 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004496}
4497
chaviw98318de2021-05-19 16:45:23 -05004498sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004499 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004500 if (windowHandleToken == nullptr) {
4501 return nullptr;
4502 }
4503
Arthur Hungb92218b2018-08-14 12:00:21 +08004504 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004505 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4506 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004507 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004508 return windowHandle;
4509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510 }
4511 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004512 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004513}
4514
chaviw98318de2021-05-19 16:45:23 -05004515sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4516 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004517 if (windowHandleToken == nullptr) {
4518 return nullptr;
4519 }
4520
chaviw98318de2021-05-19 16:45:23 -05004521 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004522 if (windowHandle->getToken() == windowHandleToken) {
4523 return windowHandle;
4524 }
4525 }
4526 return nullptr;
4527}
4528
chaviw98318de2021-05-19 16:45:23 -05004529sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4530 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004531 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004532 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4533 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004534 if (handle->getId() == windowHandle->getId() &&
4535 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004536 if (windowHandle->getInfo()->displayId != it.first) {
4537 ALOGE("Found window %s in display %" PRId32
4538 ", but it should belong to display %" PRId32,
4539 windowHandle->getName().c_str(), it.first,
4540 windowHandle->getInfo()->displayId);
4541 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004542 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004543 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004544 }
4545 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004546 return nullptr;
4547}
4548
chaviw98318de2021-05-19 16:45:23 -05004549sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004550 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4551 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004552}
4553
chaviw98318de2021-05-19 16:45:23 -05004554bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004555 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4556 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004557 windowHandle.getInfo()->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004558 if (connection != nullptr && noInputChannel) {
4559 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4560 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4561 return false;
4562 }
4563
4564 if (connection == nullptr) {
4565 if (!noInputChannel) {
4566 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4567 }
4568 return false;
4569 }
4570 if (!connection->responsive) {
4571 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4572 return false;
4573 }
4574 return true;
4575}
4576
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004577std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4578 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004579 auto connectionIt = mConnectionsByToken.find(token);
4580 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004581 return nullptr;
4582 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004583 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004584}
4585
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004586void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004587 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4588 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004589 // Remove all handles on a display if there are no windows left.
4590 mWindowHandlesByDisplay.erase(displayId);
4591 return;
4592 }
4593
4594 // Since we compare the pointer of input window handles across window updates, we need
4595 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004596 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4597 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4598 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004599 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004600 }
4601
chaviw98318de2021-05-19 16:45:23 -05004602 std::vector<sp<WindowInfoHandle>> newHandles;
4603 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004604 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004605 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004606 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004607 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004608 const bool canReceiveInput =
4609 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4610 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004611 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004612 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004613 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004614 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004615 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004616 }
4617
4618 if (info->displayId != displayId) {
4619 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4620 handle->getName().c_str(), displayId, info->displayId);
4621 continue;
4622 }
4623
Robert Carredd13602020-04-13 17:24:34 -07004624 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4625 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004626 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004627 oldHandle->updateFrom(handle);
4628 newHandles.push_back(oldHandle);
4629 } else {
4630 newHandles.push_back(handle);
4631 }
4632 }
4633
4634 // Insert or replace
4635 mWindowHandlesByDisplay[displayId] = newHandles;
4636}
4637
Arthur Hung72d8dc32020-03-28 00:48:39 +00004638void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004639 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004640 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004641 { // acquire lock
4642 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004643 for (const auto& [displayId, handles] : handlesPerDisplay) {
4644 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004645 }
4646 }
4647 // Wake up poll loop since it may need to make new input dispatching choices.
4648 mLooper->wake();
4649}
4650
Arthur Hungb92218b2018-08-14 12:00:21 +08004651/**
4652 * Called from InputManagerService, update window handle list by displayId that can receive input.
4653 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4654 * If set an empty list, remove all handles from the specific display.
4655 * For focused handle, check if need to change and send a cancel event to previous one.
4656 * For removed handle, check if need to send a cancel event if already in touch.
4657 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004658void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004659 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004660 if (DEBUG_FOCUS) {
4661 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004662 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004663 windowList += iwh->getName() + " ";
4664 }
4665 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4666 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004667
Prabir Pradhand65552b2021-10-07 11:23:50 -07004668 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004669 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004670 const WindowInfo& info = *window->getInfo();
4671
4672 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004673 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004674 if (noInputWindow && window->getToken() != nullptr) {
4675 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4676 window->getName().c_str());
4677 window->releaseChannel();
4678 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004679
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004680 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004681 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4682 !info.inputConfig.test(
4683 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004684 "%s has feature SPY, but is not a trusted overlay.",
4685 window->getName().c_str());
4686
Prabir Pradhand65552b2021-10-07 11:23:50 -07004687 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004688 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4689 !info.inputConfig.test(
4690 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004691 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4692 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004693 }
4694
Arthur Hung72d8dc32020-03-28 00:48:39 +00004695 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004696 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004697
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004698 // Save the old windows' orientation by ID before it gets updated.
4699 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004700 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004701 oldWindowOrientations.emplace(handle->getId(),
4702 handle->getInfo()->transform.getOrientation());
4703 }
4704
chaviw98318de2021-05-19 16:45:23 -05004705 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004706
chaviw98318de2021-05-19 16:45:23 -05004707 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004708 if (mLastHoverWindowHandle &&
4709 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4710 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004711 mLastHoverWindowHandle = nullptr;
4712 }
4713
Vishnu Nairc519ff72021-01-21 08:23:08 -08004714 std::optional<FocusResolver::FocusChanges> changes =
4715 mFocusResolver.setInputWindows(displayId, windowHandles);
4716 if (changes) {
4717 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004718 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004720 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4721 mTouchStatesByDisplay.find(displayId);
4722 if (stateIt != mTouchStatesByDisplay.end()) {
4723 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004724 for (size_t i = 0; i < state.windows.size();) {
4725 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004726 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004727 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004728 ALOGD("Touched window was removed: %s in display %" PRId32,
4729 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004730 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004731 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004732 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4733 if (touchedInputChannel != nullptr) {
4734 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4735 "touched window was removed");
4736 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004737 // Since we are about to drop the touch, cancel the events for the wallpaper as
4738 // well.
4739 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004740 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4741 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004742 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4743 if (wallpaper != nullptr) {
4744 sp<Connection> wallpaperConnection =
4745 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004746 if (wallpaperConnection != nullptr) {
4747 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4748 options);
4749 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004750 }
4751 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004753 state.windows.erase(state.windows.begin() + i);
4754 } else {
4755 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756 }
4757 }
arthurhungb89ccb02020-12-30 16:19:01 +08004758
arthurhung6d4bed92021-03-17 11:59:33 +08004759 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004760 // could just clear the state here.
arthurhung6d4bed92021-03-17 11:59:33 +08004761 if (mDragState &&
4762 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004763 windowHandles.end()) {
arthurhung6d4bed92021-03-17 11:59:33 +08004764 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004765 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004766 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004767
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004768 // Determine if the orientation of any of the input windows have changed, and cancel all
4769 // pointer events if necessary.
4770 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4771 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4772 if (newWindowHandle != nullptr &&
4773 newWindowHandle->getInfo()->transform.getOrientation() !=
4774 oldWindowOrientations[oldWindowHandle->getId()]) {
4775 std::shared_ptr<InputChannel> inputChannel =
4776 getInputChannelLocked(newWindowHandle->getToken());
4777 if (inputChannel != nullptr) {
4778 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4779 "touched window's orientation changed");
4780 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004781 }
4782 }
4783 }
4784
Arthur Hung72d8dc32020-03-28 00:48:39 +00004785 // Release information for windows that are no longer present.
4786 // This ensures that unused input channels are released promptly.
4787 // Otherwise, they might stick around until the window handle is destroyed
4788 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004789 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004790 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004791 if (DEBUG_FOCUS) {
4792 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004793 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004794 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004795 }
chaviw291d88a2019-02-14 10:33:58 -08004796 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797}
4798
4799void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004800 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004801 if (DEBUG_FOCUS) {
4802 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4803 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4804 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004805 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004806 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004807 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808 } // release lock
4809
4810 // Wake up poll loop since it may need to make new input dispatching choices.
4811 mLooper->wake();
4812}
4813
Vishnu Nair599f1412021-06-21 10:39:58 -07004814void InputDispatcher::setFocusedApplicationLocked(
4815 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4816 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4817 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4818
4819 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4820 return; // This application is already focused. No need to wake up or change anything.
4821 }
4822
4823 // Set the new application handle.
4824 if (inputApplicationHandle != nullptr) {
4825 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4826 } else {
4827 mFocusedApplicationHandlesByDisplay.erase(displayId);
4828 }
4829
4830 // No matter what the old focused application was, stop waiting on it because it is
4831 // no longer focused.
4832 resetNoFocusedWindowTimeoutLocked();
4833}
4834
Tiger Huang721e26f2018-07-24 22:26:19 +08004835/**
4836 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4837 * the display not specified.
4838 *
4839 * We track any unreleased events for each window. If a window loses the ability to receive the
4840 * released event, we will send a cancel event to it. So when the focused display is changed, we
4841 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4842 * display. The display-specified events won't be affected.
4843 */
4844void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004845 if (DEBUG_FOCUS) {
4846 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4847 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004848 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004849 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004850
4851 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004852 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004853 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004854 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004855 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004856 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004857 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004858 CancelationOptions
4859 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4860 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004861 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004862 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4863 }
4864 }
4865 mFocusedDisplayId = displayId;
4866
Chris Ye3c2d6f52020-08-09 10:39:48 -07004867 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004868 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004869 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004870
Vishnu Nairad321cd2020-08-20 16:40:21 -07004871 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004872 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004873 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004874 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004875 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004876 }
4877 }
4878 }
4879
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004880 if (DEBUG_FOCUS) {
4881 logDispatchStateLocked();
4882 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004883 } // release lock
4884
4885 // Wake up poll loop since it may need to make new input dispatching choices.
4886 mLooper->wake();
4887}
4888
Michael Wrightd02c5b62014-02-10 15:10:22 -08004889void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004890 if (DEBUG_FOCUS) {
4891 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004893
4894 bool changed;
4895 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004896 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897
4898 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4899 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004900 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901 }
4902
4903 if (mDispatchEnabled && !enabled) {
4904 resetAndDropEverythingLocked("dispatcher is being disabled");
4905 }
4906
4907 mDispatchEnabled = enabled;
4908 mDispatchFrozen = frozen;
4909 changed = true;
4910 } else {
4911 changed = false;
4912 }
4913
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004914 if (DEBUG_FOCUS) {
4915 logDispatchStateLocked();
4916 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004917 } // release lock
4918
4919 if (changed) {
4920 // Wake up poll loop since it may need to make new input dispatching choices.
4921 mLooper->wake();
4922 }
4923}
4924
4925void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004926 if (DEBUG_FOCUS) {
4927 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4928 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004929
4930 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004931 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932
4933 if (mInputFilterEnabled == enabled) {
4934 return;
4935 }
4936
4937 mInputFilterEnabled = enabled;
4938 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4939 } // release lock
4940
4941 // Wake up poll loop since there might be work to do to drop everything.
4942 mLooper->wake();
4943}
4944
Antonio Kantekea47acb2021-12-23 12:41:25 -08004945bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid,
4946 bool hasPermission) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00004947 bool needWake = false;
4948 {
4949 std::scoped_lock lock(mLock);
4950 if (mInTouchMode == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004951 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00004952 }
4953 if (DEBUG_TOUCH_MODE) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08004954 ALOGD("Request to change touch mode from %s to %s (calling pid=%d, uid=%d, "
4955 "hasPermission=%s)",
4956 toString(mInTouchMode), toString(inTouchMode), pid, uid, toString(hasPermission));
4957 }
4958 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07004959 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
4960 !recentWindowsAreOwnedByLocked(pid, uid)) {
4961 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
4962 "window nor none of the previously interacted window",
4963 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08004964 return false;
4965 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00004966 }
4967
4968 // TODO(b/198499018): Store touch mode per display.
4969 mInTouchMode = inTouchMode;
4970
Antonio Kantekf16f2832021-09-28 04:39:20 +00004971 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
4972 needWake = enqueueInboundEventLocked(std::move(entry));
4973 } // release lock
4974
4975 if (needWake) {
4976 mLooper->wake();
4977 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08004978 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004979}
4980
Antonio Kantek48710e42022-03-24 14:19:30 -07004981bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
4982 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
4983 if (focusedToken == nullptr) {
4984 return false;
4985 }
4986 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
4987 return isWindowOwnedBy(windowHandle, pid, uid);
4988}
4989
4990bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
4991 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
4992 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
4993 const sp<WindowInfoHandle> windowHandle =
4994 getWindowHandleLocked(connectionToken);
4995 return isWindowOwnedBy(windowHandle, pid, uid);
4996 }) != mInteractionConnectionTokens.end();
4997}
4998
Bernardo Rufinoea97d182020-08-19 14:43:14 +01004999void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5000 if (opacity < 0 || opacity > 1) {
5001 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5002 return;
5003 }
5004
5005 std::scoped_lock lock(mLock);
5006 mMaximumObscuringOpacityForTouch = opacity;
5007}
5008
Arthur Hungabbb9d82021-09-01 14:52:30 +00005009std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
5010 const sp<IBinder>& token) {
5011 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5012 for (TouchedWindow& w : state.windows) {
5013 if (w.windowHandle->getToken() == token) {
5014 return std::make_pair(&state, &w);
5015 }
5016 }
5017 }
5018 return std::make_pair(nullptr, nullptr);
5019}
5020
arthurhungb89ccb02020-12-30 16:19:01 +08005021bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5022 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005023 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005024 if (DEBUG_FOCUS) {
5025 ALOGD("Trivial transfer to same window.");
5026 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005027 return true;
5028 }
5029
Michael Wrightd02c5b62014-02-10 15:10:22 -08005030 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005031 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005032
Arthur Hungabbb9d82021-09-01 14:52:30 +00005033 // Find the target touch state and touched window by fromToken.
5034 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5035 if (state == nullptr || touchedWindow == nullptr) {
5036 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005037 return false;
5038 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005039
5040 const int32_t displayId = state->displayId;
5041 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5042 if (toWindowHandle == nullptr) {
5043 ALOGW("Cannot transfer focus because to window not found.");
5044 return false;
5045 }
5046
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005047 if (DEBUG_FOCUS) {
5048 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005049 touchedWindow->windowHandle->getName().c_str(),
5050 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005051 }
5052
Arthur Hungabbb9d82021-09-01 14:52:30 +00005053 // Erase old window.
5054 int32_t oldTargetFlags = touchedWindow->targetFlags;
5055 BitSet32 pointerIds = touchedWindow->pointerIds;
5056 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005057
Arthur Hungabbb9d82021-09-01 14:52:30 +00005058 // Add new window.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005059 int32_t newTargetFlags =
5060 oldTargetFlags & (InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
5061 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
5062 newTargetFlags |= InputTarget::FLAG_FOREGROUND;
5063 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005064 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005065
Arthur Hungabbb9d82021-09-01 14:52:30 +00005066 // Store the dragging window.
5067 if (isDragDrop) {
Arthur Hung54745652022-04-20 07:17:41 +00005068 if (pointerIds.count() > 1) {
5069 ALOGW("The drag and drop cannot be started when there is more than 1 pointer on the"
5070 " window.");
5071 return false;
5072 }
5073 // If the window didn't not support split or the source is mouse, the pointerIds count
5074 // would be 0, so we have to track the pointer 0.
5075 const int32_t id = pointerIds.count() == 0 ? 0 : pointerIds.firstMarkedBit();
5076 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005077 }
5078
Arthur Hungabbb9d82021-09-01 14:52:30 +00005079 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005080 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5081 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005082 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005083 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005084 CancelationOptions
5085 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5086 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005087 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08005088 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005089 }
5090
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005091 if (DEBUG_FOCUS) {
5092 logDispatchStateLocked();
5093 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005094 } // release lock
5095
5096 // Wake up poll loop since it may need to make new input dispatching choices.
5097 mLooper->wake();
5098 return true;
5099}
5100
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005101/**
5102 * Get the touched foreground window on the given display.
5103 * Return null if there are no windows touched on that display, or if more than one foreground
5104 * window is being touched.
5105 */
5106sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5107 auto stateIt = mTouchStatesByDisplay.find(displayId);
5108 if (stateIt == mTouchStatesByDisplay.end()) {
5109 ALOGI("No touch state on display %" PRId32, displayId);
5110 return nullptr;
5111 }
5112
5113 const TouchState& state = stateIt->second;
5114 sp<WindowInfoHandle> touchedForegroundWindow;
5115 // If multiple foreground windows are touched, return nullptr
5116 for (const TouchedWindow& window : state.windows) {
5117 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5118 if (touchedForegroundWindow != nullptr) {
5119 ALOGI("Two or more foreground windows: %s and %s",
5120 touchedForegroundWindow->getName().c_str(),
5121 window.windowHandle->getName().c_str());
5122 return nullptr;
5123 }
5124 touchedForegroundWindow = window.windowHandle;
5125 }
5126 }
5127 return touchedForegroundWindow;
5128}
5129
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005130// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005131bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005132 sp<IBinder> fromToken;
5133 { // acquire lock
5134 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005135 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005136 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005137 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5138 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005139 return false;
5140 }
5141
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005142 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5143 if (from == nullptr) {
5144 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5145 return false;
5146 }
5147
5148 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005149 } // release lock
5150
5151 return transferTouchFocus(fromToken, destChannelToken);
5152}
5153
Michael Wrightd02c5b62014-02-10 15:10:22 -08005154void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005155 if (DEBUG_FOCUS) {
5156 ALOGD("Resetting and dropping all events (%s).", reason);
5157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005158
5159 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5160 synthesizeCancelationEventsForAllConnectionsLocked(options);
5161
5162 resetKeyRepeatLocked();
5163 releasePendingEventLocked();
5164 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005165 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005167 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005168 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005169 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005170 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171}
5172
5173void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005174 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005175 dumpDispatchStateLocked(dump);
5176
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005177 std::istringstream stream(dump);
5178 std::string line;
5179
5180 while (std::getline(stream, line, '\n')) {
5181 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005182 }
5183}
5184
Prabir Pradhan99987712020-11-10 18:43:05 -08005185std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5186 std::string dump;
5187
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005188 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5189 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005190
5191 std::string windowName = "None";
5192 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005193 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005194 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5195 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5196 : "token has capture without window";
5197 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005198 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005199
5200 return dump;
5201}
5202
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005203void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005204 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5205 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5206 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005207 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005208
Tiger Huang721e26f2018-07-24 22:26:19 +08005209 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5210 dump += StringPrintf(INDENT "FocusedApplications:\n");
5211 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5212 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005213 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005214 const std::chrono::duration timeout =
5215 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005216 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005217 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005218 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005219 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005220 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005221 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005222 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005223
Vishnu Nairc519ff72021-01-21 08:23:08 -08005224 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005225 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005226
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005227 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005228 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005229 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5230 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005231 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005232 state.displayId, toString(state.down), toString(state.split),
5233 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005234 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005235 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005236 for (size_t i = 0; i < state.windows.size(); i++) {
5237 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005238 dump += StringPrintf(INDENT4
5239 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5240 i, touchedWindow.windowHandle->getName().c_str(),
5241 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005242 }
5243 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005244 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005245 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005246 }
5247 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005248 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005249 }
5250
arthurhung6d4bed92021-03-17 11:59:33 +08005251 if (mDragState) {
5252 dump += StringPrintf(INDENT "DragState:\n");
5253 mDragState->dump(dump, INDENT2);
5254 }
5255
Arthur Hungb92218b2018-08-14 12:00:21 +08005256 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005257 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5258 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5259 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5260 const auto& displayInfo = it->second;
5261 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5262 displayInfo.logicalHeight);
5263 displayInfo.transform.dump(dump, "transform", INDENT4);
5264 } else {
5265 dump += INDENT2 "No DisplayInfo found!\n";
5266 }
5267
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005268 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005269 dump += INDENT2 "Windows:\n";
5270 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005271 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5272 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005273
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005274 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005275 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005276 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005277 "applicationInfo.name=%s, "
5278 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005279 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005280 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005281 windowInfo->displayId,
5282 windowInfo->inputConfig.string().c_str(),
5283 windowInfo->alpha, windowInfo->frameLeft,
5284 windowInfo->frameTop, windowInfo->frameRight,
5285 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005286 windowInfo->applicationInfo.name.c_str(),
5287 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005288 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005289 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005290 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005291 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005292 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005293 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005294 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005295 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005296 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005297 }
5298 } else {
5299 dump += INDENT2 "Windows: <none>\n";
5300 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005301 }
5302 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005303 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005304 }
5305
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005306 if (!mGlobalMonitorsByDisplay.empty()) {
5307 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5308 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005309 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005310 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005311 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005312 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313 }
5314
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005315 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005316
5317 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005318 if (!mRecentQueue.empty()) {
5319 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005320 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005321 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005322 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005323 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005324 }
5325 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005326 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005327 }
5328
5329 // Dump event currently being dispatched.
5330 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005331 dump += INDENT "PendingEvent:\n";
5332 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005333 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005334 dump += StringPrintf(", age=%" PRId64 "ms\n",
5335 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005336 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005337 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005338 }
5339
5340 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005341 if (!mInboundQueue.empty()) {
5342 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005343 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005344 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005345 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005346 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005347 }
5348 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005349 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005350 }
5351
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005352 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005353 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005354 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5355 const KeyReplacement& replacement = pair.first;
5356 int32_t newKeyCode = pair.second;
5357 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005358 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005359 }
5360 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005361 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005362 }
5363
Prabir Pradhancef936d2021-07-21 16:17:52 +00005364 if (!mCommandQueue.empty()) {
5365 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5366 } else {
5367 dump += INDENT "CommandQueue: <empty>\n";
5368 }
5369
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005370 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005371 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005372 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005373 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005374 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005375 connection->inputChannel->getFd().get(),
5376 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005377 connection->getWindowName().c_str(),
5378 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005379 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005380
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005381 if (!connection->outboundQueue.empty()) {
5382 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5383 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005384 dump += dumpQueue(connection->outboundQueue, currentTime);
5385
Michael Wrightd02c5b62014-02-10 15:10:22 -08005386 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005387 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005388 }
5389
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005390 if (!connection->waitQueue.empty()) {
5391 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5392 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005393 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005394 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005395 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005396 }
5397 }
5398 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005399 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005400 }
5401
5402 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005403 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5404 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005405 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005406 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005407 }
5408
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005409 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005410 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5411 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5412 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005413 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005414 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005415}
5416
Michael Wright3dd60e22019-03-27 22:06:44 +00005417void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5418 const size_t numMonitors = monitors.size();
5419 for (size_t i = 0; i < numMonitors; i++) {
5420 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005421 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005422 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5423 dump += "\n";
5424 }
5425}
5426
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005427class LooperEventCallback : public LooperCallback {
5428public:
5429 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5430 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5431
5432private:
5433 std::function<int(int events)> mCallback;
5434};
5435
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005436Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005437 if (DEBUG_CHANNEL_CREATION) {
5438 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5439 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005440
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005441 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005442 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005443 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005444
5445 if (result) {
5446 return base::Error(result) << "Failed to open input channel pair with name " << name;
5447 }
5448
Michael Wrightd02c5b62014-02-10 15:10:22 -08005449 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005450 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005451 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005452 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005453 sp<Connection> connection =
5454 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005455
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005456 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5457 ALOGE("Created a new connection, but the token %p is already known", token.get());
5458 }
5459 mConnectionsByToken.emplace(token, connection);
5460
5461 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5462 this, std::placeholders::_1, token);
5463
5464 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005465 } // release lock
5466
5467 // Wake the looper because some connections have changed.
5468 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005469 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005470}
5471
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005472Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005473 const std::string& name,
5474 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005475 std::shared_ptr<InputChannel> serverChannel;
5476 std::unique_ptr<InputChannel> clientChannel;
5477 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5478 if (result) {
5479 return base::Error(result) << "Failed to open input channel pair with name " << name;
5480 }
5481
Michael Wright3dd60e22019-03-27 22:06:44 +00005482 { // acquire lock
5483 std::scoped_lock _l(mLock);
5484
5485 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005486 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5487 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005488 }
5489
Garfield Tan15601662020-09-22 15:32:38 -07005490 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005491 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005492 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005493
5494 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5495 ALOGE("Created a new connection, but the token %p is already known", token.get());
5496 }
5497 mConnectionsByToken.emplace(token, connection);
5498 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5499 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005500
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005501 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005502
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005503 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005504 }
Garfield Tan15601662020-09-22 15:32:38 -07005505
Michael Wright3dd60e22019-03-27 22:06:44 +00005506 // Wake the looper because some connections have changed.
5507 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005508 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005509}
5510
Garfield Tan15601662020-09-22 15:32:38 -07005511status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005512 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005513 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005514
Garfield Tan15601662020-09-22 15:32:38 -07005515 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005516 if (status) {
5517 return status;
5518 }
5519 } // release lock
5520
5521 // Wake the poll loop because removing the connection may have changed the current
5522 // synchronization state.
5523 mLooper->wake();
5524 return OK;
5525}
5526
Garfield Tan15601662020-09-22 15:32:38 -07005527status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5528 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005529 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005530 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005531 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005532 return BAD_VALUE;
5533 }
5534
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005535 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005536
Michael Wrightd02c5b62014-02-10 15:10:22 -08005537 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005538 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005539 }
5540
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005541 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005542
5543 nsecs_t currentTime = now();
5544 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5545
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005546 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005547 return OK;
5548}
5549
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005550void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005551 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5552 auto& [displayId, monitors] = *it;
5553 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5554 return monitor.inputChannel->getConnectionToken() == connectionToken;
5555 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005556
Michael Wright3dd60e22019-03-27 22:06:44 +00005557 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005558 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005559 } else {
5560 ++it;
5561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562 }
5563}
5564
Michael Wright3dd60e22019-03-27 22:06:44 +00005565status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005566 std::scoped_lock _l(mLock);
Michael Wright3dd60e22019-03-27 22:06:44 +00005567
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005568 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5569 if (!requestingChannel) {
5570 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5571 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005572 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005573
5574 auto [statePtr, windowPtr] = findTouchStateAndWindowLocked(token);
5575 if (statePtr == nullptr || windowPtr == nullptr || !statePtr->down) {
5576 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5577 " Ignoring.");
5578 return BAD_VALUE;
5579 }
5580
5581 TouchState& state = *statePtr;
5582
5583 // Send cancel events to all the input channels we're stealing from.
5584 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5585 "input channel stole pointer stream");
5586 options.deviceId = state.deviceId;
5587 options.displayId = state.displayId;
5588 std::string canceledWindows;
5589 for (const TouchedWindow& window : state.windows) {
5590 const std::shared_ptr<InputChannel> channel =
5591 getInputChannelLocked(window.windowHandle->getToken());
5592 if (channel != nullptr && channel->getConnectionToken() != token) {
5593 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5594 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5595 canceledWindows += channel->getName();
5596 }
5597 }
5598 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5599 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5600 canceledWindows.c_str());
5601
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005602 // Prevent the gesture from being sent to any other windows.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005603 state.filterWindowsExcept(token);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005604 state.preventNewTargets = true;
Michael Wright3dd60e22019-03-27 22:06:44 +00005605 return OK;
5606}
5607
Prabir Pradhan99987712020-11-10 18:43:05 -08005608void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5609 { // acquire lock
5610 std::scoped_lock _l(mLock);
5611 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005612 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005613 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5614 windowHandle != nullptr ? windowHandle->getName().c_str()
5615 : "token without window");
5616 }
5617
Vishnu Nairc519ff72021-01-21 08:23:08 -08005618 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005619 if (focusedToken != windowToken) {
5620 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5621 enabled ? "enable" : "disable");
5622 return;
5623 }
5624
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005625 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005626 ALOGW("Ignoring request to %s Pointer Capture: "
5627 "window has %s requested pointer capture.",
5628 enabled ? "enable" : "disable", enabled ? "already" : "not");
5629 return;
5630 }
5631
Christine Franksb768bb42021-11-29 12:11:31 -08005632 if (enabled) {
5633 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5634 mIneligibleDisplaysForPointerCapture.end(),
5635 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5636 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5637 return;
5638 }
5639 }
5640
Prabir Pradhan99987712020-11-10 18:43:05 -08005641 setPointerCaptureLocked(enabled);
5642 } // release lock
5643
5644 // Wake the thread to process command entries.
5645 mLooper->wake();
5646}
5647
Christine Franksb768bb42021-11-29 12:11:31 -08005648void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5649 { // acquire lock
5650 std::scoped_lock _l(mLock);
5651 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5652 if (!isEligible) {
5653 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5654 }
5655 } // release lock
5656}
5657
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005658std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5659 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005660 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005661 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005662 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005663 }
5664 }
5665 }
5666 return std::nullopt;
5667}
5668
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005669sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005670 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005671 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005672 }
5673
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005674 for (const auto& [token, connection] : mConnectionsByToken) {
5675 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005676 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005677 }
5678 }
Robert Carr4e670e52018-08-15 13:26:12 -07005679
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005680 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005681}
5682
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005683std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5684 sp<Connection> connection = getConnectionLocked(connectionToken);
5685 if (connection == nullptr) {
5686 return "<nullptr>";
5687 }
5688 return connection->getInputChannelName();
5689}
5690
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005691void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005692 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005693 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005694}
5695
Prabir Pradhancef936d2021-07-21 16:17:52 +00005696void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5697 const sp<Connection>& connection, uint32_t seq,
5698 bool handled, nsecs_t consumeTime) {
5699 // Handle post-event policy actions.
5700 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5701 if (dispatchEntryIt == connection->waitQueue.end()) {
5702 return;
5703 }
5704 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5705 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5706 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5707 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5708 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5709 }
5710 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5711 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5712 connection->inputChannel->getConnectionToken(),
5713 dispatchEntry->deliveryTime, consumeTime, finishTime);
5714 }
5715
5716 bool restartEvent;
5717 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5718 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5719 restartEvent =
5720 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5721 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5722 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5723 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5724 handled);
5725 } else {
5726 restartEvent = false;
5727 }
5728
5729 // Dequeue the event and start the next cycle.
5730 // Because the lock might have been released, it is possible that the
5731 // contents of the wait queue to have been drained, so we need to double-check
5732 // a few things.
5733 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5734 if (dispatchEntryIt != connection->waitQueue.end()) {
5735 dispatchEntry = *dispatchEntryIt;
5736 connection->waitQueue.erase(dispatchEntryIt);
5737 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5738 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5739 if (!connection->responsive) {
5740 connection->responsive = isConnectionResponsive(*connection);
5741 if (connection->responsive) {
5742 // The connection was unresponsive, and now it's responsive.
5743 processConnectionResponsiveLocked(*connection);
5744 }
5745 }
5746 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005747 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005748 connection->outboundQueue.push_front(dispatchEntry);
5749 traceOutboundQueueLength(*connection);
5750 } else {
5751 releaseDispatchEntry(dispatchEntry);
5752 }
5753 }
5754
5755 // Start the next dispatch cycle for this connection.
5756 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005757}
5758
Prabir Pradhancef936d2021-07-21 16:17:52 +00005759void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5760 const sp<IBinder>& newToken) {
5761 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5762 scoped_unlock unlock(mLock);
5763 mPolicy->notifyFocusChanged(oldToken, newToken);
5764 };
5765 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005766}
5767
Prabir Pradhancef936d2021-07-21 16:17:52 +00005768void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5769 auto command = [this, token, x, y]() REQUIRES(mLock) {
5770 scoped_unlock unlock(mLock);
5771 mPolicy->notifyDropWindow(token, x, y);
5772 };
5773 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005774}
5775
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005776void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5777 if (connection == nullptr) {
5778 LOG_ALWAYS_FATAL("Caller must check for nullness");
5779 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005780 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5781 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005782 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005783 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005784 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005785 return;
5786 }
5787 /**
5788 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5789 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5790 * has changed. This could cause newer entries to time out before the already dispatched
5791 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5792 * processes the events linearly. So providing information about the oldest entry seems to be
5793 * most useful.
5794 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005795 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005796 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5797 std::string reason =
5798 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005799 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005800 ns2ms(currentWait),
5801 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005802 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005803 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005804
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005805 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5806
5807 // Stop waking up for events on this connection, it is already unresponsive
5808 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005809}
5810
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005811void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5812 std::string reason =
5813 StringPrintf("%s does not have a focused window", application->getName().c_str());
5814 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005815
Prabir Pradhancef936d2021-07-21 16:17:52 +00005816 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5817 scoped_unlock unlock(mLock);
5818 mPolicy->notifyNoFocusedWindowAnr(application);
5819 };
5820 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005821}
5822
chaviw98318de2021-05-19 16:45:23 -05005823void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005824 const std::string& reason) {
5825 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5826 updateLastAnrStateLocked(windowLabel, reason);
5827}
5828
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005829void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5830 const std::string& reason) {
5831 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005832 updateLastAnrStateLocked(windowLabel, reason);
5833}
5834
5835void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5836 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005837 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005838 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005839 struct tm tm;
5840 localtime_r(&t, &tm);
5841 char timestr[64];
5842 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005843 mLastAnrState.clear();
5844 mLastAnrState += INDENT "ANR:\n";
5845 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005846 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5847 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005848 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005849}
5850
Prabir Pradhancef936d2021-07-21 16:17:52 +00005851void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5852 KeyEntry& entry) {
5853 const KeyEvent event = createKeyEvent(entry);
5854 nsecs_t delay = 0;
5855 { // release lock
5856 scoped_unlock unlock(mLock);
5857 android::base::Timer t;
5858 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5859 entry.policyFlags);
5860 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5861 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5862 std::to_string(t.duration().count()).c_str());
5863 }
5864 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005865
5866 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005867 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005868 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005869 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005870 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005871 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5872 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005874}
5875
Prabir Pradhancef936d2021-07-21 16:17:52 +00005876void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005877 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005878 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005879 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005880 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005881 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005882 };
5883 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005884}
5885
Prabir Pradhanedd96402022-02-15 01:46:16 -08005886void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5887 std::optional<int32_t> pid) {
5888 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005889 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005890 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005891 };
5892 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005893}
5894
5895/**
5896 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5897 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5898 * command entry to the command queue.
5899 */
5900void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5901 std::string reason) {
5902 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005903 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005904 if (connection.monitor) {
5905 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5906 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005907 pid = findMonitorPidByTokenLocked(connectionToken);
5908 } else {
5909 // The connection is a window
5910 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5911 reason.c_str());
5912 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
5913 if (handle != nullptr) {
5914 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005915 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005916 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08005917 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005918}
5919
5920/**
5921 * Tell the policy that a connection has become responsive so that it can stop ANR.
5922 */
5923void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5924 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005925 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005926 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005927 pid = findMonitorPidByTokenLocked(connectionToken);
5928 } else {
5929 // The connection is a window
5930 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
5931 if (handle != nullptr) {
5932 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005933 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005934 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08005935 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005936}
5937
Prabir Pradhancef936d2021-07-21 16:17:52 +00005938bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005939 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005940 KeyEntry& keyEntry, bool handled) {
5941 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005942 if (!handled) {
5943 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005944 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005945 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005946 return false;
5947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005948
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005949 // Get the fallback key state.
5950 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005951 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005952 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005953 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005954 connection->inputState.removeFallbackKey(originalKeyCode);
5955 }
5956
5957 if (handled || !dispatchEntry->hasForegroundTarget()) {
5958 // If the application handles the original key for which we previously
5959 // generated a fallback or if the window is not a foreground window,
5960 // then cancel the associated fallback key, if any.
5961 if (fallbackKeyCode != -1) {
5962 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005963 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5964 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
5965 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
5966 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
5967 keyEntry.policyFlags);
5968 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005969 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005970 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005971
5972 mLock.unlock();
5973
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005974 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005975 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005976
5977 mLock.lock();
5978
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005979 // Cancel the fallback key.
5980 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005981 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005982 "application handled the original non-fallback key "
5983 "or is no longer a foreground target, "
5984 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005985 options.keyCode = fallbackKeyCode;
5986 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005987 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005988 connection->inputState.removeFallbackKey(originalKeyCode);
5989 }
5990 } else {
5991 // If the application did not handle a non-fallback key, first check
5992 // that we are in a good state to perform unhandled key event processing
5993 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005994 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005995 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005996 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
5997 ALOGD("Unhandled key event: Skipping unhandled key event processing "
5998 "since this is not an initial down. "
5999 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6000 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6001 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006002 return false;
6003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006004
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006005 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006006 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6007 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6008 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6009 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6010 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006011 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006012
6013 mLock.unlock();
6014
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006015 bool fallback =
6016 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006017 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006018
6019 mLock.lock();
6020
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006021 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006022 connection->inputState.removeFallbackKey(originalKeyCode);
6023 return false;
6024 }
6025
6026 // Latch the fallback keycode for this key on an initial down.
6027 // The fallback keycode cannot change at any other point in the lifecycle.
6028 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006029 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006030 fallbackKeyCode = event.getKeyCode();
6031 } else {
6032 fallbackKeyCode = AKEYCODE_UNKNOWN;
6033 }
6034 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6035 }
6036
6037 ALOG_ASSERT(fallbackKeyCode != -1);
6038
6039 // Cancel the fallback key if the policy decides not to send it anymore.
6040 // We will continue to dispatch the key to the policy but we will no
6041 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006042 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6043 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006044 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6045 if (fallback) {
6046 ALOGD("Unhandled key event: Policy requested to send key %d"
6047 "as a fallback for %d, but on the DOWN it had requested "
6048 "to send %d instead. Fallback canceled.",
6049 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6050 } else {
6051 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6052 "but on the DOWN it had requested to send %d. "
6053 "Fallback canceled.",
6054 originalKeyCode, fallbackKeyCode);
6055 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006056 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006057
6058 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6059 "canceling fallback, policy no longer desires it");
6060 options.keyCode = fallbackKeyCode;
6061 synthesizeCancelationEventsForConnectionLocked(connection, options);
6062
6063 fallback = false;
6064 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006065 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006066 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006067 }
6068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006069
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006070 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6071 {
6072 std::string msg;
6073 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6074 connection->inputState.getFallbackKeys();
6075 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6076 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6077 }
6078 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6079 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006080 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006081 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006082
6083 if (fallback) {
6084 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006085 keyEntry.eventTime = event.getEventTime();
6086 keyEntry.deviceId = event.getDeviceId();
6087 keyEntry.source = event.getSource();
6088 keyEntry.displayId = event.getDisplayId();
6089 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6090 keyEntry.keyCode = fallbackKeyCode;
6091 keyEntry.scanCode = event.getScanCode();
6092 keyEntry.metaState = event.getMetaState();
6093 keyEntry.repeatCount = event.getRepeatCount();
6094 keyEntry.downTime = event.getDownTime();
6095 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006096
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006097 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6098 ALOGD("Unhandled key event: Dispatching fallback key. "
6099 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6100 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6101 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006102 return true; // restart the event
6103 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006104 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6105 ALOGD("Unhandled key event: No fallback key.");
6106 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006107
6108 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006109 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006110 }
6111 }
6112 return false;
6113}
6114
Prabir Pradhancef936d2021-07-21 16:17:52 +00006115bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006116 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006117 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006118 return false;
6119}
6120
Michael Wrightd02c5b62014-02-10 15:10:22 -08006121void InputDispatcher::traceInboundQueueLengthLocked() {
6122 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006123 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006124 }
6125}
6126
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006127void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006128 if (ATRACE_ENABLED()) {
6129 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006130 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6131 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006132 }
6133}
6134
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006135void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006136 if (ATRACE_ENABLED()) {
6137 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006138 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6139 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006140 }
6141}
6142
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006143void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006144 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006145
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006146 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006147 dumpDispatchStateLocked(dump);
6148
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006149 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006150 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006151 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006152 }
6153}
6154
6155void InputDispatcher::monitor() {
6156 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006157 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006158 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006159 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006160}
6161
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006162/**
6163 * Wake up the dispatcher and wait until it processes all events and commands.
6164 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6165 * this method can be safely called from any thread, as long as you've ensured that
6166 * the work you are interested in completing has already been queued.
6167 */
6168bool InputDispatcher::waitForIdle() {
6169 /**
6170 * Timeout should represent the longest possible time that a device might spend processing
6171 * events and commands.
6172 */
6173 constexpr std::chrono::duration TIMEOUT = 100ms;
6174 std::unique_lock lock(mLock);
6175 mLooper->wake();
6176 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6177 return result == std::cv_status::no_timeout;
6178}
6179
Vishnu Naire798b472020-07-23 13:52:21 -07006180/**
6181 * Sets focus to the window identified by the token. This must be called
6182 * after updating any input window handles.
6183 *
6184 * Params:
6185 * request.token - input channel token used to identify the window that should gain focus.
6186 * request.focusedToken - the token that the caller expects currently to be focused. If the
6187 * specified token does not match the currently focused window, this request will be dropped.
6188 * If the specified focused token matches the currently focused window, the call will succeed.
6189 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6190 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6191 * when requesting the focus change. This determines which request gets
6192 * precedence if there is a focus change request from another source such as pointer down.
6193 */
Vishnu Nair958da932020-08-21 17:12:37 -07006194void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6195 { // acquire lock
6196 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006197 std::optional<FocusResolver::FocusChanges> changes =
6198 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6199 if (changes) {
6200 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006201 }
6202 } // release lock
6203 // Wake up poll loop since it may need to make new input dispatching choices.
6204 mLooper->wake();
6205}
6206
Vishnu Nairc519ff72021-01-21 08:23:08 -08006207void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6208 if (changes.oldFocus) {
6209 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006210 if (focusedInputChannel) {
6211 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6212 "focus left window");
6213 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006214 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006215 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006216 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006217 if (changes.newFocus) {
6218 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006219 }
6220
Prabir Pradhan99987712020-11-10 18:43:05 -08006221 // If a window has pointer capture, then it must have focus. We need to ensure that this
6222 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6223 // If the window loses focus before it loses pointer capture, then the window can be in a state
6224 // where it has pointer capture but not focus, violating the contract. Therefore we must
6225 // dispatch the pointer capture event before the focus event. Since focus events are added to
6226 // the front of the queue (above), we add the pointer capture event to the front of the queue
6227 // after the focus events are added. This ensures the pointer capture event ends up at the
6228 // front.
6229 disablePointerCaptureForcedLocked();
6230
Vishnu Nairc519ff72021-01-21 08:23:08 -08006231 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006232 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006233 }
6234}
Vishnu Nair958da932020-08-21 17:12:37 -07006235
Prabir Pradhan99987712020-11-10 18:43:05 -08006236void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006237 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006238 return;
6239 }
6240
6241 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6242
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006243 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006244 setPointerCaptureLocked(false);
6245 }
6246
6247 if (!mWindowTokenWithPointerCapture) {
6248 // No need to send capture changes because no window has capture.
6249 return;
6250 }
6251
6252 if (mPendingEvent != nullptr) {
6253 // Move the pending event to the front of the queue. This will give the chance
6254 // for the pending event to be dropped if it is a captured event.
6255 mInboundQueue.push_front(mPendingEvent);
6256 mPendingEvent = nullptr;
6257 }
6258
6259 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006260 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006261 mInboundQueue.push_front(std::move(entry));
6262}
6263
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006264void InputDispatcher::setPointerCaptureLocked(bool enable) {
6265 mCurrentPointerCaptureRequest.enable = enable;
6266 mCurrentPointerCaptureRequest.seq++;
6267 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006268 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006269 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006270 };
6271 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006272}
6273
Vishnu Nair599f1412021-06-21 10:39:58 -07006274void InputDispatcher::displayRemoved(int32_t displayId) {
6275 { // acquire lock
6276 std::scoped_lock _l(mLock);
6277 // Set an empty list to remove all handles from the specific display.
6278 setInputWindowsLocked(/* window handles */ {}, displayId);
6279 setFocusedApplicationLocked(displayId, nullptr);
6280 // Call focus resolver to clean up stale requests. This must be called after input windows
6281 // have been removed for the removed display.
6282 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006283 // Reset pointer capture eligibility, regardless of previous state.
6284 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006285 } // release lock
6286
6287 // Wake up poll loop since it may need to make new input dispatching choices.
6288 mLooper->wake();
6289}
6290
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006291void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6292 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006293 // The listener sends the windows as a flattened array. Separate the windows by display for
6294 // more convenient parsing.
6295 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006296 for (const auto& info : windowInfos) {
6297 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6298 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6299 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006300
6301 { // acquire lock
6302 std::scoped_lock _l(mLock);
6303 mDisplayInfos.clear();
6304 for (const auto& displayInfo : displayInfos) {
6305 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6306 }
6307
6308 for (const auto& [displayId, handles] : handlesPerDisplay) {
6309 setInputWindowsLocked(handles, displayId);
6310 }
6311 }
6312 // Wake up poll loop since it may need to make new input dispatching choices.
6313 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006314}
6315
Vishnu Nair062a8672021-09-03 16:07:44 -07006316bool InputDispatcher::shouldDropInput(
6317 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006318 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6319 (windowHandle->getInfo()->inputConfig.test(
6320 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006321 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006322 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6323 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006324 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006325 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006326 windowHandle->getInfo()->displayId);
6327 return true;
6328 }
6329 return false;
6330}
6331
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006332void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6333 const std::vector<gui::WindowInfo>& windowInfos,
6334 const std::vector<DisplayInfo>& displayInfos) {
6335 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6336}
6337
Arthur Hungdfd528e2021-12-08 13:23:04 +00006338void InputDispatcher::cancelCurrentTouch() {
6339 {
6340 std::scoped_lock _l(mLock);
6341 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6342 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6343 "cancel current touch");
6344 synthesizeCancelationEventsForAllConnectionsLocked(options);
6345
6346 mTouchStatesByDisplay.clear();
6347 mLastHoverWindowHandle.clear();
6348 }
6349 // Wake up poll loop since there might be work to do.
6350 mLooper->wake();
6351}
6352
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006353void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6354 std::scoped_lock _l(mLock);
6355 mMonitorDispatchingTimeout = timeout;
6356}
6357
Garfield Tane84e6f92019-08-29 17:28:41 -07006358} // namespace android::inputdispatcher